Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/util/mutexlock.h
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
#ifndef STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_
#define STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_
#include "port/port_posix.h"
#include "port/thread_annotations.h"
namespace leveldb
{
// Helper class that locks a mutex on construction and unlocks the mutex when
// the destructor of the MutexLock object is invoked.
//
// Typical usage:
//
// void MyClass::MyMethod() {
// MutexLock l(&mu_); // mu_ is an instance variable
// ... some complex code, possibly with multiple return paths ...
// }
class SCOPED_LOCKABLE MutexLock {
public:
explicit MutexLock(port::Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu)
{
this->mu_->Lock();
}
~MutexLock() UNLOCK_FUNCTION()
{
this->mu_->Unlock();
}
private:
port::Mutex *const mu_;
// No copying allowed
MutexLock(const MutexLock &);
void operator=(const MutexLock &);
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_
| 1,202 | 24.0625 | 81 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/util/histogram.h
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2017-2020, Intel Corporation
#ifndef STORAGE_LEVELDB_UTIL_HISTOGRAM_H_
#define STORAGE_LEVELDB_UTIL_HISTOGRAM_H_
#include <string>
namespace leveldb
{
class Histogram {
public:
Histogram()
{
}
~Histogram()
{
}
void Clear();
void Add(double value);
void Merge(const Histogram &other);
std::string ToString() const;
double Median() const;
double Percentile(double p) const;
double Average() const;
double StandardDeviation() const;
private:
double min_;
double max_;
double num_;
double sum_;
double sum_squares_;
enum { kNumBuckets = 154 };
static const double kBucketLimit[kNumBuckets];
double buckets_[kNumBuckets];
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_HISTOGRAM_H_
| 993 | 18.490196 | 81 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/util/testutil.cc
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
#include "util/testutil.h"
#include "util/random.h"
namespace leveldb
{
namespace test
{
Slice RandomString(Random *rnd, int len, std::string *dst)
{
dst->resize(len);
for (int i = 0; i < len; i++) {
(*dst)[i] = static_cast<char>(' ' + rnd->Uniform(95)); // ' ' .. '~'
}
return Slice(*dst);
}
std::string RandomKey(Random *rnd, int len)
{
// Make sure to generate a wide variety of characters so we
// test the boundary conditions for short-key optimizations.
static const char kTestChars[] = {'\0', '\1', 'a', 'b', 'c', 'd', 'e', '\xfd', '\xfe', '\xff'};
std::string result;
for (int i = 0; i < len; i++) {
result += kTestChars[rnd->Uniform(sizeof(kTestChars))];
}
return result;
}
Slice CompressibleString(Random *rnd, double compressed_fraction, size_t len, std::string *dst)
{
int raw = static_cast<int>(len * compressed_fraction);
if (raw < 1)
raw = 1;
std::string raw_data;
RandomString(rnd, raw, &raw_data);
// Duplicate the random data until we have filled "len" bytes
dst->clear();
while (dst->size() < len) {
dst->append(raw_data);
}
dst->resize(len);
return Slice(*dst);
}
} // namespace test
} // namespace leveldb
| 1,384 | 24.648148 | 96 |
cc
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/util/histogram.cc
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
/* Copyright 2020, Intel Corporation */
#include "util/histogram.h"
#include "port/port_posix.h"
#include <math.h>
#include <stdio.h>
namespace leveldb
{
// clang-format off
const double Histogram::kBucketLimit[kNumBuckets] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 25, 30, 35, 40, 45,
50, 60, 70, 80, 90, 100, 120, 140, 160, 180, 200, 250, 300, 350, 400, 450,
500, 600, 700, 800, 900, 1000, 1200, 1400, 1600, 1800, 2000, 2500, 3000,
3500, 4000, 4500, 5000, 6000, 7000, 8000, 9000, 10000, 12000, 14000,
16000, 18000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 60000,
70000, 80000, 90000, 100000, 120000, 140000, 160000, 180000, 200000,
250000, 300000, 350000, 400000, 450000, 500000, 600000, 700000, 800000,
900000, 1000000, 1200000, 1400000, 1600000, 1800000, 2000000, 2500000,
3000000, 3500000, 4000000, 4500000, 5000000, 6000000, 7000000, 8000000,
9000000, 10000000, 12000000, 14000000, 16000000, 18000000, 20000000,
25000000, 30000000, 35000000, 40000000, 45000000, 50000000, 60000000,
70000000, 80000000, 90000000, 100000000, 120000000, 140000000, 160000000,
180000000, 200000000, 250000000, 300000000, 350000000, 400000000,
450000000, 500000000, 600000000, 700000000, 800000000, 900000000,
1000000000, 1200000000, 1400000000, 1600000000, 1800000000, 2000000000,
2500000000.0, 3000000000.0, 3500000000.0, 4000000000.0, 4500000000.0,
5000000000.0, 6000000000.0, 7000000000.0, 8000000000.0, 9000000000.0,
1e200,
};
// clang-format on
void Histogram::Clear()
{
min_ = kBucketLimit[kNumBuckets - 1];
max_ = 0;
num_ = 0;
sum_ = 0;
sum_squares_ = 0;
for (int i = 0; i < kNumBuckets; i++) {
buckets_[i] = 0;
}
}
void Histogram::Add(double value)
{
// Linear search is fast enough for our usage in db_bench
int b = 0;
while (b < kNumBuckets - 1 && kBucketLimit[b] <= value) {
b++;
}
buckets_[b] += 1.0;
if (min_ > value)
min_ = value;
if (max_ < value)
max_ = value;
num_++;
sum_ += value;
sum_squares_ += (value * value);
}
void Histogram::Merge(const Histogram &other)
{
if (other.min_ < min_)
min_ = other.min_;
if (other.max_ > max_)
max_ = other.max_;
num_ += other.num_;
sum_ += other.sum_;
sum_squares_ += other.sum_squares_;
for (int b = 0; b < kNumBuckets; b++) {
buckets_[b] += other.buckets_[b];
}
}
double Histogram::Median() const
{
return Percentile(50.0);
}
double Histogram::Percentile(double p) const
{
double threshold = num_ * (p / 100.0);
double sum = 0;
for (int b = 0; b < kNumBuckets; b++) {
sum += buckets_[b];
if (sum >= threshold) {
// Scale linearly within this bucket
double left_point = (b == 0) ? 0 : kBucketLimit[b - 1];
double right_point = kBucketLimit[b];
double left_sum = sum - buckets_[b];
double right_sum = sum;
double pos = (threshold - left_sum) / (right_sum - left_sum);
double r = left_point + (right_point - left_point) * pos;
if (r < min_)
r = min_;
if (r > max_)
r = max_;
return r;
}
}
return max_;
}
double Histogram::Average() const
{
if (num_ == 0.0)
return 0;
return sum_ / num_;
}
double Histogram::StandardDeviation() const
{
if (num_ == 0.0)
return 0;
double variance = (sum_squares_ * num_ - sum_ * sum_) / (num_ * num_);
return sqrt(variance);
}
std::string Histogram::ToString() const
{
std::string r;
char buf[200];
snprintf(buf, sizeof(buf), "Count: %.0f Average: %.4f StdDev: %.2f\n", num_, Average(),
StandardDeviation());
r.append(buf);
snprintf(buf, sizeof(buf), "Min: %.4f Median: %.4f Max: %.4f\n", (num_ == 0.0 ? 0.0 : min_),
Median(), max_);
r.append(buf);
snprintf(buf, sizeof(buf), "Percentiles: P50: %.2f P75: %.2f P99: %.2f P99.9: %.2f P99.99: %.2f\n",
Percentile(50), Percentile(75), Percentile(99), Percentile(99.9), Percentile(99.99));
r.append(buf);
r.append("------------------------------------------------------\n");
const double mult = 100.0 / num_;
double sum = 0;
for (int b = 0; b < kNumBuckets; b++) {
if (buckets_[b] <= 0.0)
continue;
sum += buckets_[b];
snprintf(buf, sizeof(buf), "[ %7.0f, %7.0f ) %7.0f %7.3f%% %7.3f%% ",
((b == 0) ? 0.0 : kBucketLimit[b - 1]), // left
kBucketLimit[b], // right
buckets_[b], // count
mult * buckets_[b], // percentage
mult * sum); // cumulative percentage
r.append(buf);
// Add hash marks based on percentage; 20 marks for 100%.
int marks = static_cast<int>(20 * (buckets_[b] / num_) + 0.5);
r.append(marks, '#');
r.push_back('\n');
}
return r;
}
} // namespace leveldb
| 4,793 | 28.411043 | 100 |
cc
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/util/env_posix.cc
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
/* Copyright 2020, Intel Corporation */
#include <deque>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits>
#include <pthread.h>
#include <set>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "leveldb/env.h"
#include "leveldb/slice.h"
#include "port/port_posix.h"
#include "util/env_posix_test_helper.h"
#include "util/logging.h"
#include "util/mutexlock.h"
#include "util/posix_logger.h"
namespace leveldb
{
namespace
{
static int open_read_only_file_limit = -1;
static int mmap_limit = -1;
static const size_t kBufSize = 65536;
static Status PosixError(const std::string &context, int err_number)
{
if (err_number == ENOENT) {
return Status::NotFound(context, strerror(err_number));
} else {
return Status::IOError(context, strerror(err_number));
}
}
// Helper class to limit resource usage to avoid exhaustion.
// Currently used to limit read-only file descriptors and mmap file usage
// so that we do not end up running out of file descriptors, virtual memory,
// or running into kernel performance problems for very large databases.
class Limiter {
public:
// Limit maximum number of resources to |n|.
Limiter(intptr_t n)
{
SetAllowed(n);
}
// If another resource is available, acquire it and return true.
// Else return false.
bool Acquire()
{
if (GetAllowed() <= 0) {
return false;
}
MutexLock l(&mu_);
intptr_t x = GetAllowed();
if (x <= 0) {
return false;
} else {
SetAllowed(x - 1);
return true;
}
}
// Release a resource acquired by a previous call to Acquire() that returned
// true.
void Release()
{
MutexLock l(&mu_);
SetAllowed(GetAllowed() + 1);
}
private:
port::Mutex mu_;
port::AtomicPointer allowed_;
intptr_t GetAllowed() const
{
return reinterpret_cast<intptr_t>(allowed_.Acquire_Load());
}
// REQUIRES: mu_ must be held
void SetAllowed(intptr_t v)
{
allowed_.Release_Store(reinterpret_cast<void *>(v));
}
Limiter(const Limiter &);
void operator=(const Limiter &);
};
class PosixSequentialFile : public SequentialFile {
private:
std::string filename_;
int fd_;
public:
PosixSequentialFile(const std::string &fname, int fd) : filename_(fname), fd_(fd)
{
}
virtual ~PosixSequentialFile()
{
close(fd_);
}
virtual Status Read(size_t n, Slice *result, char *scratch)
{
Status s;
while (true) {
ssize_t r = read(fd_, scratch, n);
if (r < 0) {
if (errno == EINTR) {
continue; // Retry
}
s = PosixError(filename_, errno);
break;
}
*result = Slice(scratch, r);
break;
}
return s;
}
virtual Status Skip(uint64_t n)
{
if (lseek(fd_, n, SEEK_CUR) == static_cast<off_t>(-1)) {
return PosixError(filename_, errno);
}
return Status::OK();
}
};
// pread() based random-access
class PosixRandomAccessFile : public RandomAccessFile {
private:
std::string filename_;
bool temporary_fd_; // If true, fd_ is -1 and we open on every read.
int fd_;
Limiter *limiter_;
public:
PosixRandomAccessFile(const std::string &fname, int fd, Limiter *limiter)
: filename_(fname), fd_(fd), limiter_(limiter)
{
temporary_fd_ = !limiter->Acquire();
if (temporary_fd_) {
// Open file on every access.
close(fd_);
fd_ = -1;
}
}
virtual ~PosixRandomAccessFile()
{
if (!temporary_fd_) {
close(fd_);
limiter_->Release();
}
}
virtual Status Read(uint64_t offset, size_t n, Slice *result, char *scratch) const
{
int fd = fd_;
if (temporary_fd_) {
fd = open(filename_.c_str(), O_RDONLY);
if (fd < 0) {
return PosixError(filename_, errno);
}
}
Status s;
ssize_t r = pread(fd, scratch, n, static_cast<off_t>(offset));
*result = Slice(scratch, (r < 0) ? 0 : r);
if (r < 0) {
// An error: return a non-ok status
s = PosixError(filename_, errno);
}
if (temporary_fd_) {
// Close the temporary file descriptor opened earlier.
close(fd);
}
return s;
}
};
// mmap() based random-access
class PosixMmapReadableFile : public RandomAccessFile {
private:
std::string filename_;
void *mmapped_region_;
size_t length_;
Limiter *limiter_;
public:
// base[0,length-1] contains the mmapped contents of the file.
PosixMmapReadableFile(const std::string &fname, void *base, size_t length, Limiter *limiter)
: filename_(fname), mmapped_region_(base), length_(length), limiter_(limiter)
{
}
virtual ~PosixMmapReadableFile()
{
munmap(mmapped_region_, length_);
limiter_->Release();
}
virtual Status Read(uint64_t offset, size_t n, Slice *result, char *scratch) const
{
Status s;
if (offset + n > length_) {
*result = Slice();
s = PosixError(filename_, EINVAL);
} else {
*result = Slice(reinterpret_cast<char *>(mmapped_region_) + offset, n);
}
return s;
}
};
class PosixWritableFile : public WritableFile {
private:
// buf_[0, pos_-1] contains data to be written to fd_.
std::string filename_;
int fd_;
char buf_[kBufSize];
size_t pos_;
public:
PosixWritableFile(const std::string &fname, int fd) : filename_(fname), fd_(fd), pos_(0)
{
}
~PosixWritableFile()
{
if (fd_ >= 0) {
// Ignoring any potential errors
Close();
}
}
virtual Status Append(const Slice &data)
{
size_t n = data.size();
const char *p = data.data();
// Fit as much as possible into buffer.
size_t copy = std::min(n, kBufSize - pos_);
memcpy(buf_ + pos_, p, copy);
p += copy;
n -= copy;
pos_ += copy;
if (n == 0) {
return Status::OK();
}
// Can't fit in buffer, so need to do at least one write.
Status s = FlushBuffered();
if (!s.ok()) {
return s;
}
// Small writes go to buffer, large writes are written directly.
if (n < kBufSize) {
memcpy(buf_, p, n);
pos_ = n;
return Status::OK();
}
return WriteRaw(p, n);
}
virtual Status Close()
{
Status result = FlushBuffered();
const int r = close(fd_);
if (r < 0 && result.ok()) {
result = PosixError(filename_, errno);
}
fd_ = -1;
return result;
}
virtual Status Flush()
{
return FlushBuffered();
}
Status SyncDirIfManifest()
{
const char *f = filename_.c_str();
const char *sep = strrchr(f, '/');
Slice basename;
std::string dir;
if (sep == NULL) {
dir = ".";
basename = f;
} else {
dir = std::string(f, sep - f);
basename = sep + 1;
}
Status s;
if (basename.starts_with("MANIFEST")) {
int fd = open(dir.c_str(), O_RDONLY);
if (fd < 0) {
s = PosixError(dir, errno);
} else {
if (fsync(fd) < 0) {
s = PosixError(dir, errno);
}
close(fd);
}
}
return s;
}
virtual Status Sync()
{
// Ensure new files referred to by the manifest are in the filesystem.
Status s = SyncDirIfManifest();
if (!s.ok()) {
return s;
}
s = FlushBuffered();
if (s.ok()) {
if (fdatasync(fd_) != 0) {
s = PosixError(filename_, errno);
}
}
return s;
}
private:
Status FlushBuffered()
{
Status s = WriteRaw(buf_, pos_);
pos_ = 0;
return s;
}
Status WriteRaw(const char *p, size_t n)
{
while (n > 0) {
ssize_t r = write(fd_, p, n);
if (r < 0) {
if (errno == EINTR) {
continue; // Retry
}
return PosixError(filename_, errno);
}
p += r;
n -= r;
}
return Status::OK();
}
};
static int LockOrUnlock(int fd, bool lock)
{
errno = 0;
struct flock f;
memset(&f, 0, sizeof(f));
f.l_type = (lock ? F_WRLCK : F_UNLCK);
f.l_whence = SEEK_SET;
f.l_start = 0;
f.l_len = 0; // Lock/unlock entire file
return fcntl(fd, F_SETLK, &f);
}
class PosixFileLock : public FileLock {
public:
int fd_;
std::string name_;
};
// Set of locked files. We keep a separate set instead of just
// relying on fcntrl(F_SETLK) since fcntl(F_SETLK) does not provide
// any protection against multiple uses from the same process.
class PosixLockTable {
private:
port::Mutex mu_;
std::set<std::string> locked_files_;
public:
bool Insert(const std::string &fname)
{
MutexLock l(&mu_);
return locked_files_.insert(fname).second;
}
void Remove(const std::string &fname)
{
MutexLock l(&mu_);
locked_files_.erase(fname);
}
};
class PosixEnv : public Env {
public:
PosixEnv();
virtual ~PosixEnv()
{
char msg[] = "Destroying Env::Default()\n";
fwrite(msg, 1, sizeof(msg), stderr);
abort();
}
virtual Status NewSequentialFile(const std::string &fname, SequentialFile **result)
{
int fd = open(fname.c_str(), O_RDONLY);
if (fd < 0) {
*result = NULL;
return PosixError(fname, errno);
} else {
*result = new PosixSequentialFile(fname, fd);
return Status::OK();
}
}
virtual Status NewRandomAccessFile(const std::string &fname, RandomAccessFile **result)
{
*result = NULL;
Status s;
int fd = open(fname.c_str(), O_RDONLY);
if (fd < 0) {
s = PosixError(fname, errno);
} else if (mmap_limit_.Acquire()) {
uint64_t size;
s = GetFileSize(fname, &size);
if (s.ok()) {
void *base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
if (base != MAP_FAILED) {
*result = new PosixMmapReadableFile(fname, base, size, &mmap_limit_);
} else {
s = PosixError(fname, errno);
}
}
close(fd);
if (!s.ok()) {
mmap_limit_.Release();
}
} else {
*result = new PosixRandomAccessFile(fname, fd, &fd_limit_);
}
return s;
}
virtual Status NewWritableFile(const std::string &fname, WritableFile **result)
{
Status s;
int fd = open(fname.c_str(), O_TRUNC | O_WRONLY | O_CREAT, 0644);
if (fd < 0) {
*result = NULL;
s = PosixError(fname, errno);
} else {
*result = new PosixWritableFile(fname, fd);
}
return s;
}
virtual Status NewAppendableFile(const std::string &fname, WritableFile **result)
{
Status s;
int fd = open(fname.c_str(), O_APPEND | O_WRONLY | O_CREAT, 0644);
if (fd < 0) {
*result = NULL;
s = PosixError(fname, errno);
} else {
*result = new PosixWritableFile(fname, fd);
}
return s;
}
virtual bool FileExists(const std::string &fname)
{
return access(fname.c_str(), F_OK) == 0;
}
virtual Status GetChildren(const std::string &dir, std::vector<std::string> *result)
{
result->clear();
DIR *d = opendir(dir.c_str());
if (d == NULL) {
return PosixError(dir, errno);
}
struct dirent *entry;
while ((entry = readdir(d)) != NULL) {
result->push_back(entry->d_name);
}
closedir(d);
return Status::OK();
}
virtual Status DeleteFile(const std::string &fname)
{
Status result;
if (unlink(fname.c_str()) != 0) {
result = PosixError(fname, errno);
}
return result;
}
virtual Status CreateDir(const std::string &name)
{
Status result;
if (mkdir(name.c_str(), 0755) != 0) {
result = PosixError(name, errno);
}
return result;
}
virtual Status DeleteDir(const std::string &name)
{
Status result;
if (rmdir(name.c_str()) != 0) {
result = PosixError(name, errno);
}
return result;
}
virtual Status GetFileSize(const std::string &fname, uint64_t *size)
{
Status s;
struct stat sbuf;
if (stat(fname.c_str(), &sbuf) != 0) {
*size = 0;
s = PosixError(fname, errno);
} else {
*size = sbuf.st_size;
}
return s;
}
virtual Status RenameFile(const std::string &src, const std::string &target)
{
Status result;
if (rename(src.c_str(), target.c_str()) != 0) {
result = PosixError(src, errno);
}
return result;
}
virtual Status LockFile(const std::string &fname, FileLock **lock)
{
*lock = NULL;
Status result;
int fd = open(fname.c_str(), O_RDWR | O_CREAT, 0644);
if (fd < 0) {
result = PosixError(fname, errno);
} else if (!locks_.Insert(fname)) {
close(fd);
result = Status::IOError("lock " + fname, "already held by process");
} else if (LockOrUnlock(fd, true) == -1) {
result = PosixError("lock " + fname, errno);
close(fd);
locks_.Remove(fname);
} else {
PosixFileLock *my_lock = new PosixFileLock;
my_lock->fd_ = fd;
my_lock->name_ = fname;
*lock = my_lock;
}
return result;
}
virtual Status UnlockFile(FileLock *lock)
{
PosixFileLock *my_lock = reinterpret_cast<PosixFileLock *>(lock);
Status result;
if (LockOrUnlock(my_lock->fd_, false) == -1) {
result = PosixError("unlock", errno);
}
locks_.Remove(my_lock->name_);
close(my_lock->fd_);
delete my_lock;
return result;
}
virtual void Schedule(void (*function)(void *), void *arg);
virtual void StartThread(void (*function)(void *arg), void *arg);
virtual Status GetTestDirectory(std::string *result)
{
const char *env = getenv("TEST_TMPDIR");
if (env && env[0] != '\0') {
*result = env;
} else {
char buf[100];
snprintf(buf, sizeof(buf), "/tmp/leveldbtest-%d", int(geteuid()));
*result = buf;
}
// Directory may already exist
CreateDir(*result);
return Status::OK();
}
static uint64_t gettid()
{
pthread_t tid = pthread_self();
uint64_t thread_id = 0;
memcpy(&thread_id, &tid, std::min(sizeof(thread_id), sizeof(tid)));
return thread_id;
}
virtual Status NewLogger(const std::string &fname, Logger **result)
{
FILE *f = fopen(fname.c_str(), "w");
if (f == NULL) {
*result = NULL;
return PosixError(fname, errno);
} else {
*result = new PosixLogger(f, &PosixEnv::gettid);
return Status::OK();
}
}
virtual uint64_t NowMicros()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
}
virtual void SleepForMicroseconds(int micros)
{
usleep(micros);
}
private:
void PthreadCall(const char *label, int result)
{
if (result != 0) {
fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
abort();
}
}
// BGThread() is the body of the background thread
void BGThread();
static void *BGThreadWrapper(void *arg)
{
reinterpret_cast<PosixEnv *>(arg)->BGThread();
return NULL;
}
pthread_mutex_t mu_;
pthread_cond_t bgsignal_;
pthread_t bgthread_;
bool started_bgthread_;
// Entry per Schedule() call
struct BGItem {
void *arg;
void (*function)(void *);
};
typedef std::deque<BGItem> BGQueue;
BGQueue queue_;
PosixLockTable locks_;
Limiter mmap_limit_;
Limiter fd_limit_;
};
// Return the maximum number of concurrent mmaps.
static int MaxMmaps()
{
if (mmap_limit >= 0) {
return mmap_limit;
}
// Up to 1000 mmaps for 64-bit binaries; none for smaller pointer sizes.
mmap_limit = sizeof(void *) >= 8 ? 1000 : 0;
return mmap_limit;
}
// Return the maximum number of read-only files to keep open.
static intptr_t MaxOpenFiles()
{
if (open_read_only_file_limit >= 0) {
return open_read_only_file_limit;
}
struct rlimit rlim;
if (getrlimit(RLIMIT_NOFILE, &rlim)) {
// getrlimit failed, fallback to hard-coded default.
open_read_only_file_limit = 50;
} else if (rlim.rlim_cur == RLIM_INFINITY) {
open_read_only_file_limit = std::numeric_limits<int>::max();
} else {
// Allow use of 20% of available file descriptors for read-only files.
open_read_only_file_limit = rlim.rlim_cur / 5;
}
return open_read_only_file_limit;
}
PosixEnv::PosixEnv() : started_bgthread_(false), mmap_limit_(MaxMmaps()), fd_limit_(MaxOpenFiles())
{
PthreadCall("mutex_init", pthread_mutex_init(&mu_, NULL));
PthreadCall("cvar_init", pthread_cond_init(&bgsignal_, NULL));
}
void PosixEnv::Schedule(void (*function)(void *), void *arg)
{
PthreadCall("lock", pthread_mutex_lock(&mu_));
// Start background thread if necessary
if (!started_bgthread_) {
started_bgthread_ = true;
PthreadCall("create thread",
pthread_create(&bgthread_, NULL, &PosixEnv::BGThreadWrapper, this));
}
// If the queue is currently empty, the background thread may currently be
// waiting.
if (queue_.empty()) {
PthreadCall("signal", pthread_cond_signal(&bgsignal_));
}
// Add to priority queue
queue_.push_back(BGItem());
queue_.back().function = function;
queue_.back().arg = arg;
PthreadCall("unlock", pthread_mutex_unlock(&mu_));
}
void PosixEnv::BGThread()
{
while (true) {
// Wait until there is an item that is ready to run
PthreadCall("lock", pthread_mutex_lock(&mu_));
while (queue_.empty()) {
PthreadCall("wait", pthread_cond_wait(&bgsignal_, &mu_));
}
void (*function)(void *) = queue_.front().function;
void *arg = queue_.front().arg;
queue_.pop_front();
PthreadCall("unlock", pthread_mutex_unlock(&mu_));
(*function)(arg);
}
}
namespace
{
struct StartThreadState {
void (*user_function)(void *);
void *arg;
};
}
static void *StartThreadWrapper(void *arg)
{
StartThreadState *state = reinterpret_cast<StartThreadState *>(arg);
state->user_function(state->arg);
delete state;
return NULL;
}
void PosixEnv::StartThread(void (*function)(void *arg), void *arg)
{
pthread_t t;
StartThreadState *state = new StartThreadState;
state->user_function = function;
state->arg = arg;
PthreadCall("start thread", pthread_create(&t, NULL, &StartThreadWrapper, state));
}
} // namespace
static pthread_once_t once = PTHREAD_ONCE_INIT;
static Env *default_env;
static void InitDefaultEnv()
{
default_env = new PosixEnv;
}
void EnvPosixTestHelper::SetReadOnlyFDLimit(int limit)
{
assert(default_env == NULL);
open_read_only_file_limit = limit;
}
void EnvPosixTestHelper::SetReadOnlyMMapLimit(int limit)
{
assert(default_env == NULL);
mmap_limit = limit;
}
Env *Env::Default()
{
pthread_once(&once, InitDefaultEnv);
return default_env;
}
} // namespace leveldb
| 17,689 | 20.812577 | 99 |
cc
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/util/random.h
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
#ifndef STORAGE_LEVELDB_UTIL_RANDOM_H_
#define STORAGE_LEVELDB_UTIL_RANDOM_H_
#include <stdint.h>
namespace leveldb
{
// A very simple random number generator. Not especially good at
// generating truly random bits, but good enough for our needs in this
// package.
class Random {
private:
uint32_t seed_;
public:
explicit Random(uint32_t s) : seed_(s & 0x7fffffffu)
{
// Avoid bad seeds.
if (seed_ == 0 || seed_ == 2147483647L) {
seed_ = 1;
}
}
uint32_t Next()
{
static const uint32_t M = 2147483647L; // 2^31-1
static const uint64_t A = 16807; // bits 14, 8, 7, 5, 2, 1, 0
// We are computing
// seed_ = (seed_ * A) % M, where M = 2^31-1
//
// seed_ must not be zero or M, or else all subsequent computed values
// will be zero or M respectively. For all other values, seed_ will end
// up cycling through every number in [1,M-1]
uint64_t product = seed_ * A;
// Compute (product % M) using the fact that ((x << 31) % M) == x.
seed_ = static_cast<uint32_t>((product >> 31) + (product & M));
// The first reduction may overflow by 1 bit, so we may need to
// repeat. mod == M is not possible; using > allows the faster
// sign-bit-based test.
if (seed_ > M) {
seed_ -= M;
}
return seed_;
}
// Returns a uniformly distributed value in the range [0..n-1]
// REQUIRES: n > 0
uint32_t Uniform(int n)
{
return Next() % n;
}
// Randomly returns true ~"1/n" of the time, and false otherwise.
// REQUIRES: n > 0
bool OneIn(int n)
{
return (Next() % n) == 0;
}
// Skewed: pick "base" uniformly from range [0,max_log] and then
// return "base" random bits. The effect is to pick a number in the
// range [0,2^max_log-1] with exponential bias towards smaller numbers.
uint32_t Skewed(int max_log)
{
return Uniform(1 << Uniform(max_log + 1));
}
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_RANDOM_H_
| 2,202 | 26.886076 | 81 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/util/posix_logger.h
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
//
// Logger implementation that can be shared by all environments
// where enough posix functionality is available.
#ifndef STORAGE_LEVELDB_UTIL_POSIX_LOGGER_H_
#define STORAGE_LEVELDB_UTIL_POSIX_LOGGER_H_
#include "leveldb/env.h"
#include <algorithm>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
namespace leveldb
{
class PosixLogger : public Logger {
private:
FILE *file_;
uint64_t (*gettid_)(); // Return the thread id for the current thread
public:
PosixLogger(FILE *f, uint64_t (*gettid)()) : file_(f), gettid_(gettid)
{
}
virtual ~PosixLogger()
{
fclose(file_);
}
virtual void Logv(const char *format, va_list ap)
{
const uint64_t thread_id = (*gettid_)();
// We try twice: the first time with a fixed-size stack allocated buffer,
// and the second time with a much larger dynamically allocated buffer.
char buffer[500];
for (int iter = 0; iter < 2; iter++) {
char *base;
int bufsize;
if (iter == 0) {
bufsize = sizeof(buffer);
base = buffer;
} else {
bufsize = 30000;
base = new char[bufsize];
}
char *p = base;
char *limit = base + bufsize;
struct timeval now_tv;
gettimeofday(&now_tv, NULL);
const time_t seconds = now_tv.tv_sec;
struct tm t;
localtime_r(&seconds, &t);
p += snprintf(p, limit - p, "%04d/%02d/%02d-%02d:%02d:%02d.%06d %llx ",
t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min,
t.tm_sec, static_cast<int>(now_tv.tv_usec),
static_cast<long long unsigned int>(thread_id));
// Print the message
if (p < limit) {
va_list backup_ap;
va_copy(backup_ap, ap);
p += vsnprintf(p, limit - p, format, backup_ap);
va_end(backup_ap);
}
// Truncate to available space if necessary
if (p >= limit) {
if (iter == 0) {
continue; // Try again with larger buffer
} else {
p = limit - 1;
}
}
// Add newline if necessary
if (p == base || p[-1] != '\n') {
*p++ = '\n';
}
assert(p <= limit);
fwrite(base, 1, p - base, file_);
fflush(file_);
if (base != buffer) {
delete[] base;
}
break;
}
}
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_POSIX_LOGGER_H_
| 2,503 | 23.54902 | 81 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/util/env_posix_test_helper.h
|
// Copyright 2017 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
#ifndef STORAGE_LEVELDB_UTIL_ENV_POSIX_TEST_HELPER_H_
#define STORAGE_LEVELDB_UTIL_ENV_POSIX_TEST_HELPER_H_
namespace leveldb
{
class EnvPosixTest;
// A helper for the POSIX Env to facilitate testing.
class EnvPosixTestHelper {
private:
friend class EnvPosixTest;
// Set the maximum number of read-only files that will be opened.
// Must be called before creating an Env.
static void SetReadOnlyFDLimit(int limit);
// Set the maximum number of read-only files that will be mapped via mmap.
// Must be called before creating an Env.
static void SetReadOnlyMMapLimit(int limit);
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_ENV_POSIX_TEST_HELPER_H_
| 967 | 28.333333 | 81 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/port/port_posix.h
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
// See port_example.h for documentation for the following types/functions.
#ifndef STORAGE_LEVELDB_PORT_PORT_POSIX_H_
#define STORAGE_LEVELDB_PORT_PORT_POSIX_H_
#undef PLATFORM_IS_LITTLE_ENDIAN
#if defined(__APPLE__)
#include <machine/endian.h>
#if defined(__DARWIN_LITTLE_ENDIAN) && defined(__DARWIN_BYTE_ORDER)
#define PLATFORM_IS_LITTLE_ENDIAN (__DARWIN_BYTE_ORDER == __DARWIN_LITTLE_ENDIAN)
#endif
#elif defined(OS_SOLARIS)
#include <sys/isa_defs.h>
#ifdef _LITTLE_ENDIAN
#define PLATFORM_IS_LITTLE_ENDIAN true
#else
#define PLATFORM_IS_LITTLE_ENDIAN false
#endif
#elif defined(OS_FREEBSD) || defined(OS_OPENBSD) || defined(OS_NETBSD) || defined(OS_DRAGONFLYBSD)
#include <sys/endian.h>
#include <sys/types.h>
#define PLATFORM_IS_LITTLE_ENDIAN (_BYTE_ORDER == _LITTLE_ENDIAN)
#elif defined(OS_HPUX)
#define PLATFORM_IS_LITTLE_ENDIAN false
#elif defined(OS_ANDROID)
// Due to a bug in the NDK x86 <sys/endian.h> definition,
// _BYTE_ORDER must be used instead of __BYTE_ORDER on Android.
// See http://code.google.com/p/android/issues/detail?id=39824
#include <endian.h>
#define PLATFORM_IS_LITTLE_ENDIAN (_BYTE_ORDER == _LITTLE_ENDIAN)
#else
#include <endian.h>
#endif
#include <pthread.h>
#if defined(HAVE_CRC32C)
#include <crc32c/crc32c.h>
#endif // defined(HAVE_CRC32C)
#ifdef HAVE_SNAPPY
#include <snappy.h>
#endif // defined(HAVE_SNAPPY)
#include "port/atomic_pointer.h"
#include <stdint.h>
#include <string>
#ifndef PLATFORM_IS_LITTLE_ENDIAN
#define PLATFORM_IS_LITTLE_ENDIAN (__BYTE_ORDER == __LITTLE_ENDIAN)
#endif
#if defined(__APPLE__) || defined(OS_FREEBSD) || defined(OS_OPENBSD) || defined(OS_DRAGONFLYBSD)
// Use fsync() on platforms without fdatasync()
#define fdatasync fsync
#endif
#if defined(OS_ANDROID) && __ANDROID_API__ < 9
// fdatasync() was only introduced in API level 9 on Android. Use fsync()
// when targetting older platforms.
#define fdatasync fsync
#endif
namespace leveldb
{
namespace port
{
static const bool kLittleEndian = PLATFORM_IS_LITTLE_ENDIAN;
#undef PLATFORM_IS_LITTLE_ENDIAN
class CondVar;
class Mutex {
public:
Mutex();
~Mutex();
void Lock();
void Unlock();
void AssertHeld()
{
}
private:
friend class CondVar;
pthread_mutex_t mu_;
// No copying
Mutex(const Mutex &);
void operator=(const Mutex &);
};
class CondVar {
public:
explicit CondVar(Mutex *mu);
~CondVar();
void Wait();
void Signal();
void SignalAll();
private:
pthread_cond_t cv_;
Mutex *mu_;
};
typedef pthread_once_t OnceType;
#define LEVELDB_ONCE_INIT PTHREAD_ONCE_INIT
extern void InitOnce(OnceType *once, void (*initializer)());
inline bool Snappy_Compress(const char *input, size_t length, ::std::string *output)
{
#ifdef HAVE_SNAPPY
output->resize(snappy::MaxCompressedLength(length));
size_t outlen;
snappy::RawCompress(input, length, &(*output)[0], &outlen);
output->resize(outlen);
return true;
#endif // defined(HAVE_SNAPPY)
return false;
}
inline bool Snappy_GetUncompressedLength(const char *input, size_t length, size_t *result)
{
#ifdef HAVE_SNAPPY
return snappy::GetUncompressedLength(input, length, result);
#else
return false;
#endif // defined(HAVE_SNAPPY)
}
inline bool Snappy_Uncompress(const char *input, size_t length, char *output)
{
#ifdef HAVE_SNAPPY
return snappy::RawUncompress(input, length, output);
#else
return false;
#endif // defined(HAVE_SNAPPY)
}
inline bool GetHeapProfile(void (*func)(void *, const char *, int), void *arg)
{
return false;
}
inline uint32_t AcceleratedCRC32C(uint32_t crc, const char *buf, size_t size)
{
#if defined(HAVE_CRC32C)
return ::crc32c::Extend(crc, reinterpret_cast<const uint8_t *>(buf), size);
#else
return 0;
#endif // defined(HAVE_CRC32C)
}
} // namespace port
} // namespace leveldb
#endif // STORAGE_LEVELDB_PORT_PORT_POSIX_H_
| 4,061 | 23.768293 | 98 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/port/port_posix.cc
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
/* Copyright 2020, Intel Corporation */
#include "port/port_posix.h"
#include <cstdlib>
#include <stdio.h>
#include <string.h>
namespace leveldb
{
namespace port
{
static void PthreadCall(const char *label, int result)
{
if (result != 0) {
fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
abort();
}
}
Mutex::Mutex()
{
PthreadCall("init mutex", pthread_mutex_init(&mu_, NULL));
}
Mutex::~Mutex()
{
PthreadCall("destroy mutex", pthread_mutex_destroy(&mu_));
}
void Mutex::Lock()
{
PthreadCall("lock", pthread_mutex_lock(&mu_));
}
void Mutex::Unlock()
{
PthreadCall("unlock", pthread_mutex_unlock(&mu_));
}
CondVar::CondVar(Mutex *mu) : mu_(mu)
{
PthreadCall("init cv", pthread_cond_init(&cv_, NULL));
}
CondVar::~CondVar()
{
PthreadCall("destroy cv", pthread_cond_destroy(&cv_));
}
void CondVar::Wait()
{
PthreadCall("wait", pthread_cond_wait(&cv_, &mu_->mu_));
}
void CondVar::Signal()
{
PthreadCall("signal", pthread_cond_signal(&cv_));
}
void CondVar::SignalAll()
{
PthreadCall("broadcast", pthread_cond_broadcast(&cv_));
}
void InitOnce(OnceType *once, void (*initializer)())
{
PthreadCall("once", pthread_once(once, initializer));
}
} // namespace port
} // namespace leveldb
| 1,484 | 17.797468 | 81 |
cc
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/port/thread_annotations.h
|
// Copyright (c) 2012 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
#ifndef STORAGE_LEVELDB_PORT_THREAD_ANNOTATIONS_H_
#define STORAGE_LEVELDB_PORT_THREAD_ANNOTATIONS_H_
// Some environments provide custom macros to aid in static thread-safety
// analysis. Provide empty definitions of such macros unless they are already
// defined.
#ifndef EXCLUSIVE_LOCKS_REQUIRED
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#endif
#ifndef SHARED_LOCKS_REQUIRED
#define SHARED_LOCKS_REQUIRED(...)
#endif
#ifndef LOCKS_EXCLUDED
#define LOCKS_EXCLUDED(...)
#endif
#ifndef LOCK_RETURNED
#define LOCK_RETURNED(x)
#endif
#ifndef LOCKABLE
#define LOCKABLE
#endif
#ifndef SCOPED_LOCKABLE
#define SCOPED_LOCKABLE
#endif
#ifndef EXCLUSIVE_LOCK_FUNCTION
#define EXCLUSIVE_LOCK_FUNCTION(...)
#endif
#ifndef SHARED_LOCK_FUNCTION
#define SHARED_LOCK_FUNCTION(...)
#endif
#ifndef EXCLUSIVE_TRYLOCK_FUNCTION
#define EXCLUSIVE_TRYLOCK_FUNCTION(...)
#endif
#ifndef SHARED_TRYLOCK_FUNCTION
#define SHARED_TRYLOCK_FUNCTION(...)
#endif
#ifndef UNLOCK_FUNCTION
#define UNLOCK_FUNCTION(...)
#endif
#ifndef NO_THREAD_SAFETY_ANALYSIS
#define NO_THREAD_SAFETY_ANALYSIS
#endif
#endif // STORAGE_LEVELDB_PORT_THREAD_ANNOTATIONS_H_
| 1,429 | 21.34375 | 81 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/port/atomic_pointer.h
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
// AtomicPointer provides storage for a lock-free pointer.
// Platform-dependent implementation of AtomicPointer:
// - If the platform provides a cheap barrier, we use it with raw pointers
// - If <atomic> is present (on newer versions of gcc, it is), we use
// a <atomic>-based AtomicPointer. However we prefer the memory
// barrier based version, because at least on a gcc 4.4 32-bit build
// on linux, we have encountered a buggy <atomic> implementation.
// Also, some <atomic> implementations are much slower than a memory-barrier
// based implementation (~16ns for <atomic> based acquire-load vs. ~1ns for
// a barrier based acquire-load).
// This code is based on atomicops-internals-* in Google's perftools:
// http://code.google.com/p/google-perftools/source/browse/#svn%2Ftrunk%2Fsrc%2Fbase
#ifndef PORT_ATOMIC_POINTER_H_
#define PORT_ATOMIC_POINTER_H_
#include <stdint.h>
#ifdef LEVELDB_ATOMIC_PRESENT
#include <atomic>
#endif
#ifdef OS_WIN
#include <windows.h>
#endif
#ifdef __APPLE__
#include <libkern/OSAtomic.h>
#endif
#if defined(_M_X64) || defined(__x86_64__)
#define ARCH_CPU_X86_FAMILY 1
#elif defined(_M_IX86) || defined(__i386__) || defined(__i386)
#define ARCH_CPU_X86_FAMILY 1
#elif defined(__ARMEL__)
#define ARCH_CPU_ARM_FAMILY 1
#elif defined(__aarch64__)
#define ARCH_CPU_ARM64_FAMILY 1
#elif defined(__ppc__) || defined(__powerpc__) || defined(__powerpc64__)
#define ARCH_CPU_PPC_FAMILY 1
#elif defined(__mips__)
#define ARCH_CPU_MIPS_FAMILY 1
#endif
namespace leveldb
{
namespace port
{
// Define MemoryBarrier() if available
// Windows on x86
#if defined(OS_WIN) && defined(COMPILER_MSVC) && defined(ARCH_CPU_X86_FAMILY)
// windows.h already provides a MemoryBarrier(void) macro
// http://msdn.microsoft.com/en-us/library/ms684208(v=vs.85).aspx
#define LEVELDB_HAVE_MEMORY_BARRIER
// Mac OS
#elif defined(__APPLE__)
inline void MemoryBarrier()
{
OSMemoryBarrier();
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// Gcc on x86
#elif defined(ARCH_CPU_X86_FAMILY) && defined(__GNUC__)
inline void MemoryBarrier()
{
// See http://gcc.gnu.org/ml/gcc/2003-04/msg01180.html for a discussion on
// this idiom. Also see http://en.wikipedia.org/wiki/Memory_ordering.
__asm__ __volatile__("" : : : "memory");
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// Sun Studio
#elif defined(ARCH_CPU_X86_FAMILY) && defined(__SUNPRO_CC)
inline void MemoryBarrier()
{
// See http://gcc.gnu.org/ml/gcc/2003-04/msg01180.html for a discussion on
// this idiom. Also see http://en.wikipedia.org/wiki/Memory_ordering.
asm volatile("" : : : "memory");
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// ARM Linux
#elif defined(ARCH_CPU_ARM_FAMILY) && defined(__linux__)
typedef void (*LinuxKernelMemoryBarrierFunc)(void);
// The Linux ARM kernel provides a highly optimized device-specific memory
// barrier function at a fixed memory address that is mapped in every
// user-level process.
//
// This beats using CPU-specific instructions which are, on single-core
// devices, un-necessary and very costly (e.g. ARMv7-A "dmb" takes more
// than 180ns on a Cortex-A8 like the one on a Nexus One). Benchmarking
// shows that the extra function call cost is completely negligible on
// multi-core devices.
//
inline void MemoryBarrier()
{
(*(LinuxKernelMemoryBarrierFunc)0xffff0fa0)();
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// ARM64
#elif defined(ARCH_CPU_ARM64_FAMILY)
inline void MemoryBarrier()
{
asm volatile("dmb sy" : : : "memory");
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// PPC
#elif defined(ARCH_CPU_PPC_FAMILY) && defined(__GNUC__)
inline void MemoryBarrier()
{
// TODO for some powerpc expert: is there a cheaper suitable variant?
// Perhaps by having separate barriers for acquire and release ops.
asm volatile("sync" : : : "memory");
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// MIPS
#elif defined(ARCH_CPU_MIPS_FAMILY) && defined(__GNUC__)
inline void MemoryBarrier()
{
__asm__ __volatile__("sync" : : : "memory");
}
#define LEVELDB_HAVE_MEMORY_BARRIER
#endif
// AtomicPointer built using platform-specific MemoryBarrier()
#if defined(LEVELDB_HAVE_MEMORY_BARRIER)
class AtomicPointer {
private:
void *rep_;
public:
AtomicPointer()
{
}
explicit AtomicPointer(void *p) : rep_(p)
{
}
inline void *NoBarrier_Load() const
{
return rep_;
}
inline void NoBarrier_Store(void *v)
{
rep_ = v;
}
inline void *Acquire_Load() const
{
void *result = rep_;
MemoryBarrier();
return result;
}
inline void Release_Store(void *v)
{
MemoryBarrier();
rep_ = v;
}
};
// AtomicPointer based on <cstdatomic>
#elif defined(LEVELDB_ATOMIC_PRESENT)
class AtomicPointer {
private:
std::atomic<void *> rep_;
public:
AtomicPointer()
{
}
explicit AtomicPointer(void *v) : rep_(v)
{
}
inline void *Acquire_Load() const
{
return rep_.load(std::memory_order_acquire);
}
inline void Release_Store(void *v)
{
rep_.store(v, std::memory_order_release);
}
inline void *NoBarrier_Load() const
{
return rep_.load(std::memory_order_relaxed);
}
inline void NoBarrier_Store(void *v)
{
rep_.store(v, std::memory_order_relaxed);
}
};
// Atomic pointer based on sparc memory barriers
#elif defined(__sparcv9) && defined(__GNUC__)
class AtomicPointer {
private:
void *rep_;
public:
AtomicPointer()
{
}
explicit AtomicPointer(void *v) : rep_(v)
{
}
inline void *Acquire_Load() const
{
void *val;
__asm__ __volatile__("ldx [%[rep_]], %[val] \n\t"
"membar #LoadLoad|#LoadStore \n\t"
: [val] "=r"(val)
: [rep_] "r"(&rep_)
: "memory");
return val;
}
inline void Release_Store(void *v)
{
__asm__ __volatile__("membar #LoadStore|#StoreStore \n\t"
"stx %[v], [%[rep_]] \n\t"
:
: [rep_] "r"(&rep_), [v] "r"(v)
: "memory");
}
inline void *NoBarrier_Load() const
{
return rep_;
}
inline void NoBarrier_Store(void *v)
{
rep_ = v;
}
};
// Atomic pointer based on ia64 acq/rel
#elif defined(__ia64) && defined(__GNUC__)
class AtomicPointer {
private:
void *rep_;
public:
AtomicPointer()
{
}
explicit AtomicPointer(void *v) : rep_(v)
{
}
inline void *Acquire_Load() const
{
void *val;
__asm__ __volatile__("ld8.acq %[val] = [%[rep_]] \n\t"
: [val] "=r"(val)
: [rep_] "r"(&rep_)
: "memory");
return val;
}
inline void Release_Store(void *v)
{
__asm__ __volatile__("st8.rel [%[rep_]] = %[v] \n\t"
:
: [rep_] "r"(&rep_), [v] "r"(v)
: "memory");
}
inline void *NoBarrier_Load() const
{
return rep_;
}
inline void NoBarrier_Store(void *v)
{
rep_ = v;
}
};
// We have neither MemoryBarrier(), nor <atomic>
#else
#error Please implement AtomicPointer for this platform.
#endif
#undef LEVELDB_HAVE_MEMORY_BARRIER
#undef ARCH_CPU_X86_FAMILY
#undef ARCH_CPU_ARM_FAMILY
#undef ARCH_CPU_ARM64_FAMILY
#undef ARCH_CPU_PPC_FAMILY
} // namespace port
} // namespace leveldb
#endif // PORT_ATOMIC_POINTER_H_
| 7,207 | 23.26936 | 84 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/include/leveldb/status.h
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
// A Status encapsulates the result of an operation. It may indicate success,
// or it may indicate an error with an associated error message.
//
// Multiple threads can invoke const methods on a Status without
// external synchronization, but if any of the threads may call a
// non-const method, all threads accessing the same Status must use
// external synchronization.
#ifndef STORAGE_LEVELDB_INCLUDE_STATUS_H_
#define STORAGE_LEVELDB_INCLUDE_STATUS_H_
#include "leveldb/slice.h"
#include <string>
namespace leveldb
{
class Status {
public:
// Create a success status.
Status() : state_(NULL)
{
}
~Status()
{
delete[] state_;
}
// Copy the specified status.
Status(const Status &s);
void operator=(const Status &s);
// Return a success status.
static Status OK()
{
return Status();
}
// Return error status of an appropriate type.
static Status NotFound(const Slice &msg, const Slice &msg2 = Slice())
{
return Status(kNotFound, msg, msg2);
}
static Status Corruption(const Slice &msg, const Slice &msg2 = Slice())
{
return Status(kCorruption, msg, msg2);
}
static Status NotSupported(const Slice &msg, const Slice &msg2 = Slice())
{
return Status(kNotSupported, msg, msg2);
}
static Status InvalidArgument(const Slice &msg, const Slice &msg2 = Slice())
{
return Status(kInvalidArgument, msg, msg2);
}
static Status IOError(const Slice &msg, const Slice &msg2 = Slice())
{
return Status(kIOError, msg, msg2);
}
// Returns true iff the status indicates success.
bool ok() const
{
return (state_ == NULL);
}
// Returns true iff the status indicates a NotFound error.
bool IsNotFound() const
{
return code() == kNotFound;
}
// Returns true iff the status indicates a Corruption error.
bool IsCorruption() const
{
return code() == kCorruption;
}
// Returns true iff the status indicates an IOError.
bool IsIOError() const
{
return code() == kIOError;
}
// Returns true iff the status indicates a NotSupportedError.
bool IsNotSupportedError() const
{
return code() == kNotSupported;
}
// Returns true iff the status indicates an InvalidArgument.
bool IsInvalidArgument() const
{
return code() == kInvalidArgument;
}
// Return a string representation of this status suitable for printing.
// Returns the string "OK" for success.
std::string ToString() const;
private:
// OK status has a NULL state_. Otherwise, state_ is a new[] array
// of the following form:
// state_[0..3] == length of message
// state_[4] == code
// state_[5..] == message
const char *state_;
enum Code {
kOk = 0,
kNotFound = 1,
kCorruption = 2,
kNotSupported = 3,
kInvalidArgument = 4,
kIOError = 5
};
Code code() const
{
return (state_ == NULL) ? kOk : static_cast<Code>(state_[4]);
}
Status(Code code, const Slice &msg, const Slice &msg2);
static const char *CopyState(const char *s);
};
inline Status::Status(const Status &s)
{
state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_);
}
inline void Status::operator=(const Status &s)
{
// The following condition catches both aliasing (when this == &s),
// and the common case where both s and *this are ok.
if (state_ != s.state_) {
delete[] state_;
state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_);
}
}
} // namespace leveldb
#endif // STORAGE_LEVELDB_INCLUDE_STATUS_H_
| 3,658 | 23.231788 | 81 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/include/leveldb/slice.h
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
// Slice is a simple structure containing a pointer into some external
// storage and a size. The user of a Slice must ensure that the slice
// is not used after the corresponding external storage has been
// deallocated.
//
// Multiple threads can invoke const methods on a Slice without
// external synchronization, but if any of the threads may call a
// non-const method, all threads accessing the same Slice must use
// external synchronization.
#ifndef STORAGE_LEVELDB_INCLUDE_SLICE_H_
#define STORAGE_LEVELDB_INCLUDE_SLICE_H_
#include <assert.h>
#include <stddef.h>
#include <string.h>
#include <string>
namespace leveldb
{
class Slice {
public:
// Create an empty slice.
Slice() : data_(""), size_(0)
{
}
// Create a slice that refers to d[0,n-1].
Slice(const char *d, size_t n) : data_(d), size_(n)
{
}
// Create a slice that refers to the contents of "s"
Slice(const std::string &s) : data_(s.data()), size_(s.size())
{
}
// Create a slice that refers to s[0,strlen(s)-1]
Slice(const char *s) : data_(s), size_(strlen(s))
{
}
// Return a pointer to the beginning of the referenced data
const char *data() const
{
return data_;
}
// Return the length (in bytes) of the referenced data
size_t size() const
{
return size_;
}
// Return true iff the length of the referenced data is zero
bool empty() const
{
return size_ == 0;
}
// Return the ith byte in the referenced data.
// REQUIRES: n < size()
char operator[](size_t n) const
{
assert(n < size());
return data_[n];
}
// Change this slice to refer to an empty array
void clear()
{
data_ = "";
size_ = 0;
}
// Drop the first "n" bytes from this slice.
void remove_prefix(size_t n)
{
assert(n <= size());
data_ += n;
size_ -= n;
}
// Return a string that contains the copy of the referenced data.
std::string ToString() const
{
return std::string(data_, size_);
}
// Three-way comparison. Returns value:
// < 0 iff "*this" < "b",
// == 0 iff "*this" == "b",
// > 0 iff "*this" > "b"
int compare(const Slice &b) const;
// Return true iff "x" is a prefix of "*this"
bool starts_with(const Slice &x) const
{
return ((size_ >= x.size_) && (memcmp(data_, x.data_, x.size_) == 0));
}
private:
const char *data_;
size_t size_;
// Intentionally copyable
};
inline bool operator==(const Slice &x, const Slice &y)
{
return ((x.size() == y.size()) && (memcmp(x.data(), y.data(), x.size()) == 0));
}
inline bool operator!=(const Slice &x, const Slice &y)
{
return !(x == y);
}
inline int Slice::compare(const Slice &b) const
{
const size_t min_len = (size_ < b.size_) ? size_ : b.size_;
int r = memcmp(data_, b.data_, min_len);
if (r == 0) {
if (size_ < b.size_)
r = -1;
else if (size_ > b.size_)
r = +1;
}
return r;
}
} // namespace leveldb
#endif // STORAGE_LEVELDB_INCLUDE_SLICE_H_
| 3,163 | 21.125874 | 81 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench/include/leveldb/env.h
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
// An Env is an interface used by the leveldb implementation to access
// operating system functionality like the filesystem etc. Callers
// may wish to provide a custom Env object when opening a database to
// get fine gain control; e.g., to rate limit file system operations.
//
// All Env implementations are safe for concurrent access from
// multiple threads without any external synchronization.
#ifndef STORAGE_LEVELDB_INCLUDE_ENV_H_
#define STORAGE_LEVELDB_INCLUDE_ENV_H_
#include "leveldb/status.h"
#include <stdarg.h>
#include <stdint.h>
#include <string>
#include <vector>
namespace leveldb
{
class FileLock;
class Logger;
class RandomAccessFile;
class SequentialFile;
class Slice;
class WritableFile;
class Env {
public:
Env()
{
}
virtual ~Env();
// Return a default environment suitable for the current operating
// system. Sophisticated users may wish to provide their own Env
// implementation instead of relying on this default environment.
//
// The result of Default() belongs to leveldb and must never be deleted.
static Env *Default();
// Create a brand new sequentially-readable file with the specified name.
// On success, stores a pointer to the new file in *result and returns OK.
// On failure stores NULL in *result and returns non-OK. If the file does
// not exist, returns a non-OK status. Implementations should return a
// NotFound status when the file does not exist.
//
// The returned file will only be accessed by one thread at a time.
virtual Status NewSequentialFile(const std::string &fname, SequentialFile **result) = 0;
// Create a brand new random access read-only file with the
// specified name. On success, stores a pointer to the new file in
// *result and returns OK. On failure stores NULL in *result and
// returns non-OK. If the file does not exist, returns a non-OK
// status. Implementations should return a NotFound status when the file does
// not exist.
//
// The returned file may be concurrently accessed by multiple threads.
virtual Status NewRandomAccessFile(const std::string &fname, RandomAccessFile **result) = 0;
// Create an object that writes to a new file with the specified
// name. Deletes any existing file with the same name and creates a
// new file. On success, stores a pointer to the new file in
// *result and returns OK. On failure stores NULL in *result and
// returns non-OK.
//
// The returned file will only be accessed by one thread at a time.
virtual Status NewWritableFile(const std::string &fname, WritableFile **result) = 0;
// Create an object that either appends to an existing file, or
// writes to a new file (if the file does not exist to begin with).
// On success, stores a pointer to the new file in *result and
// returns OK. On failure stores NULL in *result and returns
// non-OK.
//
// The returned file will only be accessed by one thread at a time.
//
// May return an IsNotSupportedError error if this Env does
// not allow appending to an existing file. Users of Env (including
// the leveldb implementation) must be prepared to deal with
// an Env that does not support appending.
virtual Status NewAppendableFile(const std::string &fname, WritableFile **result);
// Returns true iff the named file exists.
virtual bool FileExists(const std::string &fname) = 0;
// Store in *result the names of the children of the specified directory.
// The names are relative to "dir".
// Original contents of *results are dropped.
virtual Status GetChildren(const std::string &dir, std::vector<std::string> *result) = 0;
// Delete the named file.
virtual Status DeleteFile(const std::string &fname) = 0;
// Create the specified directory.
virtual Status CreateDir(const std::string &dirname) = 0;
// Delete the specified directory.
virtual Status DeleteDir(const std::string &dirname) = 0;
// Store the size of fname in *file_size.
virtual Status GetFileSize(const std::string &fname, uint64_t *file_size) = 0;
// Rename file src to target.
virtual Status RenameFile(const std::string &src, const std::string &target) = 0;
// Lock the specified file. Used to prevent concurrent access to
// the same db by multiple processes. On failure, stores NULL in
// *lock and returns non-OK.
//
// On success, stores a pointer to the object that represents the
// acquired lock in *lock and returns OK. The caller should call
// UnlockFile(*lock) to release the lock. If the process exits,
// the lock will be automatically released.
//
// If somebody else already holds the lock, finishes immediately
// with a failure. I.e., this call does not wait for existing locks
// to go away.
//
// May create the named file if it does not already exist.
virtual Status LockFile(const std::string &fname, FileLock **lock) = 0;
// Release the lock acquired by a previous successful call to LockFile.
// REQUIRES: lock was returned by a successful LockFile() call
// REQUIRES: lock has not already been unlocked.
virtual Status UnlockFile(FileLock *lock) = 0;
// Arrange to run "(*function)(arg)" once in a background thread.
//
// "function" may run in an unspecified thread. Multiple functions
// added to the same Env may run concurrently in different threads.
// I.e., the caller may not assume that background work items are
// serialized.
virtual void Schedule(void (*function)(void *arg), void *arg) = 0;
// Start a new thread, invoking "function(arg)" within the new thread.
// When "function(arg)" returns, the thread will be destroyed.
virtual void StartThread(void (*function)(void *arg), void *arg) = 0;
// *path is set to a temporary directory that can be used for testing. It may
// or many not have just been created. The directory may or may not differ
// between runs of the same process, but subsequent calls will return the
// same directory.
virtual Status GetTestDirectory(std::string *path) = 0;
// Create and return a log file for storing informational messages.
virtual Status NewLogger(const std::string &fname, Logger **result) = 0;
// Returns the number of micro-seconds since some fixed point in time. Only
// useful for computing deltas of time.
virtual uint64_t NowMicros() = 0;
// Sleep/delay the thread for the prescribed number of micro-seconds.
virtual void SleepForMicroseconds(int micros) = 0;
private:
// No copying allowed
Env(const Env &);
void operator=(const Env &);
};
// A file abstraction for reading sequentially through a file
class SequentialFile {
public:
SequentialFile()
{
}
virtual ~SequentialFile();
// Read up to "n" bytes from the file. "scratch[0..n-1]" may be
// written by this routine. Sets "*result" to the data that was
// read (including if fewer than "n" bytes were successfully read).
// May set "*result" to point at data in "scratch[0..n-1]", so
// "scratch[0..n-1]" must be live when "*result" is used.
// If an error was encountered, returns a non-OK status.
//
// REQUIRES: External synchronization
virtual Status Read(size_t n, Slice *result, char *scratch) = 0;
// Skip "n" bytes from the file. This is guaranteed to be no
// slower that reading the same data, but may be faster.
//
// If end of file is reached, skipping will stop at the end of the
// file, and Skip will return OK.
//
// REQUIRES: External synchronization
virtual Status Skip(uint64_t n) = 0;
private:
// No copying allowed
SequentialFile(const SequentialFile &);
void operator=(const SequentialFile &);
};
// A file abstraction for randomly reading the contents of a file.
class RandomAccessFile {
public:
RandomAccessFile()
{
}
virtual ~RandomAccessFile();
// Read up to "n" bytes from the file starting at "offset".
// "scratch[0..n-1]" may be written by this routine. Sets "*result"
// to the data that was read (including if fewer than "n" bytes were
// successfully read). May set "*result" to point at data in
// "scratch[0..n-1]", so "scratch[0..n-1]" must be live when
// "*result" is used. If an error was encountered, returns a non-OK
// status.
//
// Safe for concurrent use by multiple threads.
virtual Status Read(uint64_t offset, size_t n, Slice *result, char *scratch) const = 0;
private:
// No copying allowed
RandomAccessFile(const RandomAccessFile &);
void operator=(const RandomAccessFile &);
};
// A file abstraction for sequential writing. The implementation
// must provide buffering since callers may append small fragments
// at a time to the file.
class WritableFile {
public:
WritableFile()
{
}
virtual ~WritableFile();
virtual Status Append(const Slice &data) = 0;
virtual Status Close() = 0;
virtual Status Flush() = 0;
virtual Status Sync() = 0;
private:
// No copying allowed
WritableFile(const WritableFile &);
void operator=(const WritableFile &);
};
// An interface for writing log messages.
class Logger {
public:
Logger()
{
}
virtual ~Logger();
// Write an entry to the log file with the specified format.
virtual void Logv(const char *format, va_list ap) = 0;
private:
// No copying allowed
Logger(const Logger &);
void operator=(const Logger &);
};
// Identifies a locked file.
class FileLock {
public:
FileLock()
{
}
virtual ~FileLock();
private:
// No copying allowed
FileLock(const FileLock &);
void operator=(const FileLock &);
};
// Log the specified data to *info_log if info_log is non-NULL.
extern void Log(Logger *info_log, const char *format, ...)
#if defined(__GNUC__) || defined(__clang__)
__attribute__((__format__(__printf__, 2, 3)))
#endif
;
// A utility routine: write "data" to the named file.
Status WriteStringToFile(Env *env, const Slice &data, const std::string &fname);
// A utility routine: read contents of named file into *data
Status ReadFileToString(Env *env, const std::string &fname, std::string *data);
// An implementation of Env that forwards all calls to another Env.
// May be useful to clients who wish to override just part of the
// functionality of another Env.
class EnvWrapper : public Env {
public:
// Initialize an EnvWrapper that delegates all calls to *t
explicit EnvWrapper(Env *t) : target_(t)
{
}
virtual ~EnvWrapper();
// Return the target to which this Env forwards all calls
Env *target() const
{
return target_;
}
// The following text is boilerplate that forwards all methods to target()
Status NewSequentialFile(const std::string &f, SequentialFile **r)
{
return target_->NewSequentialFile(f, r);
}
Status NewRandomAccessFile(const std::string &f, RandomAccessFile **r)
{
return target_->NewRandomAccessFile(f, r);
}
Status NewWritableFile(const std::string &f, WritableFile **r)
{
return target_->NewWritableFile(f, r);
}
Status NewAppendableFile(const std::string &f, WritableFile **r)
{
return target_->NewAppendableFile(f, r);
}
bool FileExists(const std::string &f)
{
return target_->FileExists(f);
}
Status GetChildren(const std::string &dir, std::vector<std::string> *r)
{
return target_->GetChildren(dir, r);
}
Status DeleteFile(const std::string &f)
{
return target_->DeleteFile(f);
}
Status CreateDir(const std::string &d)
{
return target_->CreateDir(d);
}
Status DeleteDir(const std::string &d)
{
return target_->DeleteDir(d);
}
Status GetFileSize(const std::string &f, uint64_t *s)
{
return target_->GetFileSize(f, s);
}
Status RenameFile(const std::string &s, const std::string &t)
{
return target_->RenameFile(s, t);
}
Status LockFile(const std::string &f, FileLock **l)
{
return target_->LockFile(f, l);
}
Status UnlockFile(FileLock *l)
{
return target_->UnlockFile(l);
}
void Schedule(void (*f)(void *), void *a)
{
return target_->Schedule(f, a);
}
void StartThread(void (*f)(void *), void *a)
{
return target_->StartThread(f, a);
}
virtual Status GetTestDirectory(std::string *path)
{
return target_->GetTestDirectory(path);
}
virtual Status NewLogger(const std::string &fname, Logger **result)
{
return target_->NewLogger(fname, result);
}
uint64_t NowMicros()
{
return target_->NowMicros();
}
void SleepForMicroseconds(int micros)
{
target_->SleepForMicroseconds(micros);
}
private:
Env *target_;
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_INCLUDE_ENV_H_
| 12,539 | 30.827411 | 93 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/utils/jenkins/README.md
|
# Jenkins Configuration
## Overview
Jenkins is a self contained, open sourced automation server which can be used to automate tasks related to building and testing. Its functionality can be expanded by installing plugins.
Jenkins main function is to launch jobs. Jobs are scripts that cover managing repositories, building and testing. Jenkins pipeline is a script that is launched by Jenkins job. Each pipeline consists of build stages that follow one another, for example: download repository, build, test, etc. Each stage consists of steps that are actual commands ran on an actual device under test - which which is called: Node.
## Requirements
To run tests it is recommended to install these plugins first:
- Blue Ocean
- Branch API
- Command Agent Launcher
- Configuration as Code
- Dashboard View
- Email Extension
- External Monitor Job Type
- Folders
- Git
- Git client
- GitLab
- Job DSL
- JUnit
- LDAP
- Matrix Authorization Strategy
- Matrix Combinations
- Multijob
- Oracle Java SE Development Kit Installer
- OWASP Markup Formatter
- PAM Authentication
- Pipeline Utility Steps
- Pipeline: Build Step
- Pipeline: Multibranch
- Pipeline: REST API
- Pipeline: Stage View
- SSH Agent
- SSH Build Agents
- Timestamper
## Managing Jenkins
### Overivew
Jenkins can be configured and managed "as a code" - it means that actual jobs and pipelines can be downloaded from remote repository. But first it is needed to add a job that downloads jobs definitions from remote repository and configures Jenkins. Instructions below allows to manually trigger creating/updating jobs, but it is possible to trigger this job automatically with each push to target repository.
### Add master executor
Before running any job, it is needed to add an executor which will run Jenkins job. First, it is useful to add executor on master node - which is a server containing Jenkins instance. This executor will lunch job and then pipeline will be executed on the node specified by the "LABEL" field.
To add master executor:
- Select: "Manage Jenkins".
- Select: "Manage Nodes and Clouds".
- Select: "master" node.
- Select: "Configure".
- In the field "# of executors" type "4".
- Select: "Save".
### Add job generating jobs
To add a Job that generates jobs from Jenkinsfile:
- Select: "New item".
- Enter jobs name, e.g. "job_creator".
- Select: "Pipeline".
- Click OK.
- In tab "General", select "GitHUB Project", enter project url: "https://github.com/pmem/pmemkv".
- In "Pipeline" tab, set fields as below:
- Definition: Pipeline script from SCM
- SCM: Git
- Repositories:
- Repository URL: Enter github repository with jenkins job, e.g. "https://github.com/pmem/pmemkv".
- Credentials: none
- Branches to build:
- Branch Specifier (blank for 'any'): master (or any other branch containing jenkinsfile).
- Script Path: Enter path with the Jenkinsfile, relative to the root folder of the repository: "utils/jenkins/Jenkinsfile"
- Lightweight checkout: yes
7. Save.
8. Enter the new created job from main dashboard.
9. Click on the "Build Now".
### In-process Script Approval
By default, Jenkins will prevent to run new groovy scrips which will cause our job to fail. After each fail caused by an unapproved script, it is needed to accept this script. Unfortunately, this will be necessary to repeat several times, by launching this job repeatedly (only after creating this job, for the first time).
To approve scripts:
- Select: "Manage Jenkins".
- Select: "In-process Script Approval".
- Click "Approve".
### Test nodes
To run Jenkins jobs, it will be needed to add additional Nodes (beside of master Node) which are servers prepared to run tests. Each Node is required to have:
- Installed Java Runtime Environment.
- Installed and running SSH server, open ssh port (22).
- Added user that Jenkins can log on, with appropriate credentials needed to run tests, e.g. "test-user".
#### Adding test nodes
in this case we will be using server with Fedora31 installed and user "test-user" created.
- Select: "Manage Jenkins".
- Select: "Manage Nodes and Clouds".
- Select: "New Node".
- Type name in the "Node name" field, "Server_001(fedora31)".
- Select "Permanent Agent" (after creating first node, it is possible to copy existing configuration by selecting "Copy Existing Node").
- Click "OK".
- In the field "# of executors" type "1".
- In the field "Remote root directory" type directory that Jenkins user has credentials to access to. In our case: /home/test-user
- In the field "Labels" type an actual OS installed on server - in our case type "fedora fedora31" NOTE: There can be multiple labels assigned to server.
- In the field "Usage" select "Use this node as much as possible".
- In the field "Launch method" select "Launch agent agents via SSH".
- In the field "Host" type IP address of the server, in format x.x.x.x
- In the field "Credentials" click "Add" and then "Jenkins" to create new credentials:
- In the field "Domain" select "Global credentials (unrestricted)".
- In the field "Kind" select "Username with password".
- In the field "Scope" select "System (Jenkins and nodes only)".
- In the field "Username" type username - in our case: "test-user".
- In the field "Password" enter password.
- In the field "ID" enter username - in our case "test-user".
- Click "Add"
- In the field "Credentials" select newly created credentials - in our case: "test-user".
- In the field "Host Key Verification Strategy" select Manually trusted key Verification strategy.
- In the field "Availability" select "Keep this agent online as much as possible.
- Click "Save"
### Job overview
Jenkins jobs can be accessed from main dashboard. To select job click on the name of that job. To run job, enter "Build with Parameters". To access finished job, click on the Build name in the "Build History" section or in the "Stage view" section. In the build view "Build Artifacts" can be accessed, containing "console.log". NOTE: console logs are available also by clicking on "Console Output" or "View as plain text", which is useful when pipeline was unable to generate logs or job failed from script errors or Jenkins related errors, e.g. unapproved scripts.
### Running a Job
Enter the Job view and click "Build with Parameters". Some build configuration can be made. To run job, click "Build".
#### pmemkv_linux
**LABEL** - Name of the node or group to run job on, for example: rhel8_2, openSUSE15_2, fedora32, ubuntu20_04, ubuntu19.10, debian10, etc. Make sure that node with this label exist and its online.
**BRANCH** - Pmemkv repository branch.
**TEST_TYPE** - PMEMKV test type to run: normal, building, compability.
**DEVICE_TYPE** - Selects tested device type. If "NONE" - test will run on HDD.
**REPO_URL** - Git repository address.
**COVERAGE** - Enable or disable code coverage.
**EMAIL_RECIPIENTS** - Recipients of the e-mail with job status and sent after execution.
**SEND_RESULTS** - Enable or disable email reporting.
#### pmemkv_linux_matrix
This job will run multiple pmemkv_linux jobs. Instead LABEL and TEST_TYPE there is a combinations matrix. Each check will run job with specified TEST_TYPE on specified OS.
| 7,221 | 47.469799 | 565 |
md
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/utils/jenkins/scripts/createNamespace.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
# createNamespace.sh - Remove old namespaces and create new
set -e
# region used for dax namespaces.
DEV_DAX_R=0x0000
# region used for fsdax namespaces.
FS_DAX_R=0x0001
CREATE_DAX=false
CREATE_PMEM=false
MOUNT_POINT="/mnt/pmem0"
SIZE=100G
function usage()
{
echo ""
echo "Script for creating namespaces, mountpoint, and configuring file permissions."
echo "Usage: $(basename $1) [-h|--help] [-d|--dax] [-p|--pmem] [--size]"
echo "-h, --help Print help and exit"
echo "-d, --dax Create dax device."
echo "-p, --pmem Create fsdax device and create mountpoint."
echo "--size Set size for namespaces [default: $SIZE]"
}
function clear_namespaces() {
scriptdir=$(readlink -f $(dirname ${BASH_SOURCE[0]}))
$scriptdir/removeNamespaces.sh
}
function create_devdax() {
local align=$1
local size=$2
local cmd="sudo ndctl create-namespace --mode devdax -a ${align} -s ${size} -r ${DEV_DAX_R} -f"
result=$(${cmd})
if [ $? -ne 0 ]; then
exit 1;
fi
jq -r '.daxregion.devices[].chardev' <<< $result
}
function create_fsdax() {
local size=$1
local cmd="sudo ndctl create-namespace --mode fsdax -s ${size} -r ${FS_DAX_R} -f"
result=$(${cmd})
if [ $? -ne 0 ]; then
exit 1;
fi
jq -r '.blockdev' <<< $result
}
while getopts ":dhp-:" optchar; do
case "${optchar}" in
-)
case "$OPTARG" in
help) usage $0 && exit 0 ;;
dax) CREATE_DAX=true ;;
pmem) CREATE_PMEM=true ;;
size=*) SIZE="${OPTARG#*=}" ;;
*) echo "Invalid argument '$OPTARG'"; usage $0 && exit 1 ;;
esac
;;
p) CREATE_PMEM=true ;;
d) CREATE_DAX=true ;;
h) usage $0 && exit 0 ;;
*) echo "Invalid argument '$OPTARG'"; usage $0 && exit 1 ;;
esac
done
# There is no default test cofiguration in this script. Configurations has to be specified.
if ! $CREATE_DAX && ! $CREATE_PMEM; then
echo ""
echo "ERROR: No config type selected. Please select one or more config types."
exit 1
fi
# Remove existing namespaces.
clear_namespaces
# Creating namespaces.
trap 'echo "ERROR: Failed to create namespaces"; clear_namespaces; exit 1' ERR SIGTERM SIGABRT
if $CREATE_DAX; then
create_devdax 4k $SIZE
fi
if $CREATE_PMEM; then
pmem_name=$(create_fsdax $SIZE)
fi
# Creating mountpoint.
trap 'echo "ERROR: Failed to create mountpoint"; clear_namespaces; exit 1' ERR SIGTERM SIGABRT
if $CREATE_PMEM; then
if [ ! -d "$MOUNT_POINT" ]; then
sudo mkdir $MOUNT_POINT
fi
if ! grep -qs "$MOUNT_POINT " /proc/mounts; then
sudo mkfs.ext4 -F /dev/$pmem_name
sudo mount -o dax /dev/$pmem_name $MOUNT_POINT
fi
fi
# Changing file permissions.
sudo chmod 777 $MOUNT_POINT || true
sudo chmod 777 /dev/dax* || true
sudo chmod a+rw /sys/bus/nd/devices/region*/deep_flush
sudo chmod +r /sys/bus/nd/devices/ndbus*/region*/resource
sudo chmod +r /sys/bus/nd/devices/ndbus*/region*/dax*/resource
# Print created namespaces.
ndctl list -X | jq -r '.[] | select(.mode=="devdax") | [.daxregion.devices[].chardev, "align: "+(.daxregion.align/1024|tostring+"k"), "size: "+(.size/1024/1024/1024|tostring+"G") ]'
ndctl list | jq -r '.[] | select(.mode=="fsdax") | [.blockdev, "size: "+(.size/1024/1024/1024|tostring+"G") ]'
| 3,239 | 26.457627 | 181 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/utils/jenkins/scripts/removeNamespaces.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
# removeNamespaces.sh - clear all existing namespaces.
set -e
MOUNT_POINT="/mnt/pmem*"
sudo umount $MOUNT_POINT || true
namespace_names=$(ndctl list -X | jq -r '.[].dev')
for n in $namespace_names
do
sudo ndctl clear-errors $n -v
done
sudo ndctl disable-namespace all || true
sudo ndctl destroy-namespace all || true
| 424 | 20.25 | 54 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/utils/jenkins/scripts/common.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
# common.sh - contains bash functions used in all jenkins pipelines.
set -o pipefail
scriptdir=$(readlink -f $(dirname ${BASH_SOURCE[0]}))
function system_info {
echo "********** system-info **********"
cat /etc/os-release | grep -oP "PRETTY_NAME=\K.*"
uname -r
echo "libndctl: $(pkg-config --modversion libndctl || echo 'libndctl not found')"
echo "libfabric: $(pkg-config --modversion libfabric || echo 'libfabric not found')"
echo "libpmem: $(pkg-config --modversion libpmem || echo 'libpmem not found')"
echo "libpmemobj: $(pkg-config --modversion libpmemobj || echo 'libpmemobj not found')"
echo "libpmemobj++: $(pkg-config --modversion libpmemobj++ || echo 'libpmemobj++ not found')"
echo "memkind: $(pkg-config --modversion memkind || echo 'memkind not found')"
echo "TBB : $(pkg-config --modversion TBB || echo 'TBB not found')"
echo "valgrind: $(pkg-config --modversion valgrind || echo 'valgrind not found')"
echo "**********memory-info**********"
sudo ipmctl show -dimm || true
sudo ipmctl show -topology || true
echo "**********list-existing-namespaces**********"
sudo ndctl list -M -N
echo "**********installed-packages**********"
zypper se --installed-only 2>/dev/null || true
apt list --installed 2>/dev/null || true
yum list installed 2>/dev/null || true
echo "**********/proc/cmdline**********"
cat /proc/cmdline
echo "**********/proc/modules**********"
cat /proc/modules
echo "**********/proc/cpuinfo**********"
cat /proc/cpuinfo
echo "**********/proc/meminfo**********"
cat /proc/meminfo
eco "**********/proc/swaps**********"
cat /proc/swaps
echo "**********/proc/version**********"
cat /proc/version
echo "**********check-updates**********"
sudo zypper list-updates 2>/dev/null || true
sudo apt-get update 2>/dev/null || true ; apt upgrade --dry-run 2>/dev/null || true
sudo dnf check-update 2>/dev/null || true
echo "**********list-enviroment**********"
env
}
function set_warning_message {
local info_addr=$1
sudo bash -c "cat > /etc/motd <<EOL
___ ___
/ \ / \ HELLO!
\_ \ / __/ THIS NODE IS CONNECTED TO PMEMKV JENKINS
_\ \ / /__ THERE ARE TESTS CURRENTLY RUNNING ON THIS MACHINE
\___ \____/ __/ PLEASE GO AWAY :)
\_ _/
| @ @ \_
| FOR MORE INFORMATION GO: ${info_addr}
_/ /\
/o) (o/\ \_
\_____/ /
\____/
EOL"
}
function disable_warning_message {
sudo rm /etc/motd || true
}
# Check host linux distribution and return distro name
function check_distro {
distro=$(cat /etc/os-release | grep -e ^NAME= | cut -c6-) && echo "${distro//\"}"
}
| 2,808 | 34.556962 | 94 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmemkv-bench-sd/bench_scenarios/generate_obj_based_scope.py
|
#!/usr/bin/env python3
#
# SPDX-License-Identifier: Apache-2.0
# Copyright 2021, Intel Corporation
# This script implements generate() method, which may be invoked by run_benchmark.py directly,
# or used as standalone application, which prints configuration json (also validated against schema)
# to stdout. Such once generated json may be saved and passed to run_benchmark.py as a parameter
import json
import itertools
import jsonschema
import os
benchmarks = [
"fillseq",
"fillrandom",
"fillseq,readrandom,readrandom",
"fillrandom,readrandom,readrandom",
"fillseq,readseq,readseq",
"fillrandom,readseq,readseq",
"fillseq,readwhilewriting",
"fillseq,readrandomwriterandom",
]
size = [8, 128]
number_of_elements = 100000000
def concurrent_engines():
number_of_threads = [1, 4, 8, 12, 18, 24]
engine = ["cmap", "csmap"]
result = itertools.product(benchmarks, size, number_of_threads, engine)
return list(result)
def single_threaded_engines():
number_of_threads = [1]
engine = ["radix", "stree"]
result = itertools.product(benchmarks, size, number_of_threads, engine)
return list(result)
def generate():
benchmarks = concurrent_engines()
benchmarks.extend(single_threaded_engines())
benchmarks_configuration = []
db_path = os.getenv("PMEMKV_BENCH_DB_PATH", "/mnt/pmem0/pmemkv-bench")
for benchmark in benchmarks:
benchmark_settings = {
"env": {
"NUMACTL_CPUBIND": f"file:{os.path.dirname(db_path)}",
},
"params": {
"--benchmarks": f"{benchmark[0]}",
"--value_size": f"{benchmark[1]}",
"--threads": f"{benchmark[2]}",
"--engine": f"{benchmark[3]}",
"--num": f"{number_of_elements}",
"--db": db_path,
"--db_size_in_gb": "200",
},
}
benchmarks_configuration.append(benchmark_settings)
return benchmarks_configuration
if __name__ == "__main__":
output = generate()
schema = None
with open("bench.schema.json", "r") as schema_file:
schema = json.loads(schema_file.read())
try:
jsonschema.validate(instance=output, schema=schema)
except jsonschema.exceptions.ValidationError as e:
print(e)
exit(1)
print(json.dumps(output, indent=4))
| 2,386 | 28.109756 | 100 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/.cirrus.yml
|
freebsd_instance:
image: freebsd-12-1-release-amd64
task:
install_script: ASSUME_ALWAYS_YES=yes pkg bootstrap -f;
pkg install -y
autoconf bash binutils coreutils e2fsprogs-libuuid
git gmake libunwind ncurses pkgconf hs-pandoc
script: CFLAGS="-Wno-unused-value" gmake
| 286 | 27.7 | 57 |
yml
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/builddatastoreall.sh
|
make clobber
make -j12 EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER
make EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER
cat builddatastoreall.sh
| 236 | 46.4 | 99 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/CONTRIBUTING.md
|
# Contributing to the Persistent Memory Development Kit
Down below you'll find instructions on how to contribute to the
Persistent Memory Development Kit.
Your contributions are most welcome! You'll find it is best to begin
with a conversation about your changes, rather than just writing a bunch
of code and contributing it out of the blue.
There are several good ways to suggest new features, offer to add a feature,
or just begin a dialog about the Persistent Memory Development Kit:
* Open an issue in our [GitHub Issues Database](https://github.com/pmem/pmdk/issues)
* Suggest a feature, ask a question, start a discussion, etc. in our [pmem Google group](https://groups.google.com/group/pmem)
* Chat with members of the PMDK team real-time on the **#pmem** IRC channel on [OFTC](https://www.oftc.net)
**NOTE: If you do decide to implement code changes and contribute them,
please make sure you agree your contribution can be made available
under the [BSD-style License used for the Persistent Memory Development Kit](https://github.com/pmem/pmdk/blob/master/LICENSE).**
**NOTE: Submitting your changes also means that you certify the following:**
```
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
In case of any doubt, the gatekeeper may ask you to certify the above in writing,
i.e. via email or by including a `Signed-off-by:` line at the bottom
of your commit comments.
To improve tracking of who is the author of the contribution, we kindly ask you
to use your real name (not an alias) when committing your changes to the
Persistent Memory Development Kit:
```
Author: Random J Developer <random@developer.example.org>
```
### Code Contributions
Please feel free to use the forums mentioned above to ask
for comments & questions on your code before submitting
a pull request. The Persistent Memory Development Kit project uses the common
*fork and merge* workflow used by most GitHub-hosted projects.
The [Git Workflow blog article](https://pmem.io/2014/09/09/git-workflow.html)
describes our workflow in more detail.
#### Linux/FreeBSD
Before contributing please remember to run:
```
$ make cstyle
```
This will check all C/C++ files in the tree for style issues. To check C++
files you have to have clang-format version 6.0, otherwise they will be
skipped. If you want to run this target automatically at build time, you can
pass CSTYLEON=1 to make. If you want cstyle to be run, but not fail the build,
pass CSTYLEON=2 to make.
There is also a target for automatic C++ code formatting, to do this run:
```
$ make format
```
There are cases, when you might have several clang-format-X.Y binaries and either
no clang-format or it pointing to an older version. In such case run:
```
$ make CLANG_FORMAT=/path/to/clang-format cstyle|format
```
#### Windows
On Windows to check the code for style issues, please run:
```
$ pmdk\utils\CSTYLE.ps1
```
To check or format C++ files, you may use a standalone Visual Studio plugin
for clang-format. The plugin installer can be downloaded from
[LLVM Builds](https://llvm.org/builds) page.
If you are actively working on an PMDK feature, please let other
developers know by [creating an issue](https://github.com/pmem/pmdk/issues).
Use the template `Feature` and assign it to yourself (due to the way
GitHub permissions work, you may have to ask a team member to assign it to you).
### Bug Reports
Bugs for the PMDK project are tracked in our
[GitHub Issues Database](https://github.com/pmem/pmdk/issues).
When reporting a new bug, please use `New issue` button, pick proper template and fill
in all fields. Provide as much information as possible, including the product version:
#### PMDK version
Put the release name of the version of PMDK running when the
bug was discovered in a bug comment. If you saw this bug in multiple PMDK
versions, please put at least the most recent version and list the others
if necessary.
- Stable release names are in the form `#.#` (where `#` represents
an integer); for example `0.3`.
- Release names from working versions look like `#.#+b#` (adding a build #)
or `#.#-rc#` (adding a release candidate number)
If PMDK was built from source, the version number can be retrieved
from git using this command: `git describe`
For binary PMDK releases, use the entire package name.
For RPMs, use `rpm -q pmdk` to display the name.
For Deb packages, run `dpkg-query -W pmdk` and use the
second (version) string.
#### Priority
Requested priority describes the urgency to resolve a defect and establishes
the time frame for providing a verified resolution. Priorities are defined as:
* **P1**: Showstopper bug, requiring a resolution before the next release of the
library.
* **P2**: High-priority bug, requiring a resolution although it may be decided
that the bug does not prevent the next release of the library.
* **P3**: Medium-priority bug. The expectation is that the bug will be
evaluated and a plan will be made for when the bug will be resolved.
* **P4**: Low-priority bug, the least urgent. Fixed when the resources are available.
### Other issues
On our issues page we also gather feature requests and questions. Templates to use
are `Feature` and `Question`, respectively. They should help deliver a meaningful
description of a feature or ask a question to us (remember though we have
different means of communication, as described at the top of the page).
| 6,479 | 41.077922 | 129 |
md
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/buildclobber.sh
|
make clobber
make -j12 EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER EXTRA_CFLAGS+=-DRUN_COUNT=1
make EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER EXTRA_CFLAGS+=-DRUN_COUNT=1
cat buildclobber.sh
| 171 | 33.4 | 70 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/buildredo.sh
|
make clobber
make -j12 EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DRUN_COUNT=1
make EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DRUN_COUNT=1
cat buildredo.sh
| 166 | 32.4 | 69 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/builddatastoreclobber.sh
|
make clobber
make -j12 EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER
make EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER
cat builddatastoreclobber.sh
| 182 | 35.6 | 70 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/run.sh
|
make EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DRUN_COUNT=100000
make EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DRUN_COUNT=100000
make EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DGET_NDP_BREAKDOWN
make -j12 EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DGET_NDP_BREAKDOWN
make -j12 EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DRUN_COUNT=10000 EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER
EXTRA_CFLAGS="-Wno-error"
| 481 | 67.857143 | 112 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/README.md
|
# **PMDK: Persistent Memory Development Kit**
[](https://travis-ci.org/pmem/pmdk)
[](https://github.com/pmem/pmdk/actions)
[](https://ci.appveyor.com/project/pmem/pmdk/branch/master)
[](https://cirrus-ci.com/github/pmem/pmdk/master)
[](https://scan.coverity.com/projects/pmem-pmdk)
[](https://github.com/pmem/pmdk/releases/latest)
[](https://codecov.io/gh/pmem/pmdk/branch/master)
The **Persistent Memory Development Kit (PMDK)** is a collection of libraries and tools for System Administrators and Application Developers to simplify managing and accessing persistent memory devices. For more information, see https://pmem.io.
To install PMDK libraries, either install pre-built packages, which we build for every stable release, or clone the tree and build it yourself. **Pre-built** packages can be found in popular Linux distribution package repositories, or you can check out our recent stable releases on our [github release page](https://github.com/pmem/pmdk/releases). Specific installation instructions are outlined below.
Bugs and feature requests for this repo are tracked in our [GitHub Issues Database](https://github.com/pmem/pmdk/issues).
## Contents
1. [Libraries and Utilities](#libraries-and-utilities)
2. [Getting Started](#getting-started)
3. [Version Conventions](#version-conventions)
4. [Pre-Built Packages for Windows](#pre-built-packages-for-windows)
5. [Dependencies](#dependencies)
* [Linux](#linux)
* [Windows](#windows)
* [FreeBSD](#freebsd)
6. [Building PMDK on Linux or FreeBSD](#building-pmdk-on-linux-or-freebsd)
* [Make Options](#make-options)
* [Testing Libraries](#testing-libraries-on-linux-and-freebsd)
* [Memory Management Tools](#memory-management-tools)
7. [Building PMDK on Windows](#building-pmdk-on-windows)
* [Testing Libraries](#testing-libraries-on-windows)
8. [Experimental Packages](#experimental-packages)
* [librpmem and rpmemd packages](#the-librpmem-and-rpmemd-packages)
* [Experimental support for 64-bit ARM](#experimental-support-for-64-bit-arm)
9. [Contact Us](#contact-us)
## Libraries and Utilities
Available Libraries:
- [libpmem](https://pmem.io/pmdk/libpmem/): provides low level persistent memory support
- [libpmemobj](https://pmem.io/pmdk/libpmemobj/): provides a transactional object store, providing memory allocation, transactions, and general facilities for persistent memory programming.
- [libpmemblk](https://pmem.io/pmdk/libpmemblk/): supports arrays of pmem-resident blocks, all the same size, that are atomically updated.
- [libpmemlog](https://pmem.io/pmdk/libpmemlog/): provides a pmem-resident log file.
- [libpmempool](https://pmem.io/pmdk/libpmempool/): provides support for off-line pool management and diagnostics.
- [librpmem](https://pmem.io/pmdk/librpmem/)<sup>1</sup>: provides low-level support for remote access to persistent memory utilizing RDMA-capable RNICs.
If you're looking for *libvmem* and *libvmmalloc*, they have been moved to a
[separate repository](https://github.com/pmem/vmem).
Available Utilities:
- [pmempool](https://pmem.io/pmdk/pmempool/): Manage and analyze persistent memory pools with this stand-alone utility
- [pmemcheck](https://pmem.io/2015/07/17/pmemcheck-basic.html): Use dynamic runtime analysis with an enhanced version of Valgrind for use with persistent memory.
Currently these libraries only work on 64-bit Linux, Windows<sup>2</sup>, and 64-bit FreeBSD 11+<sup>3</sup>.
For information on how these libraries are licensed, see our [LICENSE](LICENSE) file.
><sup>1</sup> Not supported on Windows.
>
><sup>2</sup> PMDK for Windows is feature complete, but not yet considered production quality.
>
><sup>3</sup> DAX and **libfabric** are not yet supported in FreeBSD, so at this time PMDK is available as a technical preview release for development purposes.
## Getting Started
Getting Started with Persistent Memory Programming is a tutorial series created by Intel Architect, Andy Rudoff. In this tutorial, you will be introduced to persistent memory programming and learn how to apply it to your applications.
- Part 1: [What is Persistent Memory?](https://software.intel.com/en-us/persistent-memory/get-started/series)
- Part 2: [Describing The SNIA Programming Model](https://software.intel.com/en-us/videos/the-nvm-programming-model-persistent-memory-programming-series)
- Part 3: [Introduction to PMDK Libraries](https://software.intel.com/en-us/videos/intro-to-the-nvm-libraries-persistent-memory-programming-series)
- Part 4: [Thinking Transactionally](https://software.intel.com/en-us/videos/thinking-transactionally-persistent-memory-programming-series)
- Part 5: [A C++ Example](https://software.intel.com/en-us/videos/a-c-example-persistent-memory-programming-series)
Additionally, we recommend reading [Introduction to Programming with Persistent Memory from Intel](https://software.intel.com/en-us/articles/introduction-to-programming-with-persistent-memory-from-intel)
## Version Conventions
- **Builds** are tagged something like `0.2+b1`, which means _Build 1 on top of version 0.2_
- **Release Candidates** have a '-rc{version}' tag, e.g. `0.2-rc3, meaning _Release Candidate 3 for version 0.2_
- **Stable Releases** use a _major.minor_ tag like `0.2`
## Pre-Built Packages for Windows
The recommended and easiest way to install PMDK on Windows is to use Microsoft vcpkg. Vcpkg is an open source tool and ecosystem created for library management.
To install the latest PMDK release and link it to your Visual Studio solution you first need to clone and set up vcpkg on your machine as described on the [vcpkg github page](https://github.com/Microsoft/vcpkg) in **Quick Start** section.
In brief:
```
> git clone https://github.com/Microsoft/vcpkg
> cd vcpkg
> .\bootstrap-vcpkg.bat
> .\vcpkg integrate install
> .\vcpkg install pmdk:x64-windows
```
The last command can take a while - it is PMDK building and installation time.
After a successful completion of all of the above steps, the libraries are ready
to be used in Visual Studio and no additional configuration is required.
Just open VS with your already existing project or create a new one
(remember to use platform **x64**) and then include headers to project as you always do.
## Dependencies
Required packages for each supported OS are listed below. It is important to note that some tests and example applications require additional packages, but they do not interrupt building if they are missing. An appropriate message is displayed instead. For details please read the DEPENDENCIES section in the appropriate README file.
See our **[Dockerfiles](utils/docker/images)**
to get an idea what packages are required to build the entire PMDK,
with all the tests and examples on the _Travis-CI_ system.
### Linux
You will need to install the following required packages on the build system:
* **autoconf**
* **pkg-config**
* **libndctl-devel** (v63 or later)<sup>1</sup>
* **libdaxctl-devel** (v63 or later)
The following packages are required only by selected PMDK components
or features:
* **libfabric** (v1.4.2 or later) -- required by **librpmem**
><sup>1</sup> PMDK depends on libndctl to support RAS features. It is possible
to disable this support by passing NDCTL_ENABLE=n to "make", but we strongly
discourage users from doing that. Disabling NDCTL strips PMDK from ability to
detect hardware failures, which may lead to silent data corruption.
For information how to disable RAS at runtime for kernels prior to 5.0.4 please
see https://github.com/pmem/pmdk/issues/4207.
### Windows
* **MS Visual Studio 2015**
* [Windows SDK 10.0.17134.12](https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk)
* **perl** (i.e. [StrawberryPerl](http://strawberryperl.com/))
* **PowerShell 5**
### FreeBSD
* **autoconf**
* **bash**
* **binutils**
* **coreutils**
* **e2fsprogs-libuuid**
* **gmake**
* **libunwind**
* **ncurses**<sup>4</sup>
* **pkgconf**
><sup>4</sup> The pkg version of ncurses is required for proper operation; the base version included in FreeBSD is not sufficient.
## Building PMDK on Linux or FreeBSD
To build from source, clone this tree:
```
$ git clone https://github.com/pmem/pmdk
$ cd pmdk
```
For a stable version, checkout a [release tag](https://github.com/pmem/pmdk/releases) as follows. Otherwise skip this step to build the latest development release.
```
$ git checkout tags/1.9.2
```
Once the build system is setup, the Persistent Memory Development Kit is built using the `make` command at the top level:
```
$ make
```
For FreeBSD, use `gmake` rather than `make`.
By default, all code is built with the `-Werror` flag, which fails
the whole build when the compiler emits any warning. This is very useful during
development, but can be annoying in deployment. If you want to **disable -Werror**,
use the EXTRA_CFLAGS variable:
```
$ make EXTRA_CFLAGS="-Wno-error"
```
>or
```
$ make EXTRA_CFLAGS="-Wno-error=$(type-of-warning)"
```
### Make Options
There are many options that follow `make`. If you want to invoke make with the same variables multiple times, you can create a user.mk file in the top level directory and put all variables there.
For example:
```
$ cat user.mk
EXTRA_CFLAGS_RELEASE = -ggdb -fno-omit-frame-pointer
PATH += :$HOME/valgrind/bin
```
This feature is intended to be used only by developers and it may not work for all variables. Please do not file bug reports about it. Just fix it and make a PR.
**Built-in tests:** can be compiled and ran with different compiler. To do this, you must provide the `CC` and `CXX` variables. These variables are independent and setting `CC=clang` does not set `CXX=clang++`.
For example:
```
$ make CC=clang CXX=clang++
```
Once make completes, all the libraries and examples are built. You can play with the library within the build tree, or install it locally on your machine. For information about running different types of tests, please refer to the [src/test/README](src/test/README).
**Installing the library** is convenient since it installs man pages and libraries in the standard system locations:
```
(as root...)
# make install
```
To install this library into **other locations**, you can use the `prefix` variable, e.g.:
```
$ make install prefix=/usr/local
```
This will install files to /usr/local/lib, /usr/local/include /usr/local/share/man.
**Prepare library for packaging** can be done using the DESTDIR variable, e.g.:
```
$ make install DESTDIR=/tmp
```
This will install files to /tmp/usr/lib, /tmp/usr/include /tmp/usr/share/man.
**Man pages** (groff files) are generated as part of the `install` rule. To generate the documentation separately, run:
```
$ make doc
```
This call requires the following dependencies: **pandoc**. Pandoc is provided by the hs-pandoc package on FreeBSD.
**Install copy of source tree** can be done by specifying the path where you want it installed.
```
$ make source DESTDIR=some_path
```
For this example, it will be installed at $(DESTDIR)/pmdk.
**Build rpm packages** on rpm-based distributions is done by:
```
$ make rpm
```
To build rpm packages without running tests:
```
$ make BUILD_PACKAGE_CHECK=n rpm
```
This requires **rpmbuild** to be installed.
**Build dpkg packages** on Debian-based distributions is done by:
```
$ make dpkg
```
To build dpkg packages without running tests:
```
$ make BUILD_PACKAGE_CHECK=n dpkg
```
This requires **devscripts** to be installed.
### Testing Libraries on Linux and FreeBSD
Before running the tests, you may need to prepare a test configuration file (src/test/testconfig.sh). Please see the available configuration settings in the example file [src/test/testconfig.sh.example](src/test/testconfig.sh.example).
To build and run the **unit tests**:
```
$ make check
```
To run a specific **subset of tests**, run for example:
```
$ make check TEST_TYPE=short TEST_BUILD=debug TEST_FS=pmem
```
To **modify the timeout** which is available for **check** type tests, run:
```
$ make check TEST_TIME=1m
```
This will set the timeout to 1 minute.
Please refer to the **src/test/README** for more details on how to
run different types of tests.
### Memory Management Tools
The PMDK libraries support standard Valgrind DRD, Helgrind and Memcheck, as well as a PM-aware version of [Valgrind](https://github.com/pmem/valgrind) (not yet available for FreeBSD). By default, support for all tools is enabled. If you wish to disable it, supply the compiler with **VG_\<TOOL\>_ENABLED** flag set to 0, for example:
```
$ make EXTRA_CFLAGS=-DVG_MEMCHECK_ENABLED=0
```
**VALGRIND_ENABLED** flag, when set to 0, disables all Valgrind tools
(drd, helgrind, memcheck and pmemcheck).
The **SANITIZE** flag allows the libraries to be tested with various
sanitizers. For example, to test the libraries with AddressSanitizer
and UndefinedBehaviorSanitizer, run:
```
$ make SANITIZE=address,undefined clobber check
```
## Building PMDK on Windows
Clone the PMDK tree and open the solution:
```
> git clone https://github.com/pmem/pmdk
> cd pmdk/src
> devenv PMDK.sln
```
Select the desired configuration (Debug or Release) and build the solution
(i.e. by pressing Ctrl-Shift-B).
### Testing Libraries on Windows
Before running the tests, you may need to prepare a test configuration file (src/test/testconfig.ps1). Please see the available configuration settings in the example file [src/test/testconfig.ps1.example](src/test/testconfig.ps1.example).
To **run the unit tests**, open the PowerShell console and type:
```
> cd pmdk/src/test
> RUNTESTS.ps1
```
To run a specific **subset of tests**, run for example:
```
> RUNTESTS.ps1 -b debug -t short
```
To run **just one test**, run for example:
```
> RUNTESTS.ps1 -b debug -i pmem_is_pmem
```
To **modify the timeout**, run:
```
> RUNTESTS.ps1 -o 3m
```
This will set the timeout to 3 minutes.
To **display all the possible options**, run:
```
> RUNTESTS.ps1 -h
```
Please refer to the **[src/test/README](src/test/README)** for more details on how to run different types of tests.
## Experimental Packages
Some components in the source tree are treated as experimental. By default,
those components are built but not installed (and thus not included in
packages).
If you want to build/install experimental packages run:
```
$ make EXPERIMENTAL=y [install,rpm,dpkg]
```
### The librpmem and rpmemd packages
**NOTE:**
The **libfabric** package required to build the **librpmem** and **rpmemd** is
not yet available on stable Debian-based distributions. This makes it
impossible to create Debian packages.
If you want to build Debian packages of **librpmem** and **rpmemd** run:
```
$ make RPMEM_DPKG=y dpkg
```
### Experimental Support for 64-bit ARM
There is an initial support for 64-bit ARM processors provided,
currently only for aarch64. All the PMDK libraries except **librpmem**
can be built for 64-bit ARM. The examples, tools and benchmarks
are not ported yet and may not get built on ARM cores.
**NOTE:**
The support for ARM processors is highly experimental. The libraries
are only validated to "early access" quality with Cortex-A53 processor.
## Contact Us
For more information on this library, contact
Piotr Balcer (piotr.balcer@intel.com),
Andy Rudoff (andy.rudoff@intel.com), or post to our
[Google group](https://groups.google.com/group/pmem).
| 15,938 | 40.4 | 403 |
md
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/appveyor.yml
|
version: 1.4.{build}
os: Visual Studio 2019
platform: x64
install:
- ps: Install-PackageProvider -Name NuGet -Force
- ps: Install-Module PsScriptAnalyzer -Force
configuration:
- Debug
- Release
environment:
solutionname: PMDK.sln
ex_solutionname: Examples.sln
matrix:
fast_finish: true
before_build:
- ps: >-
if ($Env:CONFIGURATION -eq "Release") {
utils/CSTYLE.ps1
if ($LASTEXITCODE -ne 0) {
exit 1
}
utils/CHECK_WHITESPACE.ps1
if ($LASTEXITCODE -ne 0) {
exit 1
}
utils/ps_analyze.ps1
if ($LASTEXITCODE -ne 0) {
exit 1
}
./utils/check_sdk_version.py -d .
if ($LASTEXITCODE -ne 0) {
exit 1
}
}
build_script:
- ps: msbuild src\$Env:solutionname /property:Configuration=$Env:CONFIGURATION /m /v:m
- ps: msbuild src\examples\$Env:ex_solutionname /property:Configuration=$Env:CONFIGURATION /m /v:m
after_build:
- ps: utils/CREATE-ZIP.ps1 -b $Env:CONFIGURATION
test_script:
- ps: >-
if ($true) {
cd src\test
md C:\temp
echo "`$Env:NON_PMEM_FS_DIR = `"C:\temp`"" >> testconfig.ps1
echo "`$Env:PMEM_FS_DIR = `"C:\temp`"" >> testconfig.ps1
echo "`$Env:PMEM_FS_DIR_FORCE_PMEM = `"1`"" >> testconfig.ps1
echo "`$Env:PMDK_NO_ABORT_MSG = `"1`"" >> testconfig.ps1
echo "`$Env:TM = `"1`"" >> testconfig.ps1
write-output "config = {
'unittest_log_level': 1,
'cacheline_fs_dir': 'C:\\temp',
'force_cacheline': True,
'page_fs_dir': 'C:\\temp',
'force_page': False,
'byte_fs_dir': 'C:\\temp',
'force_byte': True,
'tm': True,
'test_type': 'check',
'granularity': 'all',
'fs_dir_force_pmem': 1,
'keep_going': False,
'timeout': '4m',
'build': 'debug',
'force_enable': None,
'fail_on_skip': False,
'enable_admin_tests': False,
}" | out-file "testconfig.py" -encoding utf8
if ($Env:CONFIGURATION -eq "Debug") {
./RUNTESTS.ps1 -b debug -o 4m
if ($?) {
./RUNTESTS.py -b debug
}
}
if ($Env:CONFIGURATION -eq "Release") {
./RUNTESTS.ps1 -b nondebug -o 4m
if ($?) {
./RUNTESTS.py -b release
}
}
}
artifacts:
- path: 'src\x64\*.zip'
name: PMDK
| 2,382 | 23.822917 | 98 |
yml
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/build.sh
|
make clobber
make -j12 EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DRUN_COUNT=10000
make EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DRUN_COUNT=10000
cat run.sh
| 180 | 35.2 | 79 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/builddatastore.sh
|
make clobber
make -j12 EXTRA_CFLAGS+=-DRUN_COUNT=1
make EXTRA_CFLAGS+=-DRUN_COUNT=1
cat builddatastore.sh
| 111 | 21.4 | 38 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/.travis.yml
|
os: linux
dist: bionic
arch:
- ppc64le
language: c
services:
- docker
env:
global:
- GITHUB_REPO=pmem/pmdk
- DOCKERHUB_REPO=pmem/pmdk
- OS=ubuntu
- OS_VER=19.10
- MAKE_PKG=0
- PMDK_CC=gcc
- PMDK_CXX=g++
- REMOTE_TESTS=1
- VALGRIND=1
- SRC_CHECKERS=0
- EXPERIMENTAL=n
jobs:
- FAULT_INJECTION=1 TEST_BUILD=debug PUSH_IMAGE=1
- OS=fedora OS_VER=31 PMDK_CC=clang PMDK_CXX=clang++ TEST_BUILD=nondebug PUSH_IMAGE=1
- MAKE_PKG=1 REMOTE_TESTS=0 VALGRIND=0
- MAKE_PKG=1 REMOTE_TESTS=0 VALGRIND=0 OS=fedora OS_VER=31
- COVERAGE=1 FAULT_INJECTION=1 TEST_BUILD=debug
before_install:
- echo $TRAVIS_COMMIT_RANGE
- export HOST_WORKDIR=`pwd`
- cd utils/docker
- ./pull-or-rebuild-image.sh
script:
- ./build-CI.sh
after_success:
- source ./set-vars.sh
- if [[ -f $CI_FILE_PUSH_IMAGE_TO_REPO ]]; then ./images/push-image.sh; fi
| 903 | 20.023256 | 89 |
yml
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/builddatastoreredo.sh
|
make clobber
make -j12 EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_REDO
make EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_REDO
cat builddatastoreredo.sh
| 173 | 33.8 | 67 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/CODING_STYLE.md
|
# C Style and Coding Standards for Persistent Memory Development Kit
This document defines the coding standards and conventions for writing
PMDK code. To ensure readability and consistency within the code,
the contributed code must adhere to the rules below.
### Introduction
The Persistent Memory Development Kit coding style is quite similar to the style
used for the SunOS product.
A full description of that standard can be found
[here.](https://www.cis.upenn.edu/~lee/06cse480/data/cstyle.ms.pdf)
This document does not cover the entire set of recommendations and formatting rules
used in writing PMDK code, but rather focuses on some PMDK-specific conventions,
not described in the document mentioned above, as well as the ones the violation
of which is most frequently observed during the code review.
Also, keep in mind that more important than the particular style is **consistency**
of coding style. So, when modifying the existing code, the changes should be
coded in the same style as the file being modified.
### Code formatting
Most of the common stylistic errors can be detected by the
[style checker program](https://github.com/pmem/pmdk/blob/master/utils/cstyle)
included in the repo.
Simply run `make cstyle` or `CSTYLE.ps1` to verify if your code is well-formatted.
Here is the list of the most important rules:
- The limit of line length is 80 characters.
- Indent the code with TABs, not spaces. Tab width is 8 characters.
- Do not break user-visible strings (even when they are longer than 80 characters)
- Put each variable declaration in a separate line.
- Do not use C++ comments (`//`).
- Spaces around operators are mandatory.
- No whitespace is allowed at the end of line.
- For multi-line macros, do not put whitespace before `\` character.
- Precede definition of each function with a brief, non-trivial description.
(Usually a single line is enough.)
- Use `XXX` tag to indicate a hack, problematic code, or something to be done.
- For pointer variables, place the `*` close to the variable name not pointer type.
- Avoid unnecessary variable initialization.
- Never type `unsigned int` - just use `unsigned` in such case.
Same with `long int` and `long`, etc.
- Sized types like `uint32_t`, `int64_t` should be used when there is an on-media format.
Otherwise, just use `unsigned`, `long`, etc.
- Functions with local scope must be declared as `static`.
### License & copyright
- Make sure you have the right to submit your contribution under the BSD license,
especially if it is based upon previous work.
See [CONTRIBUTING.md](https://github.com/pmem/pmdk/blob/master/CONTRIBUTING.md) for details.
- A copy of the [BSD-style License](https://github.com/pmem/pmdk/blob/master/LICENSE)
must be placed at the beginning of each source file, script or man page
(Obviously, it does not apply to README's, Visual Studio projects and \*.match files.)
- When adding a new file to the repo, or when making a contribution to an existing
file, feel free to put your copyright string on top of it.
### Naming convention
- Keep identifier names short, but meaningful. One-letter variables are discouraged.
- Use proper prefix for function name, depending on the module it belongs to.
- Use *under_score* pattern for function/variable names. Please, do not use
CamelCase or Hungarian notation.
- UPPERCASE constant/macro/enum names.
- Capitalize first letter for variables with global or module-level scope.
- Avoid using `l` as a variable name, because it is hard to distinguish `l` from `1`
on some displays.
### Multi-OS support (Linux/FreeBSD/Windows)
- Do not add `#ifdef <OS>` sections lightly. They should be treated as technical
debt and avoided when possible.
- Use `_WIN32` macro for conditional directives when including code using
Windows-specific API.
- Use `__FreeBSD__` macro for conditional directives for FreeBSD-specific code.
- Use `_MSC_VER` macro for conditional directives when including code using VC++
or gcc specific extensions.
- In case of large portions of code (i.e. a whole function) that have different
implementation for each OS, consider moving them to separate files.
(i.e. *xxx_linux.c*, *xxx_freebsd.c* and *xxx_windows.c*)
- Keep in mind that `long int` is always 32-bit in VC++, even when building for
64-bit platforms. Remember to use `long long` types whenever it applies, as well
as proper formatting strings and type suffixes (i.. `%llu`, `ULL`).
- Standard compliant solutions should be used in preference of compiler-specific ones.
(i.e. static inline functions versus statement expressions)
- Do not use formatting strings that are not supported by Windows implementations
of printf()/scanf() family. (like `%m`)
- It is recommended to use `PRI*` and `SCN*` macros in printf()/scanf() functions
for width-based integral types (`uint32_t`, `int64_t`, etc.).
### Debug traces and assertions
- Put `LOG(3, ...)` at the beginning of each function. Consider using higher
log level for most frequently called routines.
- Make use of `COMPILE_ERROR_ON` and `ASSERT*` macros.
- Use `ERR()` macro to log error messages.
### Unit tests
- There **must** be unit tests provided for each new function/module added.
- Test scripts **must** start with `#!/usr/bin/env <shell>` for portability between Linux and FreeBSD.
- Please, see [this](https://github.com/pmem/pmdk/blob/master/src/test/README)
and [that](https://github.com/pmem/pmdk/blob/master/src/test/unittest/README)
document to get familiar with
our test framework and the guidelines on how to write and run unit tests.
### Commit messages
All commit lines (entered when you run `git commit`) must follow the common
conventions for git commit messages:
- The first line is a short summary, no longer than **50 characters,** starting
with an area name and then a colon. There should be no period after
the short summary.
- Valid area names are: **pmem, pmem2, obj, blk, log,
test, doc, daxio, pmreorder, pool** (for *libpmempool* and *pmempool*), **rpmem**
(for *librpmem* and *rpmemd*), **benchmark, examples, core** and **common** (for everything else).
- It is acceptable for the short summary to be the only thing in the commit
message if it is a trivial change. Otherwise, the second line must be
a blank line.
- Starting at the third line, additional information is given in complete
English sentences and, optionally, bulleted points. This content must not
extend beyond **column 72.**
- The English sentences should be written in the imperative, so you say
"Fix bug X" instead of "Fixed bug X" or "Fixes bug X".
- Bullet points should use hanging indents when they take up more than
one line (see example below).
- There can be any number of paragraphs, separated by a blank line, as many
as it takes to describe the change.
- Any references to GitHub issues are at the end of the commit message.
For example, here is a properly-formatted commit message:
```
doc: fix code formatting in man pages
This section contains paragraph style text with complete English
sentences. There can be as many paragraphs as necessary.
- Bullet points are typically sentence fragments
- The first word of the bullet point is usually capitalized and
if the point is long, it is continued with a hanging indent
- The sentence fragments don't typically end with a period
Ref: pmem/issues#1
```
| 7,335 | 51.028369 | 102 |
md
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/.codecov.yml
|
ignore:
- src/windows/
- src/test/
- src/common/valgrind/
- src/benchmarks/
comment:
layout: "diff"
behavior: default
require_changes: yes
parsers:
gcov:
branch_detection:
conditional: false
loop: false
method: false
macro: false
| 276 | 13.578947 | 24 |
yml
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/buildall.sh
|
make clobber
make -j12 EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER EXTRA_CFLAGS+=-DRUN_COUNT=10000
make EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER EXTRA_CFLAGS+=-DRUN_COUNT=10000
cat run.sh
| 300 | 59.2 | 139 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_config.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* rpmemd_config.h -- internal definitions for rpmemd config
*/
#include <stdint.h>
#include <stdbool.h>
#ifndef RPMEMD_DEFAULT_LOG_FILE
#define RPMEMD_DEFAULT_LOG_FILE ("/var/log/" DAEMON_NAME ".log")
#endif
#ifndef RPMEMD_GLOBAL_CONFIG_FILE
#define RPMEMD_GLOBAL_CONFIG_FILE ("/etc/" DAEMON_NAME "/" DAEMON_NAME\
".conf")
#endif
#define RPMEMD_USER_CONFIG_FILE ("." DAEMON_NAME ".conf")
#define RPMEM_DEFAULT_MAX_LANES 1024
#define RPMEM_DEFAULT_NTHREADS 0
#define HOME_ENV "HOME"
#define HOME_STR_PLACEHOLDER ("$" HOME_ENV)
struct rpmemd_config {
char *log_file;
char *poolset_dir;
const char *rm_poolset;
bool force;
bool pool_set;
bool persist_apm;
bool persist_general;
bool use_syslog;
uint64_t max_lanes;
enum rpmemd_log_level log_level;
size_t nthreads;
};
int rpmemd_config_read(struct rpmemd_config *config, int argc, char *argv[]);
void rpmemd_config_free(struct rpmemd_config *config);
| 1,012 | 21.021739 | 77 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_log.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* rpmemd_log.c -- rpmemd logging functions definitions
*/
#include <errno.h>
#include <stdio.h>
#include <syslog.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include "rpmemd_log.h"
#include "os.h"
#include "valgrind_internal.h"
#define RPMEMD_SYSLOG_OPTS (LOG_NDELAY | LOG_PID)
#define RPMEMD_SYSLOG_FACILITY (LOG_USER)
#define RPMEMD_DEFAULT_FH stderr
#define RPMEMD_MAX_MSG ((size_t)8192)
#define RPMEMD_MAX_PREFIX ((size_t)256)
enum rpmemd_log_level rpmemd_log_level;
static char *rpmemd_ident;
static int rpmemd_use_syslog;
static FILE *rpmemd_log_file;
static char rpmemd_prefix_buff[RPMEMD_MAX_PREFIX];
static const char *rpmemd_log_level_str[MAX_RPD_LOG] = {
[RPD_LOG_ERR] = "err",
[RPD_LOG_WARN] = "warn",
[RPD_LOG_NOTICE] = "notice",
[RPD_LOG_INFO] = "info",
[_RPD_LOG_DBG] = "debug",
};
static int rpmemd_level2prio[MAX_RPD_LOG] = {
[RPD_LOG_ERR] = LOG_ERR,
[RPD_LOG_WARN] = LOG_WARNING,
[RPD_LOG_NOTICE] = LOG_NOTICE,
[RPD_LOG_INFO] = LOG_INFO,
[_RPD_LOG_DBG] = LOG_DEBUG,
};
/*
* rpmemd_log_basename -- similar to POSIX basename, but without handling for
* trailing slashes.
*/
static const char *
rpmemd_log_basename(const char *fname)
{
const char *s;
if (fname == NULL)
return "(null)";
s = strrchr(fname, '/');
if (s != NULL)
return s + 1;
else
return fname;
}
/*
* rpmemd_log_level_from_str -- converts string to log level value
*/
enum rpmemd_log_level
rpmemd_log_level_from_str(const char *str)
{
if (!str)
return MAX_RPD_LOG;
for (enum rpmemd_log_level level = 0; level < MAX_RPD_LOG; level++) {
if (strcmp(rpmemd_log_level_str[level], str) == 0)
return level;
}
return MAX_RPD_LOG;
}
/*
* rpmemd_log_level_to_str -- converts log level enum to string
*/
const char *
rpmemd_log_level_to_str(enum rpmemd_log_level level)
{
if (level >= MAX_RPD_LOG)
return NULL;
return rpmemd_log_level_str[level];
}
/*
* rpmemd_log_init -- inititalize logging subsystem
*
* ident - string prepended to every message
* use_syslog - use syslog instead of standard output
*/
int
rpmemd_log_init(const char *ident, const char *fname, int use_syslog)
{
rpmemd_use_syslog = use_syslog;
if (rpmemd_use_syslog) {
openlog(rpmemd_ident, RPMEMD_SYSLOG_OPTS,
RPMEMD_SYSLOG_FACILITY);
} else {
rpmemd_ident = strdup(ident);
if (!rpmemd_ident) {
perror("strdup");
return -1;
}
if (fname) {
rpmemd_log_file = os_fopen(fname, "a");
if (!rpmemd_log_file) {
perror(fname);
free(rpmemd_ident);
rpmemd_ident = NULL;
return -1;
}
} else {
rpmemd_log_file = RPMEMD_DEFAULT_FH;
}
}
return 0;
}
/*
* rpmemd_log_close -- deinitialize logging subsystem
*/
void
rpmemd_log_close(void)
{
if (rpmemd_use_syslog) {
closelog();
} else {
if (rpmemd_log_file != RPMEMD_DEFAULT_FH)
fclose(rpmemd_log_file);
rpmemd_log_file = NULL;
free(rpmemd_ident);
rpmemd_ident = NULL;
}
}
/*
* rpmemd_prefix -- set prefix for every message
*/
int
rpmemd_prefix(const char *fmt, ...)
{
if (!fmt) {
rpmemd_prefix_buff[0] = '\0';
return 0;
}
va_list ap;
va_start(ap, fmt);
int ret = vsnprintf(rpmemd_prefix_buff, RPMEMD_MAX_PREFIX,
fmt, ap);
va_end(ap);
if (ret < 0)
return -1;
return 0;
}
/*
* rpmemd_log -- main logging function
*/
void
rpmemd_log(enum rpmemd_log_level level, const char *fname, int lineno,
const char *fmt, ...)
{
if (!rpmemd_use_syslog && level > rpmemd_log_level)
return;
char buff[RPMEMD_MAX_MSG];
size_t cnt = 0;
int ret;
if (fname) {
ret = util_snprintf(&buff[cnt], RPMEMD_MAX_MSG - cnt,
"[%s:%d] ", rpmemd_log_basename(fname), lineno);
if (ret < 0)
RPMEMD_FATAL("snprintf failed: %d", errno);
cnt += (size_t)ret;
}
if (rpmemd_prefix_buff[0]) {
ret = util_snprintf(&buff[cnt], RPMEMD_MAX_MSG - cnt,
"%s ", rpmemd_prefix_buff);
if (ret < 0)
RPMEMD_FATAL("snprintf failed: %d", errno);
cnt += (size_t)ret;
}
const char *errorstr = "";
const char *prefix = "";
const char *suffix = "\n";
if (fmt) {
if (*fmt == '!') {
fmt++;
errorstr = strerror(errno);
prefix = ": ";
}
va_list ap;
va_start(ap, fmt);
ret = vsnprintf(&buff[cnt], RPMEMD_MAX_MSG - cnt, fmt, ap);
va_end(ap);
if (ret < 0)
RPMEMD_FATAL("vsnprintf failed");
if ((unsigned)ret >= RPMEMD_MAX_MSG - cnt)
RPMEMD_FATAL("overflow(3): %d >= %lu", ret,
RPMEMD_MAX_MSG - cnt);
cnt += (size_t)ret;
ret = util_snprintf(&buff[cnt], RPMEMD_MAX_MSG - cnt,
"%s%s%s", prefix, errorstr, suffix);
if (ret < 0)
RPMEMD_FATAL("snprintf failed: %d", errno);
cnt += (size_t)ret;
}
buff[cnt] = 0;
if (rpmemd_use_syslog) {
int prio = rpmemd_level2prio[level];
syslog(prio, "%s", buff);
} else {
/* to suppress drd false-positive */
/* XXX: confirm real nature of this issue: pmem/issues#863 */
#ifdef SUPPRESS_FPUTS_DRD_ERROR
VALGRIND_ANNOTATE_IGNORE_READS_BEGIN();
VALGRIND_ANNOTATE_IGNORE_WRITES_BEGIN();
#endif
fprintf(rpmemd_log_file, "%s", buff);
fflush(rpmemd_log_file);
#ifdef SUPPRESS_FPUTS_DRD_ERROR
VALGRIND_ANNOTATE_IGNORE_READS_END();
VALGRIND_ANNOTATE_IGNORE_WRITES_END();
#endif
}
}
| 5,228 | 19.832669 | 77 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* rpmemd.c -- rpmemd main source file
*/
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "librpmem.h"
#include "rpmemd.h"
#include "rpmemd_log.h"
#include "rpmemd_config.h"
#include "rpmem_common.h"
#include "rpmemd_fip.h"
#include "rpmemd_obc.h"
#include "rpmemd_db.h"
#include "rpmemd_util.h"
#include "pool_hdr.h"
#include "os.h"
#include "os_thread.h"
#include "util.h"
#include "uuid.h"
#include "set.h"
/*
* rpmemd -- rpmem handle
*/
struct rpmemd {
struct rpmemd_obc *obc; /* out-of-band connection handle */
struct rpmemd_db *db; /* pool set database handle */
struct rpmemd_db_pool *pool; /* pool handle */
char *pool_desc; /* pool descriptor */
struct rpmemd_fip *fip; /* fabric provider handle */
struct rpmemd_config config; /* configuration */
enum rpmem_persist_method persist_method;
int closing; /* set when closing connection */
int created; /* pool created */
os_thread_t fip_thread;
int fip_running;
};
#ifdef DEBUG
/*
* bool2str -- convert bool to yes/no string
*/
static inline const char *
bool2str(int v)
{
return v ? "yes" : "no";
}
#endif
/*
* str_or_null -- return null string instead of NULL pointer
*/
static inline const char *
_str(const char *str)
{
if (!str)
return "(null)";
return str;
}
/*
* uuid2str -- convert uuid to string
*/
static const char *
uuid2str(const uuid_t uuid)
{
static char uuid_str[64] = {0, };
int ret = util_uuid_to_string(uuid, uuid_str);
if (ret != 0) {
return "(error)";
}
return uuid_str;
}
/*
* rpmemd_get_pm -- returns persist method based on configuration
*/
static enum rpmem_persist_method
rpmemd_get_pm(struct rpmemd_config *config)
{
enum rpmem_persist_method ret = RPMEM_PM_GPSPM;
if (config->persist_apm)
ret = RPMEM_PM_APM;
return ret;
}
/*
* rpmemd_db_get_status -- convert error number to status for db operation
*/
static int
rpmemd_db_get_status(int err)
{
switch (err) {
case EEXIST:
return RPMEM_ERR_EXISTS;
case EACCES:
return RPMEM_ERR_NOACCESS;
case ENOENT:
return RPMEM_ERR_NOEXIST;
case EWOULDBLOCK:
return RPMEM_ERR_BUSY;
case EBADF:
return RPMEM_ERR_BADNAME;
case EINVAL:
return RPMEM_ERR_POOL_CFG;
default:
return RPMEM_ERR_FATAL;
}
}
/*
* rpmemd_check_pool -- verify pool parameters
*/
static int
rpmemd_check_pool(struct rpmemd *rpmemd, const struct rpmem_req_attr *req,
int *status)
{
if (rpmemd->pool->pool_size < RPMEM_MIN_POOL) {
RPMEMD_LOG(ERR, "invalid pool size -- must be >= %zu",
RPMEM_MIN_POOL);
*status = RPMEM_ERR_POOL_CFG;
return -1;
}
if (rpmemd->pool->pool_size < req->pool_size) {
RPMEMD_LOG(ERR, "requested size is too big");
*status = RPMEM_ERR_BADSIZE;
return -1;
}
return 0;
}
/*
* rpmemd_deep_persist -- perform deep persist operation
*/
static int
rpmemd_deep_persist(const void *addr, size_t size, void *ctx)
{
struct rpmemd *rpmemd = (struct rpmemd *)ctx;
return util_replica_deep_persist(addr, size, rpmemd->pool->set, 0);
}
/*
* rpmemd_common_fip_init -- initialize fabric provider
*/
static int
rpmemd_common_fip_init(struct rpmemd *rpmemd, const struct rpmem_req_attr *req,
struct rpmem_resp_attr *resp, int *status)
{
/* register the whole pool with header in RDMA */
void *addr = (void *)((uintptr_t)rpmemd->pool->pool_addr);
struct rpmemd_fip_attr fip_attr = {
.addr = addr,
.size = req->pool_size,
.nlanes = req->nlanes,
.nthreads = rpmemd->config.nthreads,
.provider = req->provider,
.persist_method = rpmemd->persist_method,
.deep_persist = rpmemd_deep_persist,
.ctx = rpmemd,
.buff_size = req->buff_size,
};
const int is_pmem = rpmemd_db_pool_is_pmem(rpmemd->pool);
if (rpmemd_apply_pm_policy(&fip_attr.persist_method,
&fip_attr.persist,
&fip_attr.memcpy_persist,
is_pmem)) {
*status = RPMEM_ERR_FATAL;
goto err_fip_init;
}
const char *node = rpmem_get_ssh_conn_addr();
enum rpmem_err err;
rpmemd->fip = rpmemd_fip_init(node, NULL, &fip_attr, resp, &err);
if (!rpmemd->fip) {
*status = (int)err;
goto err_fip_init;
}
return 0;
err_fip_init:
return -1;
}
/*
* rpmemd_print_req_attr -- print request attributes
*/
static void
rpmemd_print_req_attr(const struct rpmem_req_attr *req)
{
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "pool descriptor: '%s'",
_str(req->pool_desc));
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "pool size: %lu", req->pool_size);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "nlanes: %u", req->nlanes);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "provider: %s",
rpmem_provider_to_str(req->provider));
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "buff_size: %lu", req->buff_size);
}
/*
* rpmemd_print_pool_attr -- print pool attributes
*/
static void
rpmemd_print_pool_attr(const struct rpmem_pool_attr *attr)
{
if (attr == NULL) {
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "NULL");
} else {
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "signature: '%s'",
_str(attr->signature));
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "major: %u", attr->major);
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "compat_features: 0x%x",
attr->compat_features);
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "incompat_features: 0x%x",
attr->incompat_features);
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "ro_compat_features: 0x%x",
attr->ro_compat_features);
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "poolset_uuid: %s",
uuid2str(attr->poolset_uuid));
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "uuid: %s",
uuid2str(attr->uuid));
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "next_uuid: %s",
uuid2str(attr->next_uuid));
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "prev_uuid: %s",
uuid2str(attr->prev_uuid));
}
}
/*
* rpmemd_print_resp_attr -- print response attributes
*/
static void
rpmemd_print_resp_attr(const struct rpmem_resp_attr *attr)
{
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "port: %u", attr->port);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "rkey: 0x%lx", attr->rkey);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "raddr: 0x%lx", attr->raddr);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "nlanes: %u", attr->nlanes);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "persist method: %s",
rpmem_persist_method_to_str(attr->persist_method));
}
/*
* rpmemd_fip_thread -- background thread for establishing in-band connection
*/
static void *
rpmemd_fip_thread(void *arg)
{
struct rpmemd *rpmemd = (struct rpmemd *)arg;
int ret;
RPMEMD_LOG(INFO, "waiting for in-band connection");
ret = rpmemd_fip_accept(rpmemd->fip, RPMEM_ACCEPT_TIMEOUT);
if (ret)
goto err_accept;
RPMEMD_LOG(NOTICE, "in-band connection established");
ret = rpmemd_fip_process_start(rpmemd->fip);
if (ret)
goto err_process_start;
return NULL;
err_process_start:
rpmemd_fip_close(rpmemd->fip);
err_accept:
return (void *)(uintptr_t)ret;
}
/*
* rpmemd_fip_start_thread -- start background thread for establishing
* in-band connection
*/
static int
rpmemd_fip_start_thread(struct rpmemd *rpmemd)
{
errno = os_thread_create(&rpmemd->fip_thread, NULL,
rpmemd_fip_thread, rpmemd);
if (errno) {
RPMEMD_LOG(ERR, "!creating in-band thread");
goto err_os_thread_create;
}
rpmemd->fip_running = 1;
return 0;
err_os_thread_create:
return -1;
}
/*
* rpmemd_fip_stop_thread -- stop background thread for in-band connection
*/
static int
rpmemd_fip_stop_thread(struct rpmemd *rpmemd)
{
RPMEMD_ASSERT(rpmemd->fip_running);
void *tret;
errno = os_thread_join(&rpmemd->fip_thread, &tret);
if (errno)
RPMEMD_LOG(ERR, "!waiting for in-band thread");
int ret = (int)(uintptr_t)tret;
if (ret)
RPMEMD_LOG(ERR, "in-band thread failed -- '%d'", ret);
return ret;
}
/*
* rpmemd_fip-stop -- stop in-band thread and stop processing thread
*/
static int
rpmemd_fip_stop(struct rpmemd *rpmemd)
{
int ret;
int fip_ret = rpmemd_fip_stop_thread(rpmemd);
if (fip_ret) {
RPMEMD_LOG(ERR, "!in-band thread failed");
}
if (!fip_ret) {
ret = rpmemd_fip_process_stop(rpmemd->fip);
if (ret) {
RPMEMD_LOG(ERR, "!stopping fip process failed");
}
}
rpmemd->fip_running = 0;
return fip_ret;
}
/*
* rpmemd_close_pool -- close pool and remove it if required
*/
static int
rpmemd_close_pool(struct rpmemd *rpmemd, int remove)
{
int ret = 0;
RPMEMD_LOG(NOTICE, "closing pool");
rpmemd_db_pool_close(rpmemd->db, rpmemd->pool);
RPMEMD_LOG(INFO, "pool closed");
if (remove) {
RPMEMD_LOG(NOTICE, "removing '%s'", rpmemd->pool_desc);
ret = rpmemd_db_pool_remove(rpmemd->db,
rpmemd->pool_desc, 0, 0);
if (ret) {
RPMEMD_LOG(ERR, "!removing pool '%s' failed",
rpmemd->pool_desc);
} else {
RPMEMD_LOG(INFO, "removed '%s'", rpmemd->pool_desc);
}
}
free(rpmemd->pool_desc);
return ret;
}
/*
* rpmemd_req_cleanup -- cleanup in-band connection and all resources allocated
* during open/create requests
*/
static void
rpmemd_req_cleanup(struct rpmemd *rpmemd)
{
if (!rpmemd->fip_running)
return;
int ret;
ret = rpmemd_fip_stop(rpmemd);
if (!ret) {
rpmemd_fip_close(rpmemd->fip);
rpmemd_fip_fini(rpmemd->fip);
}
int remove = rpmemd->created && ret;
rpmemd_close_pool(rpmemd, remove);
}
/*
* rpmemd_req_create -- handle create request
*/
static int
rpmemd_req_create(struct rpmemd_obc *obc, void *arg,
const struct rpmem_req_attr *req,
const struct rpmem_pool_attr *pool_attr)
{
RPMEMD_ASSERT(arg != NULL);
RPMEMD_LOG(NOTICE, "create request:");
rpmemd_print_req_attr(req);
RPMEMD_LOG(NOTICE, "pool attributes:");
rpmemd_print_pool_attr(pool_attr);
struct rpmemd *rpmemd = (struct rpmemd *)arg;
int ret;
int status = 0;
int err_send = 1;
struct rpmem_resp_attr resp;
memset(&resp, 0, sizeof(resp));
if (rpmemd->pool) {
RPMEMD_LOG(ERR, "pool already opened");
ret = -1;
status = RPMEM_ERR_FATAL;
goto err_pool_opened;
}
rpmemd->pool_desc = strdup(req->pool_desc);
if (!rpmemd->pool_desc) {
RPMEMD_LOG(ERR, "!allocating pool descriptor");
ret = -1;
status = RPMEM_ERR_FATAL;
goto err_strdup;
}
rpmemd->pool = rpmemd_db_pool_create(rpmemd->db,
req->pool_desc, 0, pool_attr);
if (!rpmemd->pool) {
ret = -1;
status = rpmemd_db_get_status(errno);
goto err_pool_create;
}
rpmemd->created = 1;
ret = rpmemd_check_pool(rpmemd, req, &status);
if (ret)
goto err_pool_check;
ret = rpmemd_common_fip_init(rpmemd, req, &resp, &status);
if (ret)
goto err_fip_init;
RPMEMD_LOG(NOTICE, "create request response: (status = %u)", status);
if (!status)
rpmemd_print_resp_attr(&resp);
ret = rpmemd_obc_create_resp(obc, status, &resp);
if (ret)
goto err_create_resp;
ret = rpmemd_fip_start_thread(rpmemd);
if (ret)
goto err_fip_start;
return 0;
err_fip_start:
err_create_resp:
err_send = 0;
rpmemd_fip_fini(rpmemd->fip);
err_fip_init:
err_pool_check:
rpmemd_db_pool_close(rpmemd->db, rpmemd->pool);
rpmemd_db_pool_remove(rpmemd->db, req->pool_desc, 0, 0);
err_pool_create:
free(rpmemd->pool_desc);
err_strdup:
err_pool_opened:
if (err_send)
ret = rpmemd_obc_create_resp(obc, status, &resp);
rpmemd->closing = 1;
return ret;
}
/*
* rpmemd_req_open -- handle open request
*/
static int
rpmemd_req_open(struct rpmemd_obc *obc, void *arg,
const struct rpmem_req_attr *req)
{
RPMEMD_ASSERT(arg != NULL);
RPMEMD_LOG(NOTICE, "open request:");
rpmemd_print_req_attr(req);
struct rpmemd *rpmemd = (struct rpmemd *)arg;
int ret;
int status = 0;
int err_send = 1;
struct rpmem_resp_attr resp;
memset(&resp, 0, sizeof(resp));
struct rpmem_pool_attr pool_attr;
memset(&pool_attr, 0, sizeof(pool_attr));
if (rpmemd->pool) {
RPMEMD_LOG(ERR, "pool already opened");
ret = -1;
status = RPMEM_ERR_FATAL;
goto err_pool_opened;
}
rpmemd->pool_desc = strdup(req->pool_desc);
if (!rpmemd->pool_desc) {
RPMEMD_LOG(ERR, "!allocating pool descriptor");
ret = -1;
status = RPMEM_ERR_FATAL;
goto err_strdup;
}
rpmemd->pool = rpmemd_db_pool_open(rpmemd->db,
req->pool_desc, 0, &pool_attr);
if (!rpmemd->pool) {
ret = -1;
status = rpmemd_db_get_status(errno);
goto err_pool_open;
}
RPMEMD_LOG(NOTICE, "pool attributes:");
rpmemd_print_pool_attr(&pool_attr);
ret = rpmemd_check_pool(rpmemd, req, &status);
if (ret)
goto err_pool_check;
ret = rpmemd_common_fip_init(rpmemd, req, &resp, &status);
if (ret)
goto err_fip_init;
RPMEMD_LOG(NOTICE, "open request response: (status = %u)", status);
if (!status)
rpmemd_print_resp_attr(&resp);
ret = rpmemd_obc_open_resp(obc, status, &resp, &pool_attr);
if (ret)
goto err_open_resp;
ret = rpmemd_fip_start_thread(rpmemd);
if (ret)
goto err_fip_start;
return 0;
err_fip_start:
err_open_resp:
err_send = 0;
rpmemd_fip_fini(rpmemd->fip);
err_fip_init:
err_pool_check:
rpmemd_db_pool_close(rpmemd->db, rpmemd->pool);
err_pool_open:
free(rpmemd->pool_desc);
err_strdup:
err_pool_opened:
if (err_send)
ret = rpmemd_obc_open_resp(obc, status, &resp, &pool_attr);
rpmemd->closing = 1;
return ret;
}
/*
* rpmemd_req_close -- handle close request
*/
static int
rpmemd_req_close(struct rpmemd_obc *obc, void *arg, int flags)
{
RPMEMD_ASSERT(arg != NULL);
RPMEMD_LOG(NOTICE, "close request");
struct rpmemd *rpmemd = (struct rpmemd *)arg;
rpmemd->closing = 1;
int ret;
int status = 0;
if (!rpmemd->pool) {
RPMEMD_LOG(ERR, "pool not opened");
status = RPMEM_ERR_FATAL;
return rpmemd_obc_close_resp(obc, status);
}
ret = rpmemd_fip_stop(rpmemd);
if (ret) {
status = RPMEM_ERR_FATAL;
} else {
rpmemd_fip_close(rpmemd->fip);
rpmemd_fip_fini(rpmemd->fip);
}
int remove = rpmemd->created &&
(status || (flags & RPMEM_CLOSE_FLAGS_REMOVE));
if (rpmemd_close_pool(rpmemd, remove))
RPMEMD_LOG(ERR, "closing pool failed");
RPMEMD_LOG(NOTICE, "close request response (status = %u)", status);
ret = rpmemd_obc_close_resp(obc, status);
return ret;
}
/*
* rpmemd_req_set_attr -- handle set attributes request
*/
static int
rpmemd_req_set_attr(struct rpmemd_obc *obc, void *arg,
const struct rpmem_pool_attr *pool_attr)
{
RPMEMD_ASSERT(arg != NULL);
RPMEMD_LOG(NOTICE, "set attributes request");
struct rpmemd *rpmemd = (struct rpmemd *)arg;
RPMEMD_ASSERT(rpmemd->pool != NULL);
int ret;
int status = 0;
int err_send = 1;
ret = rpmemd_db_pool_set_attr(rpmemd->pool, pool_attr);
if (ret) {
ret = -1;
status = rpmemd_db_get_status(errno);
goto err_set_attr;
}
RPMEMD_LOG(NOTICE, "new pool attributes:");
rpmemd_print_pool_attr(pool_attr);
ret = rpmemd_obc_set_attr_resp(obc, status);
if (ret)
goto err_set_attr_resp;
return ret;
err_set_attr_resp:
err_send = 0;
err_set_attr:
if (err_send)
ret = rpmemd_obc_set_attr_resp(obc, status);
return ret;
}
static struct rpmemd_obc_requests rpmemd_req = {
.create = rpmemd_req_create,
.open = rpmemd_req_open,
.close = rpmemd_req_close,
.set_attr = rpmemd_req_set_attr,
};
/*
* rpmemd_print_info -- print basic info and configuration
*/
static void
rpmemd_print_info(struct rpmemd *rpmemd)
{
RPMEMD_LOG(NOTICE, "ssh connection: %s",
_str(os_getenv("SSH_CONNECTION")));
RPMEMD_LOG(NOTICE, "user: %s", _str(os_getenv("USER")));
RPMEMD_LOG(NOTICE, "configuration");
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "pool set directory: '%s'",
_str(rpmemd->config.poolset_dir));
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "persist method: %s",
rpmem_persist_method_to_str(rpmemd->persist_method));
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "number of threads: %lu",
rpmemd->config.nthreads);
RPMEMD_DBG(RPMEMD_LOG_INDENT "persist APM: %s",
bool2str(rpmemd->config.persist_apm));
RPMEMD_DBG(RPMEMD_LOG_INDENT "persist GPSPM: %s",
bool2str(rpmemd->config.persist_general));
RPMEMD_DBG(RPMEMD_LOG_INDENT "use syslog: %s",
bool2str(rpmemd->config.use_syslog));
RPMEMD_DBG(RPMEMD_LOG_INDENT "log file: %s",
_str(rpmemd->config.log_file));
RPMEMD_DBG(RPMEMD_LOG_INDENT "log level: %s",
rpmemd_log_level_to_str(rpmemd->config.log_level));
}
int
main(int argc, char *argv[])
{
util_init();
int send_status = 1;
int ret = 1;
struct rpmemd *rpmemd = calloc(1, sizeof(*rpmemd));
if (!rpmemd) {
RPMEMD_LOG(ERR, "!calloc");
goto err_rpmemd;
}
rpmemd->obc = rpmemd_obc_init(STDIN_FILENO, STDOUT_FILENO);
if (!rpmemd->obc) {
RPMEMD_LOG(ERR, "out-of-band connection initialization");
goto err_obc;
}
if (rpmemd_log_init(DAEMON_NAME, NULL, 0)) {
RPMEMD_LOG(ERR, "logging subsystem initialization failed");
goto err_log_init;
}
if (rpmemd_config_read(&rpmemd->config, argc, argv) != 0) {
RPMEMD_LOG(ERR, "reading configuration failed");
goto err_config;
}
rpmemd_log_close();
rpmemd_log_level = rpmemd->config.log_level;
if (rpmemd_log_init(DAEMON_NAME, rpmemd->config.log_file,
rpmemd->config.use_syslog)) {
RPMEMD_LOG(ERR, "logging subsystem initialization"
" failed (%s, %d)", rpmemd->config.log_file,
rpmemd->config.use_syslog);
goto err_log_init_config;
}
RPMEMD_LOG(INFO, "%s version %s", DAEMON_NAME, SRCVERSION);
rpmemd->persist_method = rpmemd_get_pm(&rpmemd->config);
rpmemd->db = rpmemd_db_init(rpmemd->config.poolset_dir, 0666);
if (!rpmemd->db) {
RPMEMD_LOG(ERR, "!pool set db initialization");
goto err_db_init;
}
if (rpmemd->config.rm_poolset) {
RPMEMD_LOG(INFO, "removing '%s'",
rpmemd->config.rm_poolset);
if (rpmemd_db_pool_remove(rpmemd->db,
rpmemd->config.rm_poolset,
rpmemd->config.force,
rpmemd->config.pool_set)) {
RPMEMD_LOG(ERR, "removing '%s' failed",
rpmemd->config.rm_poolset);
ret = errno;
} else {
RPMEMD_LOG(NOTICE, "removed '%s'",
rpmemd->config.rm_poolset);
ret = 0;
}
send_status = 0;
goto out_rm;
}
ret = rpmemd_obc_status(rpmemd->obc, 0);
if (ret) {
RPMEMD_LOG(ERR, "writing status failed");
goto err_status;
}
rpmemd_print_info(rpmemd);
while (!ret) {
ret = rpmemd_obc_process(rpmemd->obc, &rpmemd_req, rpmemd);
if (ret) {
RPMEMD_LOG(ERR, "out-of-band connection"
" process failed");
goto err;
}
if (rpmemd->closing)
break;
}
rpmemd_db_fini(rpmemd->db);
rpmemd_config_free(&rpmemd->config);
rpmemd_log_close();
rpmemd_obc_fini(rpmemd->obc);
free(rpmemd);
return 0;
err:
rpmemd_req_cleanup(rpmemd);
err_status:
out_rm:
rpmemd_db_fini(rpmemd->db);
err_db_init:
err_log_init_config:
rpmemd_config_free(&rpmemd->config);
err_config:
rpmemd_log_close();
err_log_init:
if (send_status) {
if (rpmemd_obc_status(rpmemd->obc, (uint32_t)errno))
RPMEMD_LOG(ERR, "writing status failed");
}
rpmemd_obc_fini(rpmemd->obc);
err_obc:
free(rpmemd);
err_rpmemd:
return ret;
}
| 18,497 | 22.007463 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_log.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* rpmemd_log.h -- rpmemd logging functions declarations
*/
#include <string.h>
#include "util.h"
#define FORMAT_PRINTF(a, b) __attribute__((__format__(__printf__, (a), (b))))
/*
* The tab character is not allowed in rpmemd log,
* because it is not well handled by syslog.
* Please use RPMEMD_LOG_INDENT instead.
*/
#define RPMEMD_LOG_INDENT " "
#ifdef DEBUG
#define RPMEMD_LOG(level, fmt, arg...) do {\
COMPILE_ERROR_ON(strchr(fmt, '\t') != 0);\
rpmemd_log(RPD_LOG_##level, __FILE__, __LINE__, fmt, ## arg);\
} while (0)
#else
#define RPMEMD_LOG(level, fmt, arg...) do {\
COMPILE_ERROR_ON(strchr(fmt, '\t') != 0);\
rpmemd_log(RPD_LOG_##level, NULL, 0, fmt, ## arg);\
} while (0)
#endif
#ifdef DEBUG
#define RPMEMD_DBG(fmt, arg...) do {\
COMPILE_ERROR_ON(strchr(fmt, '\t') != 0);\
rpmemd_log(_RPD_LOG_DBG, __FILE__, __LINE__, fmt, ## arg);\
} while (0)
#else
#define RPMEMD_DBG(fmt, arg...) do {} while (0)
#endif
#define RPMEMD_ERR(fmt, arg...) do {\
RPMEMD_LOG(ERR, fmt, ## arg);\
} while (0)
#define RPMEMD_FATAL(fmt, arg...) do {\
RPMEMD_LOG(ERR, fmt, ## arg);\
abort();\
} while (0)
#define RPMEMD_ASSERT(cond) do {\
if (!(cond)) {\
rpmemd_log(RPD_LOG_ERR, __FILE__, __LINE__,\
"assertion fault: %s", #cond);\
abort();\
}\
} while (0)
enum rpmemd_log_level {
RPD_LOG_ERR,
RPD_LOG_WARN,
RPD_LOG_NOTICE,
RPD_LOG_INFO,
_RPD_LOG_DBG, /* disallow to use this with LOG macro */
MAX_RPD_LOG,
};
enum rpmemd_log_level rpmemd_log_level_from_str(const char *str);
const char *rpmemd_log_level_to_str(enum rpmemd_log_level level);
extern enum rpmemd_log_level rpmemd_log_level;
int rpmemd_log_init(const char *ident, const char *fname, int use_syslog);
void rpmemd_log_close(void);
int rpmemd_prefix(const char *fmt, ...) FORMAT_PRINTF(1, 2);
void rpmemd_log(enum rpmemd_log_level level, const char *fname,
int lineno, const char *fmt, ...) FORMAT_PRINTF(4, 5);
| 1,991 | 25.210526 | 77 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_util.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2018, Intel Corporation */
/*
* rpmemd_util.c -- rpmemd utility functions definitions
*/
#include <stdlib.h>
#include <unistd.h>
#include "libpmem.h"
#include "rpmem_common.h"
#include "rpmemd_log.h"
#include "rpmemd_util.h"
/*
* rpmemd_pmem_persist -- pmem_persist wrapper required to unify function
* pointer type with pmem_msync
*/
int
rpmemd_pmem_persist(const void *addr, size_t len)
{
pmem_persist(addr, len);
return 0;
}
/*
* rpmemd_flush_fatal -- APM specific flush function which should never be
* called because APM does not require flushes
*/
int
rpmemd_flush_fatal(const void *addr, size_t len)
{
RPMEMD_FATAL("rpmemd_flush_fatal should never be called");
}
/*
* rpmemd_persist_to_str -- convert persist function pointer to string
*/
static const char *
rpmemd_persist_to_str(int (*persist)(const void *addr, size_t len))
{
if (persist == rpmemd_pmem_persist) {
return "pmem_persist";
} else if (persist == pmem_msync) {
return "pmem_msync";
} else if (persist == rpmemd_flush_fatal) {
return "none";
} else {
return NULL;
}
}
/*
* rpmem_print_pm_policy -- print persistency method policy
*/
static void
rpmem_print_pm_policy(enum rpmem_persist_method persist_method,
int (*persist)(const void *addr, size_t len))
{
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "persist method: %s",
rpmem_persist_method_to_str(persist_method));
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "persist flush: %s",
rpmemd_persist_to_str(persist));
}
/*
* rpmem_memcpy_msync -- memcpy and msync
*/
static void *
rpmem_memcpy_msync(void *pmemdest, const void *src, size_t len)
{
void *ret = pmem_memcpy(pmemdest, src, len, PMEM_F_MEM_NOFLUSH);
pmem_msync(pmemdest, len);
return ret;
}
/*
* rpmemd_apply_pm_policy -- choose the persistency method and the flush
* function according to the pool type and the persistency method read from the
* config
*/
int
rpmemd_apply_pm_policy(enum rpmem_persist_method *persist_method,
int (**persist)(const void *addr, size_t len),
void *(**memcpy_persist)(void *pmemdest, const void *src, size_t len),
const int is_pmem)
{
switch (*persist_method) {
case RPMEM_PM_APM:
if (is_pmem) {
*persist_method = RPMEM_PM_APM;
*persist = rpmemd_flush_fatal;
} else {
*persist_method = RPMEM_PM_GPSPM;
*persist = pmem_msync;
}
break;
case RPMEM_PM_GPSPM:
*persist_method = RPMEM_PM_GPSPM;
*persist = is_pmem ? rpmemd_pmem_persist : pmem_msync;
break;
default:
RPMEMD_FATAL("invalid persist method: %d", *persist_method);
return -1;
}
/* this is for RPMEM_PERSIST_INLINE */
if (is_pmem)
*memcpy_persist = pmem_memcpy_persist;
else
*memcpy_persist = rpmem_memcpy_msync;
RPMEMD_LOG(NOTICE, "persistency policy:");
rpmem_print_pm_policy(*persist_method, *persist);
return 0;
}
| 2,839 | 22.666667 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_db.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* rpmemd_db.h -- internal definitions for rpmemd database of pool set files
*/
struct rpmemd_db;
struct rpmem_pool_attr;
/*
* struct rpmemd_db_pool -- remote pool context
*/
struct rpmemd_db_pool {
void *pool_addr;
size_t pool_size;
struct pool_set *set;
};
struct rpmemd_db *rpmemd_db_init(const char *root_dir, mode_t mode);
struct rpmemd_db_pool *rpmemd_db_pool_create(struct rpmemd_db *db,
const char *pool_desc, size_t pool_size,
const struct rpmem_pool_attr *rattr);
struct rpmemd_db_pool *rpmemd_db_pool_open(struct rpmemd_db *db,
const char *pool_desc, size_t pool_size, struct rpmem_pool_attr *rattr);
int rpmemd_db_pool_remove(struct rpmemd_db *db, const char *pool_desc,
int force, int pool_set);
int rpmemd_db_pool_set_attr(struct rpmemd_db_pool *prp,
const struct rpmem_pool_attr *rattr);
void rpmemd_db_pool_close(struct rpmemd_db *db, struct rpmemd_db_pool *prp);
void rpmemd_db_fini(struct rpmemd_db *db);
int rpmemd_db_check_dir(struct rpmemd_db *db);
int rpmemd_db_pool_is_pmem(struct rpmemd_db_pool *pool);
| 1,132 | 32.323529 | 76 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_obc.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2019, Intel Corporation */
/*
* rpmemd_obc.c -- rpmemd out-of-band connection definitions
*/
#include <stdlib.h>
#include <errno.h>
#include <stdint.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include "librpmem.h"
#include "rpmemd_log.h"
#include "rpmem_proto.h"
#include "rpmem_common.h"
#include "rpmemd_obc.h"
struct rpmemd_obc {
int fd_in;
int fd_out;
};
/*
* rpmemd_obc_check_proto_ver -- check protocol version
*/
static int
rpmemd_obc_check_proto_ver(unsigned major, unsigned minor)
{
if (major != RPMEM_PROTO_MAJOR ||
minor != RPMEM_PROTO_MINOR) {
RPMEMD_LOG(ERR, "unsupported protocol version -- %u.%u",
major, minor);
return -1;
}
return 0;
}
/*
* rpmemd_obc_check_msg_hdr -- check message header
*/
static int
rpmemd_obc_check_msg_hdr(struct rpmem_msg_hdr *hdrp)
{
switch (hdrp->type) {
case RPMEM_MSG_TYPE_OPEN:
case RPMEM_MSG_TYPE_CREATE:
case RPMEM_MSG_TYPE_CLOSE:
case RPMEM_MSG_TYPE_SET_ATTR:
/* all messages from obc to server are fine */
break;
default:
RPMEMD_LOG(ERR, "invalid message type -- %u", hdrp->type);
return -1;
}
if (hdrp->size < sizeof(struct rpmem_msg_hdr)) {
RPMEMD_LOG(ERR, "invalid message size -- %lu", hdrp->size);
return -1;
}
return 0;
}
/*
* rpmemd_obc_check_pool_desc -- check pool descriptor
*/
static int
rpmemd_obc_check_pool_desc(struct rpmem_msg_hdr *hdrp, size_t msg_size,
struct rpmem_msg_pool_desc *pool_desc)
{
size_t body_size = msg_size + pool_desc->size;
if (hdrp->size != body_size) {
RPMEMD_LOG(ERR, "message and pool descriptor size mismatch "
"-- is %lu should be %lu", hdrp->size, body_size);
return -1;
}
if (pool_desc->size < 2) {
RPMEMD_LOG(ERR, "invalid pool descriptor size -- %u "
"(must be >= 2)", pool_desc->size);
return -1;
}
if (pool_desc->desc[pool_desc->size - 1] != '\0') {
RPMEMD_LOG(ERR, "invalid pool descriptor "
"(must be null-terminated string)");
return -1;
}
size_t len = strlen((char *)pool_desc->desc) + 1;
if (pool_desc->size != len) {
RPMEMD_LOG(ERR, "invalid pool descriptor size -- is %lu "
"should be %u", len, pool_desc->size);
return -1;
}
return 0;
}
/*
* rpmemd_obc_check_provider -- check provider value
*/
static int
rpmemd_obc_check_provider(uint32_t provider)
{
if (provider == 0 || provider >= MAX_RPMEM_PROV) {
RPMEMD_LOG(ERR, "invalid provider -- %u", provider);
return -1;
}
return 0;
}
/*
* rpmemd_obc_ntoh_check_msg_create -- convert and check create request message
*/
static int
rpmemd_obc_ntoh_check_msg_create(struct rpmem_msg_hdr *hdrp)
{
int ret;
struct rpmem_msg_create *msg = (struct rpmem_msg_create *)hdrp;
rpmem_ntoh_msg_create(msg);
ret = rpmemd_obc_check_proto_ver(msg->c.major, msg->c.minor);
if (ret)
return ret;
ret = rpmemd_obc_check_pool_desc(hdrp, sizeof(*msg), &msg->pool_desc);
if (ret)
return ret;
ret = rpmemd_obc_check_provider(msg->c.provider);
if (ret)
return ret;
return 0;
}
/*
* rpmemd_obc_ntoh_check_msg_open -- convert and check open request message
*/
static int
rpmemd_obc_ntoh_check_msg_open(struct rpmem_msg_hdr *hdrp)
{
int ret;
struct rpmem_msg_open *msg = (struct rpmem_msg_open *)hdrp;
rpmem_ntoh_msg_open(msg);
ret = rpmemd_obc_check_proto_ver(msg->c.major, msg->c.minor);
if (ret)
return ret;
ret = rpmemd_obc_check_pool_desc(hdrp, sizeof(*msg), &msg->pool_desc);
if (ret)
return ret;
ret = rpmemd_obc_check_provider(msg->c.provider);
if (ret)
return ret;
return 0;
}
/*
* rpmemd_obc_ntoh_check_msg_close -- convert and check close request message
*/
static int
rpmemd_obc_ntoh_check_msg_close(struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_close *msg = (struct rpmem_msg_close *)hdrp;
rpmem_ntoh_msg_close(msg);
/* nothing to do */
return 0;
}
/*
* rpmemd_obc_ntoh_check_msg_set_attr -- convert and check set attributes
* request message
*/
static int
rpmemd_obc_ntoh_check_msg_set_attr(struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_set_attr *msg = (struct rpmem_msg_set_attr *)hdrp;
rpmem_ntoh_msg_set_attr(msg);
/* nothing to do */
return 0;
}
typedef int (*rpmemd_obc_ntoh_check_msg_fn)(struct rpmem_msg_hdr *hdrp);
static rpmemd_obc_ntoh_check_msg_fn rpmemd_obc_ntoh_check_msg[] = {
[RPMEM_MSG_TYPE_CREATE] = rpmemd_obc_ntoh_check_msg_create,
[RPMEM_MSG_TYPE_OPEN] = rpmemd_obc_ntoh_check_msg_open,
[RPMEM_MSG_TYPE_CLOSE] = rpmemd_obc_ntoh_check_msg_close,
[RPMEM_MSG_TYPE_SET_ATTR] = rpmemd_obc_ntoh_check_msg_set_attr,
};
/*
* rpmemd_obc_process_create -- process create request
*/
static int
rpmemd_obc_process_create(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg,
struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_create *msg = (struct rpmem_msg_create *)hdrp;
struct rpmem_req_attr req = {
.pool_size = msg->c.pool_size,
.nlanes = (unsigned)msg->c.nlanes,
.pool_desc = (char *)msg->pool_desc.desc,
.provider = (enum rpmem_provider)msg->c.provider,
.buff_size = msg->c.buff_size,
};
struct rpmem_pool_attr *rattr = NULL;
struct rpmem_pool_attr rpmem_attr;
unpack_rpmem_pool_attr(&msg->pool_attr, &rpmem_attr);
if (!util_is_zeroed(&rpmem_attr, sizeof(rpmem_attr)))
rattr = &rpmem_attr;
return req_cb->create(obc, arg, &req, rattr);
}
/*
* rpmemd_obc_process_open -- process open request
*/
static int
rpmemd_obc_process_open(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg,
struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_open *msg = (struct rpmem_msg_open *)hdrp;
struct rpmem_req_attr req = {
.pool_size = msg->c.pool_size,
.nlanes = (unsigned)msg->c.nlanes,
.pool_desc = (const char *)msg->pool_desc.desc,
.provider = (enum rpmem_provider)msg->c.provider,
.buff_size = msg->c.buff_size,
};
return req_cb->open(obc, arg, &req);
}
/*
* rpmemd_obc_process_close -- process close request
*/
static int
rpmemd_obc_process_close(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg,
struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_close *msg = (struct rpmem_msg_close *)hdrp;
return req_cb->close(obc, arg, (int)msg->flags);
}
/*
* rpmemd_obc_process_set_attr -- process set attributes request
*/
static int
rpmemd_obc_process_set_attr(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg,
struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_set_attr *msg = (struct rpmem_msg_set_attr *)hdrp;
struct rpmem_pool_attr *rattr = NULL;
struct rpmem_pool_attr rpmem_attr;
unpack_rpmem_pool_attr(&msg->pool_attr, &rpmem_attr);
if (!util_is_zeroed(&rpmem_attr, sizeof(rpmem_attr)))
rattr = &rpmem_attr;
return req_cb->set_attr(obc, arg, rattr);
}
typedef int (*rpmemd_obc_process_fn)(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg,
struct rpmem_msg_hdr *hdrp);
static rpmemd_obc_process_fn rpmemd_obc_process_cb[] = {
[RPMEM_MSG_TYPE_CREATE] = rpmemd_obc_process_create,
[RPMEM_MSG_TYPE_OPEN] = rpmemd_obc_process_open,
[RPMEM_MSG_TYPE_CLOSE] = rpmemd_obc_process_close,
[RPMEM_MSG_TYPE_SET_ATTR] = rpmemd_obc_process_set_attr,
};
/*
* rpmemd_obc_recv -- wrapper for read and decode data function
*/
static inline int
rpmemd_obc_recv(struct rpmemd_obc *obc, void *buff, size_t len)
{
return rpmem_xread(obc->fd_in, buff, len, 0);
}
/*
* rpmemd_obc_send -- wrapper for encode and write data function
*/
static inline int
rpmemd_obc_send(struct rpmemd_obc *obc, const void *buff, size_t len)
{
return rpmem_xwrite(obc->fd_out, buff, len, 0);
}
/*
* rpmemd_obc_msg_recv -- receive and check request message
*
* Return values:
* 0 - success
* < 0 - error
* 1 - obc disconnected
*/
static int
rpmemd_obc_msg_recv(struct rpmemd_obc *obc,
struct rpmem_msg_hdr **hdrpp)
{
struct rpmem_msg_hdr hdr;
struct rpmem_msg_hdr nhdr;
struct rpmem_msg_hdr *hdrp;
int ret;
ret = rpmemd_obc_recv(obc, &nhdr, sizeof(nhdr));
if (ret == 1) {
RPMEMD_LOG(NOTICE, "out-of-band connection disconnected");
return 1;
}
if (ret < 0) {
RPMEMD_LOG(ERR, "!receiving message header failed");
return ret;
}
memcpy(&hdr, &nhdr, sizeof(hdr));
rpmem_ntoh_msg_hdr(&hdr);
ret = rpmemd_obc_check_msg_hdr(&hdr);
if (ret) {
RPMEMD_LOG(ERR, "parsing message header failed");
return ret;
}
hdrp = malloc(hdr.size);
if (!hdrp) {
RPMEMD_LOG(ERR, "!allocating message buffer failed");
return -1;
}
memcpy(hdrp, &nhdr, sizeof(*hdrp));
size_t body_size = hdr.size - sizeof(hdr);
ret = rpmemd_obc_recv(obc, hdrp->body, body_size);
if (ret) {
RPMEMD_LOG(ERR, "!receiving message body failed");
goto err_recv_body;
}
ret = rpmemd_obc_ntoh_check_msg[hdr.type](hdrp);
if (ret) {
RPMEMD_LOG(ERR, "parsing message body failed");
goto err_body;
}
*hdrpp = hdrp;
return 0;
err_body:
err_recv_body:
free(hdrp);
return -1;
}
/*
* rpmemd_obc_init -- initialize rpmemd
*/
struct rpmemd_obc *
rpmemd_obc_init(int fd_in, int fd_out)
{
struct rpmemd_obc *obc = calloc(1, sizeof(*obc));
if (!obc) {
RPMEMD_LOG(ERR, "!allocating obc failed");
goto err_calloc;
}
obc->fd_in = fd_in;
obc->fd_out = fd_out;
return obc;
err_calloc:
return NULL;
}
/*
* rpmemd_obc_fini -- destroy obc
*/
void
rpmemd_obc_fini(struct rpmemd_obc *obc)
{
free(obc);
}
/*
* rpmemd_obc_status -- sends initial status to the client
*/
int
rpmemd_obc_status(struct rpmemd_obc *obc, uint32_t status)
{
return rpmemd_obc_send(obc, &status, sizeof(status));
}
/*
* rpmemd_obc_process -- wait for and process a message from client
*
* Return values:
* 0 - success
* < 0 - error
* 1 - client disconnected
*/
int
rpmemd_obc_process(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg)
{
RPMEMD_ASSERT(req_cb != NULL);
RPMEMD_ASSERT(req_cb->create != NULL);
RPMEMD_ASSERT(req_cb->open != NULL);
RPMEMD_ASSERT(req_cb->close != NULL);
RPMEMD_ASSERT(req_cb->set_attr != NULL);
struct rpmem_msg_hdr *hdrp = NULL;
int ret;
ret = rpmemd_obc_msg_recv(obc, &hdrp);
if (ret)
return ret;
RPMEMD_ASSERT(hdrp != NULL);
ret = rpmemd_obc_process_cb[hdrp->type](obc, req_cb, arg, hdrp);
free(hdrp);
return ret;
}
/*
* rpmemd_obc_create_resp -- send create request response message
*/
int
rpmemd_obc_create_resp(struct rpmemd_obc *obc,
int status, const struct rpmem_resp_attr *res)
{
struct rpmem_msg_create_resp resp = {
.hdr = {
.type = RPMEM_MSG_TYPE_CREATE_RESP,
.size = sizeof(struct rpmem_msg_create_resp),
.status = (uint32_t)status,
},
.ibc = {
.port = res->port,
.rkey = res->rkey,
.raddr = res->raddr,
.persist_method = res->persist_method,
.nlanes = res->nlanes,
},
};
rpmem_hton_msg_create_resp(&resp);
return rpmemd_obc_send(obc, &resp, sizeof(resp));
}
/*
* rpmemd_obc_open_resp -- send open request response message
*/
int
rpmemd_obc_open_resp(struct rpmemd_obc *obc,
int status, const struct rpmem_resp_attr *res,
const struct rpmem_pool_attr *pool_attr)
{
struct rpmem_msg_open_resp resp = {
.hdr = {
.type = RPMEM_MSG_TYPE_OPEN_RESP,
.size = sizeof(struct rpmem_msg_open_resp),
.status = (uint32_t)status,
},
.ibc = {
.port = res->port,
.rkey = res->rkey,
.raddr = res->raddr,
.persist_method = res->persist_method,
.nlanes = res->nlanes,
},
};
pack_rpmem_pool_attr(pool_attr, &resp.pool_attr);
rpmem_hton_msg_open_resp(&resp);
return rpmemd_obc_send(obc, &resp, sizeof(resp));
}
/*
* rpmemd_obc_close_resp -- send close request response message
*/
int
rpmemd_obc_close_resp(struct rpmemd_obc *obc,
int status)
{
struct rpmem_msg_close_resp resp = {
.hdr = {
.type = RPMEM_MSG_TYPE_CLOSE_RESP,
.size = sizeof(struct rpmem_msg_close_resp),
.status = (uint32_t)status,
},
};
rpmem_hton_msg_close_resp(&resp);
return rpmemd_obc_send(obc, &resp, sizeof(resp));
}
/*
* rpmemd_obc_set_attr_resp -- send set attributes request response message
*/
int
rpmemd_obc_set_attr_resp(struct rpmemd_obc *obc, int status)
{
struct rpmem_msg_set_attr_resp resp = {
.hdr = {
.type = RPMEM_MSG_TYPE_SET_ATTR_RESP,
.size = sizeof(struct rpmem_msg_set_attr_resp),
.status = (uint32_t)status,
},
};
rpmem_hton_msg_set_attr_resp(&resp);
return rpmemd_obc_send(obc, &resp, sizeof(resp));
}
| 12,309 | 21.422587 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_config.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* rpmemd_config.c -- rpmemd config source file
*/
#include <pwd.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <inttypes.h>
#include "rpmemd.h"
#include "rpmemd_log.h"
#include "rpmemd_config.h"
#include "os.h"
#define CONFIG_LINE_SIZE_INIT 50
#define INVALID_CHAR_POS UINT64_MAX
struct rpmemd_special_chars_pos {
uint64_t equal_char;
uint64_t comment_char;
uint64_t EOL_char;
};
enum rpmemd_option {
RPD_OPT_LOG_FILE,
RPD_OPT_POOLSET_DIR,
RPD_OPT_PERSIST_APM,
RPD_OPT_PERSIST_GENERAL,
RPD_OPT_USE_SYSLOG,
RPD_OPT_LOG_LEVEL,
RPD_OPT_RM_POOLSET,
RPD_OPT_MAX_VALUE,
RPD_OPT_INVALID = UINT64_MAX,
};
static const char *optstr = "c:hVr:fst:";
/*
* options -- cl and config file options
*/
static const struct option options[] = {
{"config", required_argument, NULL, 'c'},
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'V'},
{"log-file", required_argument, NULL, RPD_OPT_LOG_FILE},
{"poolset-dir", required_argument, NULL, RPD_OPT_POOLSET_DIR},
{"persist-apm", no_argument, NULL, RPD_OPT_PERSIST_APM},
{"persist-general", no_argument, NULL, RPD_OPT_PERSIST_GENERAL},
{"use-syslog", no_argument, NULL, RPD_OPT_USE_SYSLOG},
{"log-level", required_argument, NULL, RPD_OPT_LOG_LEVEL},
{"remove", required_argument, NULL, 'r'},
{"force", no_argument, NULL, 'f'},
{"pool-set", no_argument, NULL, 's'},
{"nthreads", required_argument, NULL, 't'},
{NULL, 0, NULL, 0},
};
#define VALUE_INDENT " "
static const char * const help_str =
"\n"
"Options:\n"
" -c, --config <path> configuration file location\n"
" -r, --remove <poolset> remove pool described by given poolset file\n"
" -f, --force ignore errors when removing a pool\n"
" -t, --nthreads <num> number of processing threads\n"
" -h, --help display help message and exit\n"
" -V, --version display target daemon version and exit\n"
" --log-file <path> log file location\n"
" --poolset-dir <path> pool set files directory\n"
" --persist-apm enable Appliance Persistency Method\n"
" --persist-general enable General Server Persistency Mechanism\n"
" --use-syslog use syslog(3) for logging messages\n"
" --log-level <level> set log level value\n"
VALUE_INDENT "err error conditions\n"
VALUE_INDENT "warn warning conditions\n"
VALUE_INDENT "notice normal, but significant, condition\n"
VALUE_INDENT "info informational message\n"
VALUE_INDENT "debug debug-level message\n"
"\n"
"For complete documentation see %s(1) manual page.";
/*
* print_version -- (internal) prints version message
*/
static void
print_version(void)
{
RPMEMD_LOG(ERR, "%s version %s", DAEMON_NAME, SRCVERSION);
}
/*
* print_usage -- (internal) prints usage message
*/
static void
print_usage(const char *name)
{
RPMEMD_LOG(ERR, "usage: %s [--version] [--help] [<args>]",
name);
}
/*
* print_help -- (internal) prints help message
*/
static void
print_help(const char *name)
{
print_usage(name);
print_version();
RPMEMD_LOG(ERR, help_str, DAEMON_NAME);
}
/*
* parse_config_string -- (internal) parse string value
*/
static inline char *
parse_config_string(const char *value)
{
if (strlen(value) == 0) {
errno = EINVAL;
return NULL;
}
char *output = strdup(value);
if (output == NULL)
RPMEMD_FATAL("!strdup");
return output;
}
/*
* parse_config_bool -- (internal) parse yes / no flag
*/
static inline int
parse_config_bool(bool *config_value, const char *value)
{
if (value == NULL)
*config_value = true;
else if (strcmp("yes", value) == 0)
*config_value = true;
else if (strcmp("no", value) == 0)
*config_value = false;
else {
errno = EINVAL;
return -1;
}
return 0;
}
/*
* set_option -- (internal) set single config option
*/
static int
set_option(enum rpmemd_option option, const char *value,
struct rpmemd_config *config)
{
int ret = 0;
switch (option) {
case RPD_OPT_LOG_FILE:
free(config->log_file);
config->log_file = parse_config_string(value);
if (config->log_file == NULL)
return -1;
else
config->use_syslog = false;
break;
case RPD_OPT_POOLSET_DIR:
free(config->poolset_dir);
config->poolset_dir = parse_config_string(value);
if (config->poolset_dir == NULL)
return -1;
break;
case RPD_OPT_PERSIST_APM:
ret = parse_config_bool(&config->persist_apm, value);
break;
case RPD_OPT_PERSIST_GENERAL:
ret = parse_config_bool(&config->persist_general, value);
break;
case RPD_OPT_USE_SYSLOG:
ret = parse_config_bool(&config->use_syslog, value);
break;
case RPD_OPT_LOG_LEVEL:
config->log_level = rpmemd_log_level_from_str(value);
if (config->log_level == MAX_RPD_LOG) {
errno = EINVAL;
return -1;
}
break;
default:
errno = EINVAL;
return -1;
}
return ret;
}
/*
* get_config_line -- (internal) read single line from file
*/
static int
get_config_line(FILE *file, char **line, uint64_t *line_max,
uint8_t *line_max_increased, struct rpmemd_special_chars_pos *pos)
{
uint8_t line_complete = 0;
uint64_t line_length = 0;
char *line_part = *line;
do {
char *ret = fgets(line_part,
(int)(*line_max - line_length), file);
if (ret == NULL)
return 0;
for (uint64_t i = 0; i < *line_max; ++i) {
if (line_part[i] == '\n')
line_complete = 1;
else if (line_part[i] == '\0') {
line_length += i;
if (line_length + 1 < *line_max)
line_complete = 1;
break;
} else if (line_part[i] == '#' &&
pos->comment_char == UINT64_MAX)
pos->comment_char = line_length + i;
else if (line_part[i] == '=' &&
pos->equal_char == UINT64_MAX)
pos->equal_char = line_length + i;
}
if (line_complete == 0) {
*line = realloc(*line, sizeof(char) * (*line_max) * 2);
if (*line == NULL) {
RPMEMD_FATAL("!realloc");
}
line_part = *line + *line_max - 1;
line_length = *line_max - 1;
*line_max *= 2;
*line_max_increased = 1;
}
} while (line_complete != 1);
pos->EOL_char = line_length;
return 0;
}
/*
* trim_line_element -- (internal) remove white characters
*/
static char *
trim_line_element(char *line, uint64_t start, uint64_t end)
{
for (; start <= end; ++start) {
if (!isspace(line[start]))
break;
}
for (; end > start; --end) {
if (!isspace(line[end - 1]))
break;
}
if (start == end)
return NULL;
line[end] = '\0';
return &line[start];
}
/*
* parse_config_key -- (internal) lookup config key
*/
static enum rpmemd_option
parse_config_key(const char *key)
{
for (int i = 0; options[i].name != 0; ++i) {
if (strcmp(key, options[i].name) == 0)
return (enum rpmemd_option)options[i].val;
}
return RPD_OPT_INVALID;
}
/*
* parse_config_line -- (internal) parse single config line
*
* Return newly written option flag. Store possible errors in errno.
*/
static int
parse_config_line(char *line, struct rpmemd_special_chars_pos *pos,
struct rpmemd_config *config, uint64_t disabled)
{
if (pos->comment_char < pos->equal_char)
pos->equal_char = INVALID_CHAR_POS;
uint64_t end_of_content = pos->comment_char != INVALID_CHAR_POS ?
pos->comment_char : pos->EOL_char;
if (pos->equal_char == INVALID_CHAR_POS) {
char *leftover = trim_line_element(line, 0, end_of_content);
if (leftover != NULL) {
errno = EINVAL;
return -1;
} else {
return 0;
}
}
char *key_name = trim_line_element(line, 0, pos->equal_char);
char *value = trim_line_element(line, pos->equal_char + 1,
end_of_content);
if (key_name == NULL || value == NULL) {
errno = EINVAL;
return -1;
}
enum rpmemd_option key = parse_config_key(key_name);
if (key != RPD_OPT_INVALID) {
if ((disabled & (uint64_t)(1 << key)) == 0)
if (set_option(key, value, config) != 0)
return -1;
} else {
errno = EINVAL;
return -1;
}
return 0;
}
/*
* parse_config_file -- (internal) parse config file
*/
static int
parse_config_file(const char *filename, struct rpmemd_config *config,
uint64_t disabled, int required)
{
RPMEMD_ASSERT(filename != NULL);
FILE *file = os_fopen(filename, "r");
if (file == NULL) {
if (required) {
RPMEMD_LOG(ERR, "!%s", filename);
goto error_fopen;
} else {
goto optional_config_missing;
}
}
uint8_t line_max_increased = 0;
uint64_t line_max = CONFIG_LINE_SIZE_INIT;
uint64_t line_num = 1;
char *line = (char *)malloc(sizeof(char) * line_max);
if (line == NULL) {
RPMEMD_LOG(ERR, "!malloc");
goto error_malloc_line;
}
char *line_copy = (char *)malloc(sizeof(char) * line_max);
if (line_copy == NULL) {
RPMEMD_LOG(ERR, "!malloc");
goto error_malloc_line_copy;
}
struct rpmemd_special_chars_pos pos;
do {
memset(&pos, 0xff, sizeof(pos));
if (get_config_line(file, &line, &line_max,
&line_max_increased, &pos) != 0)
goto error;
if (line_max_increased) {
char *line_new = (char *)realloc(line_copy,
sizeof(char) * line_max);
if (line_new == NULL) {
RPMEMD_LOG(ERR, "!malloc");
goto error;
}
line_copy = line_new;
line_max_increased = 0;
}
if (pos.EOL_char != INVALID_CHAR_POS) {
strcpy(line_copy, line);
int ret = parse_config_line(line_copy, &pos, config,
disabled);
if (ret != 0) {
size_t len = strlen(line);
if (len > 0 && line[len - 1] == '\n')
line[len - 1] = '\0';
RPMEMD_LOG(ERR, "Invalid config file line at "
"%s:%lu\n%s",
filename, line_num, line);
goto error;
}
}
++line_num;
} while (pos.EOL_char != INVALID_CHAR_POS);
free(line_copy);
free(line);
fclose(file);
optional_config_missing:
return 0;
error:
free(line_copy);
error_malloc_line_copy:
free(line);
error_malloc_line:
fclose(file);
error_fopen:
return -1;
}
/*
* parse_cl_args -- (internal) parse command line arguments
*/
static void
parse_cl_args(int argc, char *argv[], struct rpmemd_config *config,
const char **config_file, uint64_t *cl_options)
{
RPMEMD_ASSERT(argv != NULL);
RPMEMD_ASSERT(config != NULL);
int opt;
int option_index = 0;
while ((opt = getopt_long(argc, argv, optstr, options,
&option_index)) != -1) {
switch (opt) {
case 'c':
(*config_file) = optarg;
break;
case 'r':
config->rm_poolset = optarg;
break;
case 'f':
config->force = true;
break;
case 's':
config->pool_set = true;
break;
case 't':
errno = 0;
char *endptr;
config->nthreads = strtoul(optarg, &endptr, 10);
if (errno || *endptr != '\0') {
RPMEMD_LOG(ERR,
"invalid number of threads -- '%s'",
optarg);
exit(-1);
}
break;
case 'h':
print_help(argv[0]);
exit(0);
case 'V':
print_version();
exit(0);
break;
default:
if (set_option((enum rpmemd_option)opt, optarg, config)
== 0) {
*cl_options |= (UINT64_C(1) << opt);
} else {
print_usage(argv[0]);
exit(-1);
}
}
}
}
/*
* get_home_dir -- (internal) return user home directory
*
* Function will lookup user home directory in order:
* 1. HOME environment variable
* 2. Password file entry using real user ID
*/
static void
get_home_dir(char *str, size_t size)
{
char *home = os_getenv(HOME_ENV);
if (home) {
int r = util_snprintf(str, size, "%s", home);
if (r < 0)
RPMEMD_FATAL("!snprintf");
} else {
uid_t uid = getuid();
struct passwd *pw = getpwuid(uid);
if (pw == NULL)
RPMEMD_FATAL("!getpwuid");
int r = util_snprintf(str, size, "%s", pw->pw_dir);
if (r < 0)
RPMEMD_FATAL("!snprintf");
}
}
/*
* concat_dir_and_file_name -- (internal) concatenate directory and file name
* into single string path
*/
static void
concat_dir_and_file_name(char *path, size_t size, const char *dir,
const char *file)
{
int r = util_snprintf(path, size, "%s/%s", dir, file);
if (r < 0)
RPMEMD_FATAL("!snprintf");
}
/*
* str_replace_home -- (internal) replace $HOME string with user home directory
*
* If function does not find $HOME string it will return haystack untouched.
* Otherwise it will allocate new string with $HOME replaced with provided
* home_dir path. haystack will be released and newly created string returned.
*/
static char *
str_replace_home(char *haystack, const char *home_dir)
{
const size_t placeholder_len = strlen(HOME_STR_PLACEHOLDER);
const size_t home_len = strlen(home_dir);
size_t haystack_len = strlen(haystack);
char *pos = strstr(haystack, HOME_STR_PLACEHOLDER);
if (!pos)
return haystack;
const char *after = pos + placeholder_len;
if (isalnum(*after))
return haystack;
haystack_len += home_len - placeholder_len + 1;
char *buf = malloc(sizeof(char) * haystack_len);
if (!buf)
RPMEMD_FATAL("!malloc");
*pos = '\0';
int r = util_snprintf(buf, haystack_len, "%s%s%s", haystack, home_dir,
after);
if (r < 0)
RPMEMD_FATAL("!snprintf");
free(haystack);
return buf;
}
/*
* config_set_default -- (internal) load default config
*/
static void
config_set_default(struct rpmemd_config *config, const char *poolset_dir)
{
config->log_file = strdup(RPMEMD_DEFAULT_LOG_FILE);
if (!config->log_file)
RPMEMD_FATAL("!strdup");
config->poolset_dir = strdup(poolset_dir);
if (!config->poolset_dir)
RPMEMD_FATAL("!strdup");
config->persist_apm = false;
config->persist_general = true;
config->use_syslog = true;
config->max_lanes = RPMEM_DEFAULT_MAX_LANES;
config->log_level = RPD_LOG_ERR;
config->rm_poolset = NULL;
config->force = false;
config->nthreads = RPMEM_DEFAULT_NTHREADS;
}
/*
* rpmemd_config_read -- read config from cl and config files
*
* cl param overwrites configuration from any config file. Config file are read
* in order:
* 1. Global config file
* 2. User config file
* or
* cl provided config file
*/
int
rpmemd_config_read(struct rpmemd_config *config, int argc, char *argv[])
{
const char *cl_config_file = NULL;
char user_config_file[PATH_MAX];
char home_dir[PATH_MAX];
uint64_t cl_options = 0;
get_home_dir(home_dir, PATH_MAX);
config_set_default(config, home_dir);
parse_cl_args(argc, argv, config, &cl_config_file, &cl_options);
if (cl_config_file) {
if (parse_config_file(cl_config_file, config, cl_options, 1)) {
rpmemd_config_free(config);
return 1;
}
} else {
if (parse_config_file(RPMEMD_GLOBAL_CONFIG_FILE, config,
cl_options, 0)) {
rpmemd_config_free(config);
return 1;
}
concat_dir_and_file_name(user_config_file, PATH_MAX, home_dir,
RPMEMD_USER_CONFIG_FILE);
if (parse_config_file(user_config_file, config, cl_options,
0)) {
rpmemd_config_free(config);
return 1;
}
}
config->poolset_dir = str_replace_home(config->poolset_dir, home_dir);
return 0;
}
/*
* rpmemd_config_free -- rpmemd config release
*/
void
rpmemd_config_free(struct rpmemd_config *config)
{
free(config->log_file);
free(config->poolset_dir);
}
| 15,007 | 22.413417 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_util.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2018, Intel Corporation */
/*
* rpmemd_util.h -- rpmemd utility functions declarations
*/
int rpmemd_pmem_persist(const void *addr, size_t len);
int rpmemd_flush_fatal(const void *addr, size_t len);
int rpmemd_apply_pm_policy(enum rpmem_persist_method *persist_method,
int (**persist)(const void *addr, size_t len),
void *(**memcpy_persist)(void *pmemdest, const void *src, size_t len),
const int is_pmem);
| 473 | 32.857143 | 71 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_db.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* rpmemd_db.c -- rpmemd database of pool set files
*/
#include <stdio.h>
#include <stdint.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/file.h>
#include <sys/mman.h>
#include "queue.h"
#include "set.h"
#include "os.h"
#include "out.h"
#include "file.h"
#include "sys_util.h"
#include "librpmem.h"
#include "rpmemd_db.h"
#include "rpmemd_log.h"
/*
* struct rpmemd_db -- pool set database structure
*/
struct rpmemd_db {
os_mutex_t lock;
char *root_dir;
mode_t mode;
};
/*
* declaration of the 'struct list_head' type
*/
PMDK_LIST_HEAD(list_head, rpmemd_db_entry);
/*
* struct rpmemd_db_entry -- entry in the pool set list
*/
struct rpmemd_db_entry {
PMDK_LIST_ENTRY(rpmemd_db_entry) next;
char *pool_desc;
struct pool_set *set;
};
/*
* rpmemd_db_init -- initialize the rpmem database of pool set files
*/
struct rpmemd_db *
rpmemd_db_init(const char *root_dir, mode_t mode)
{
if (root_dir[0] != '/') {
RPMEMD_LOG(ERR, "root directory is not an absolute path"
" -- '%s'", root_dir);
errno = EINVAL;
return NULL;
}
struct rpmemd_db *db = calloc(1, sizeof(*db));
if (!db) {
RPMEMD_LOG(ERR, "!allocating the rpmem database structure");
return NULL;
}
db->root_dir = strdup(root_dir);
if (!db->root_dir) {
RPMEMD_LOG(ERR, "!allocating the root dir path");
free(db);
return NULL;
}
db->mode = mode;
util_mutex_init(&db->lock);
return db;
}
/*
* rpmemd_db_concat -- (internal) concatenate two paths
*/
static char *
rpmemd_db_concat(const char *path1, const char *path2)
{
size_t len1 = strlen(path1);
size_t len2 = strlen(path2);
size_t new_len = len1 + len2 + 2; /* +1 for '/' in snprintf() */
if (path1[0] != '/') {
RPMEMD_LOG(ERR, "the first path is not an absolute one -- '%s'",
path1);
errno = EINVAL;
return NULL;
}
if (path2[0] == '/') {
RPMEMD_LOG(ERR, "the second path is not a relative one -- '%s'",
path2);
/* set to EBADF to distinguish this case from other errors */
errno = EBADF;
return NULL;
}
char *new_str = malloc(new_len);
if (new_str == NULL) {
RPMEMD_LOG(ERR, "!allocating path buffer");
return NULL;
}
int ret = util_snprintf(new_str, new_len, "%s/%s", path1, path2);
if (ret < 0) {
RPMEMD_LOG(ERR, "!snprintf");
free(new_str);
errno = EINVAL;
return NULL;
}
return new_str;
}
/*
* rpmemd_db_get_path -- (internal) get the full path of the pool set file
*/
static char *
rpmemd_db_get_path(struct rpmemd_db *db, const char *pool_desc)
{
return rpmemd_db_concat(db->root_dir, pool_desc);
}
/*
* rpmemd_db_pool_madvise -- (internal) workaround device dax alignment issue
*/
static int
rpmemd_db_pool_madvise(struct pool_set *set)
{
/*
* This is a workaround for an issue with using device dax with
* libibverbs. The problem is that we use ibv_fork_init(3) which
* makes all registered memory being madvised with MADV_DONTFORK
* flag. In libpmemobj the remote replication is performed without
* pool header (first 4k). In such case the address passed to
* madvise(2) is aligned to 4k, but device dax can require different
* alignment (default is 2MB). This workaround madvises the entire
* memory region before registering it by ibv_reg_mr(3).
*/
const struct pool_set_part *part = &set->replica[0]->part[0];
if (part->is_dev_dax) {
int ret = os_madvise(part->addr, part->filesize,
MADV_DONTFORK);
if (ret) {
ERR("!madvise");
return -1;
}
}
return 0;
}
/*
* rpmemd_get_attr -- (internal) get pool attributes from remote pool attributes
*/
static void
rpmemd_get_attr(struct pool_attr *attr, const struct rpmem_pool_attr *rattr)
{
LOG(3, "attr %p, rattr %p", attr, rattr);
memcpy(attr->signature, rattr->signature, POOL_HDR_SIG_LEN);
attr->major = rattr->major;
attr->features.compat = rattr->compat_features;
attr->features.incompat = rattr->incompat_features;
attr->features.ro_compat = rattr->ro_compat_features;
memcpy(attr->poolset_uuid, rattr->poolset_uuid, POOL_HDR_UUID_LEN);
memcpy(attr->first_part_uuid, rattr->uuid, POOL_HDR_UUID_LEN);
memcpy(attr->prev_repl_uuid, rattr->prev_uuid, POOL_HDR_UUID_LEN);
memcpy(attr->next_repl_uuid, rattr->next_uuid, POOL_HDR_UUID_LEN);
memcpy(attr->arch_flags, rattr->user_flags, POOL_HDR_ARCH_LEN);
}
/*
* rpmemd_db_pool_create -- create a new pool set
*/
struct rpmemd_db_pool *
rpmemd_db_pool_create(struct rpmemd_db *db, const char *pool_desc,
size_t pool_size, const struct rpmem_pool_attr *rattr)
{
RPMEMD_ASSERT(db != NULL);
util_mutex_lock(&db->lock);
struct rpmemd_db_pool *prp = NULL;
struct pool_set *set;
char *path;
int ret;
prp = malloc(sizeof(struct rpmemd_db_pool));
if (!prp) {
RPMEMD_LOG(ERR, "!allocating pool set db entry");
goto err_unlock;
}
path = rpmemd_db_get_path(db, pool_desc);
if (!path) {
goto err_free_prp;
}
struct pool_attr attr;
struct pool_attr *pattr = NULL;
if (rattr != NULL) {
rpmemd_get_attr(&attr, rattr);
pattr = &attr;
}
ret = util_pool_create_uuids(&set, path, 0, RPMEM_MIN_POOL,
RPMEM_MIN_PART, pattr, NULL, REPLICAS_DISABLED,
POOL_REMOTE);
if (ret) {
RPMEMD_LOG(ERR, "!cannot create pool set -- '%s'", path);
goto err_free_path;
}
ret = util_poolset_chmod(set, db->mode);
if (ret) {
RPMEMD_LOG(ERR, "!cannot change pool set mode bits to 0%o",
db->mode);
}
if (rpmemd_db_pool_madvise(set))
goto err_poolset_close;
/* mark as opened */
prp->pool_addr = set->replica[0]->part[0].addr;
prp->pool_size = set->poolsize;
prp->set = set;
free(path);
util_mutex_unlock(&db->lock);
return prp;
err_poolset_close:
util_poolset_close(set, DO_NOT_DELETE_PARTS);
err_free_path:
free(path);
err_free_prp:
free(prp);
err_unlock:
util_mutex_unlock(&db->lock);
return NULL;
}
/*
* rpmemd_db_pool_open -- open a pool set
*/
struct rpmemd_db_pool *
rpmemd_db_pool_open(struct rpmemd_db *db, const char *pool_desc,
size_t pool_size, struct rpmem_pool_attr *rattr)
{
RPMEMD_ASSERT(db != NULL);
RPMEMD_ASSERT(rattr != NULL);
util_mutex_lock(&db->lock);
struct rpmemd_db_pool *prp = NULL;
struct pool_set *set;
char *path;
int ret;
prp = malloc(sizeof(struct rpmemd_db_pool));
if (!prp) {
RPMEMD_LOG(ERR, "!allocating pool set db entry");
goto err_unlock;
}
path = rpmemd_db_get_path(db, pool_desc);
if (!path) {
goto err_free_prp;
}
ret = util_pool_open_remote(&set, path, 0, RPMEM_MIN_PART, rattr);
if (ret) {
RPMEMD_LOG(ERR, "!cannot open pool set -- '%s'", path);
goto err_free_path;
}
if (rpmemd_db_pool_madvise(set))
goto err_poolset_close;
/* mark as opened */
prp->pool_addr = set->replica[0]->part[0].addr;
prp->pool_size = set->poolsize;
prp->set = set;
free(path);
util_mutex_unlock(&db->lock);
return prp;
err_poolset_close:
util_poolset_close(set, DO_NOT_DELETE_PARTS);
err_free_path:
free(path);
err_free_prp:
free(prp);
err_unlock:
util_mutex_unlock(&db->lock);
return NULL;
}
/*
* rpmemd_db_pool_close -- close a pool set
*/
void
rpmemd_db_pool_close(struct rpmemd_db *db, struct rpmemd_db_pool *prp)
{
RPMEMD_ASSERT(db != NULL);
util_mutex_lock(&db->lock);
util_poolset_close(prp->set, DO_NOT_DELETE_PARTS);
free(prp);
util_mutex_unlock(&db->lock);
}
/*
* rpmemd_db_pool_set_attr -- overwrite pool attributes
*/
int
rpmemd_db_pool_set_attr(struct rpmemd_db_pool *prp,
const struct rpmem_pool_attr *rattr)
{
RPMEMD_ASSERT(prp != NULL);
RPMEMD_ASSERT(prp->set != NULL);
RPMEMD_ASSERT(prp->set->nreplicas == 1);
return util_replica_set_attr(prp->set->replica[0], rattr);
}
struct rm_cb_args {
int force;
int ret;
};
/*
* rm_poolset_cb -- (internal) callback for removing part files
*/
static int
rm_poolset_cb(struct part_file *pf, void *arg)
{
struct rm_cb_args *args = (struct rm_cb_args *)arg;
if (pf->is_remote) {
RPMEMD_LOG(ERR, "removing remote replica not supported");
return -1;
}
int ret = util_unlink_flock(pf->part->path);
if (!args->force && ret) {
RPMEMD_LOG(ERR, "!unlink -- '%s'", pf->part->path);
args->ret = ret;
}
return 0;
}
/*
* rpmemd_db_pool_remove -- remove a pool set
*/
int
rpmemd_db_pool_remove(struct rpmemd_db *db, const char *pool_desc,
int force, int pool_set)
{
RPMEMD_ASSERT(db != NULL);
RPMEMD_ASSERT(pool_desc != NULL);
util_mutex_lock(&db->lock);
struct rm_cb_args args;
args.force = force;
args.ret = 0;
char *path;
path = rpmemd_db_get_path(db, pool_desc);
if (!path) {
args.ret = -1;
goto err_unlock;
}
int ret = util_poolset_foreach_part(path, rm_poolset_cb, &args);
if (!force && ret) {
RPMEMD_LOG(ERR, "!removing '%s' failed", path);
args.ret = ret;
goto err_free_path;
}
if (pool_set)
os_unlink(path);
err_free_path:
free(path);
err_unlock:
util_mutex_unlock(&db->lock);
return args.ret;
}
/*
* rpmemd_db_fini -- deinitialize the rpmem database of pool set files
*/
void
rpmemd_db_fini(struct rpmemd_db *db)
{
RPMEMD_ASSERT(db != NULL);
util_mutex_destroy(&db->lock);
free(db->root_dir);
free(db);
}
/*
* rpmemd_db_check_dups_set -- (internal) check for duplicates in the database
*/
static inline int
rpmemd_db_check_dups_set(struct pool_set *set, const char *path)
{
for (unsigned r = 0; r < set->nreplicas; r++) {
struct pool_replica *rep = set->replica[r];
for (unsigned p = 0; p < rep->nparts; p++) {
if (strcmp(path, rep->part[p].path) == 0)
return -1;
}
}
return 0;
}
/*
* rpmemd_db_check_dups -- (internal) check for duplicates in the database
*/
static int
rpmemd_db_check_dups(struct list_head *head, struct rpmemd_db *db,
const char *pool_desc, struct pool_set *set)
{
struct rpmemd_db_entry *edb;
PMDK_LIST_FOREACH(edb, head, next) {
for (unsigned r = 0; r < edb->set->nreplicas; r++) {
struct pool_replica *rep = edb->set->replica[r];
for (unsigned p = 0; p < rep->nparts; p++) {
if (rpmemd_db_check_dups_set(set,
rep->part[p].path)) {
RPMEMD_LOG(ERR, "part file '%s' from "
"pool set '%s' duplicated in "
"pool set '%s'",
rep->part[p].path,
pool_desc,
edb->pool_desc);
errno = EEXIST;
return -1;
}
}
}
}
return 0;
}
/*
* rpmemd_db_add -- (internal) add an entry for a given set to the database
*/
static struct rpmemd_db_entry *
rpmemd_db_add(struct list_head *head, struct rpmemd_db *db,
const char *pool_desc, struct pool_set *set)
{
struct rpmemd_db_entry *edb;
edb = calloc(1, sizeof(*edb));
if (!edb) {
RPMEMD_LOG(ERR, "!allocating database entry");
goto err_calloc;
}
edb->set = set;
edb->pool_desc = strdup(pool_desc);
if (!edb->pool_desc) {
RPMEMD_LOG(ERR, "!allocating path for database entry");
goto err_strdup;
}
PMDK_LIST_INSERT_HEAD(head, edb, next);
return edb;
err_strdup:
free(edb);
err_calloc:
return NULL;
}
/*
* new_paths -- (internal) create two new paths
*/
static int
new_paths(const char *dir, const char *name, const char *old_desc,
char **path, char **new_desc)
{
*path = rpmemd_db_concat(dir, name);
if (!(*path))
return -1;
if (old_desc[0] != 0)
*new_desc = rpmemd_db_concat(old_desc, name);
else {
*new_desc = strdup(name);
if (!(*new_desc)) {
RPMEMD_LOG(ERR, "!allocating new descriptor");
}
}
if (!(*new_desc)) {
free(*path);
return -1;
}
return 0;
}
/*
* rpmemd_db_check_dir_r -- (internal) recursively check given directory
* for duplicates
*/
static int
rpmemd_db_check_dir_r(struct list_head *head, struct rpmemd_db *db,
const char *dir, char *pool_desc)
{
char *new_dir, *new_desc, *full_path;
struct dirent *dentry;
struct pool_set *set = NULL;
DIR *dirp;
int ret = 0;
dirp = opendir(dir);
if (dirp == NULL) {
RPMEMD_LOG(ERR, "cannot open the directory -- %s", dir);
return -1;
}
while ((dentry = readdir(dirp)) != NULL) {
if (strcmp(dentry->d_name, ".") == 0 ||
strcmp(dentry->d_name, "..") == 0)
continue;
if (dentry->d_type == DT_DIR) { /* directory */
if (new_paths(dir, dentry->d_name, pool_desc,
&new_dir, &new_desc))
goto err_closedir;
/* call recursively for a new directory */
ret = rpmemd_db_check_dir_r(head, db, new_dir,
new_desc);
free(new_dir);
free(new_desc);
if (ret)
goto err_closedir;
continue;
}
if (new_paths(dir, dentry->d_name, pool_desc,
&full_path, &new_desc)) {
goto err_closedir;
}
if (util_poolset_read(&set, full_path)) {
RPMEMD_LOG(ERR, "!error reading pool set file -- %s",
full_path);
goto err_free_paths;
}
if (rpmemd_db_check_dups(head, db, new_desc, set)) {
RPMEMD_LOG(ERR, "!duplicate found in pool set file"
" -- %s", full_path);
goto err_free_set;
}
if (rpmemd_db_add(head, db, new_desc, set) == NULL) {
goto err_free_set;
}
free(new_desc);
free(full_path);
}
closedir(dirp);
return 0;
err_free_set:
util_poolset_close(set, DO_NOT_DELETE_PARTS);
err_free_paths:
free(new_desc);
free(full_path);
err_closedir:
closedir(dirp);
return -1;
}
/*
* rpmemd_db_check_dir -- check given directory for duplicates
*/
int
rpmemd_db_check_dir(struct rpmemd_db *db)
{
RPMEMD_ASSERT(db != NULL);
util_mutex_lock(&db->lock);
struct list_head head;
PMDK_LIST_INIT(&head);
int ret = rpmemd_db_check_dir_r(&head, db, db->root_dir, "");
while (!PMDK_LIST_EMPTY(&head)) {
struct rpmemd_db_entry *edb = PMDK_LIST_FIRST(&head);
PMDK_LIST_REMOVE(edb, next);
util_poolset_close(edb->set, DO_NOT_DELETE_PARTS);
free(edb->pool_desc);
free(edb);
}
util_mutex_unlock(&db->lock);
return ret;
}
/*
* rpmemd_db_pool_is_pmem -- true if pool is in PMEM
*/
int
rpmemd_db_pool_is_pmem(struct rpmemd_db_pool *pool)
{
return REP(pool->set, 0)->is_pmem;
}
| 13,747 | 20.616352 | 80 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_fip.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* rpmemd_fip.h -- rpmemd libfabric provider module header file
*/
#include <stddef.h>
struct rpmemd_fip;
struct rpmemd_fip_attr {
void *addr;
size_t size;
unsigned nlanes;
size_t nthreads;
size_t buff_size;
enum rpmem_provider provider;
enum rpmem_persist_method persist_method;
int (*persist)(const void *addr, size_t len);
void *(*memcpy_persist)(void *pmemdest, const void *src, size_t len);
int (*deep_persist)(const void *addr, size_t len, void *ctx);
void *ctx;
};
struct rpmemd_fip *rpmemd_fip_init(const char *node,
const char *service,
struct rpmemd_fip_attr *attr,
struct rpmem_resp_attr *resp,
enum rpmem_err *err);
void rpmemd_fip_fini(struct rpmemd_fip *fip);
int rpmemd_fip_accept(struct rpmemd_fip *fip, int timeout);
int rpmemd_fip_process_start(struct rpmemd_fip *fip);
int rpmemd_fip_process_stop(struct rpmemd_fip *fip);
int rpmemd_fip_wait_close(struct rpmemd_fip *fip, int timeout);
int rpmemd_fip_close(struct rpmemd_fip *fip);
| 1,066 | 27.078947 | 70 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_fip.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* rpmemd_fip.c -- rpmemd libfabric provider module source file
*/
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <rdma/fabric.h>
#include <rdma/fi_domain.h>
#include <rdma/fi_endpoint.h>
#include <rdma/fi_cm.h>
#include <rdma/fi_errno.h>
#include "rpmemd_log.h"
#include "rpmem_common.h"
#include "rpmem_proto.h"
#include "rpmem_fip_msg.h"
#include "rpmem_fip_common.h"
#include "rpmemd_fip.h"
#include "os_thread.h"
#include "util.h"
#include "valgrind_internal.h"
#define RPMEMD_FI_ERR(e, fmt, args...)\
RPMEMD_LOG(ERR, fmt ": %s", ## args, fi_strerror((e)))
#define RPMEMD_FI_CLOSE(f, fmt, args...) (\
{\
int ret = fi_close(&(f)->fid);\
if (ret)\
RPMEMD_FI_ERR(ret, fmt, ## args);\
ret;\
})
/*
* rpmem_fip_lane -- base lane structure
*/
struct rpmem_fip_lane {
struct fid_ep *ep;
struct fid_cq *cq;
};
/*
* rpmemd_fip_lane -- daemon's lane
*/
struct rpmemd_fip_lane {
struct rpmem_fip_lane base; /* lane base structure */
struct rpmem_fip_msg recv; /* RECV message */
struct rpmem_fip_msg send; /* SEND message */
struct rpmem_msg_persist_resp resp; /* persist response msg buffer */
int send_posted; /* send buffer has been posted */
int recv_posted; /* recv buffer has been posted */
};
/*
* rpmemd_fip_thread -- thread context
*/
struct rpmemd_fip_thread {
struct rpmemd_fip *fip; /* main context */
os_thread_t thread; /* thread structure */
struct fid_cq *cq; /* per-thread completion queue */
struct rpmemd_fip_lane **lanes; /* lanes processed by this thread */
size_t nlanes; /* number of lanes processed by this thread */
};
/*
* rpmemd_fip -- main context of rpmemd_fip
*/
struct rpmemd_fip {
struct fi_info *fi; /* fabric interface information */
struct fid_fabric *fabric; /* fabric domain */
struct fid_domain *domain; /* fabric protection domain */
struct fid_eq *eq; /* event queue */
struct fid_pep *pep; /* passive endpoint - listener */
struct fid_mr *mr; /* memory region for pool */
int (*persist)(const void *addr, size_t len); /* persist function */
void *(*memcpy_persist)(void *pmemdest, const void *src, size_t len);
int (*deep_persist)(const void *addr, size_t len, void *ctx);
void *ctx;
void *addr; /* pool's address */
size_t size; /* size of the pool */
enum rpmem_persist_method persist_method;
volatile int closing; /* flag for closing background threads */
unsigned nlanes; /* number of lanes */
size_t nthreads; /* number of threads for processing */
size_t cq_size; /* size of completion queue */
size_t lanes_per_thread; /* number of lanes per thread */
size_t buff_size; /* size of buffer for inlined data */
struct rpmemd_fip_lane *lanes;
struct rpmem_fip_lane rd_lane; /* lane for read operation */
void *pmsg; /* persist message buffer */
size_t pmsg_size; /* persist message buffer size including alignment */
struct fid_mr *pmsg_mr; /* persist message memory region */
void *pmsg_mr_desc; /* persist message local descriptor */
struct rpmem_msg_persist_resp *pres; /* persist response buffer */
struct fid_mr *pres_mr; /* persist response memory region */
void *pres_mr_desc; /* persist response local descriptor */
struct rpmemd_fip_thread *threads;
};
/*
* rpmemd_fip_get_pmsg -- return persist message buffer
*/
static inline struct rpmem_msg_persist *
rpmemd_fip_get_pmsg(struct rpmemd_fip *fip, size_t idx)
{
return (struct rpmem_msg_persist *)
((uintptr_t)fip->pmsg + idx * fip->pmsg_size);
}
/*
* rpmemd_fip_getinfo -- obtain fabric interface information
*/
static int
rpmemd_fip_getinfo(struct rpmemd_fip *fip, const char *service,
const char *node, enum rpmem_provider provider)
{
int ret;
struct fi_info *hints = rpmem_fip_get_hints(provider);
if (!hints) {
RPMEMD_LOG(ERR, "getting fabric interface hints");
ret = -1;
goto err_fi_get_hints;
}
ret = fi_getinfo(RPMEM_FIVERSION, node, service, FI_SOURCE,
hints, &fip->fi);
if (ret) {
RPMEMD_FI_ERR(ret, "getting fabric interface information");
goto err_fi_getinfo;
}
rpmem_fip_print_info(fip->fi);
fi_freeinfo(hints);
return 0;
err_fi_getinfo:
fi_freeinfo(hints);
err_fi_get_hints:
return ret;
}
/*
* rpmemd_fip_set_resp -- fill the response structure
*/
static int
rpmemd_fip_set_resp(struct rpmemd_fip *fip, struct rpmem_resp_attr *resp)
{
int ret;
if (fip->fi->addr_format == FI_SOCKADDR_IN) {
struct sockaddr_in addr_in;
size_t addrlen = sizeof(addr_in);
ret = fi_getname(&fip->pep->fid, &addr_in, &addrlen);
if (ret) {
RPMEMD_FI_ERR(ret, "getting local endpoint address");
goto err_fi_getname;
}
if (!addr_in.sin_port) {
RPMEMD_LOG(ERR, "dynamic allocation of port failed");
goto err_port;
}
resp->port = htons(addr_in.sin_port);
} else if (fip->fi->addr_format == FI_SOCKADDR_IN6) {
struct sockaddr_in6 addr_in6;
size_t addrlen = sizeof(addr_in6);
ret = fi_getname(&fip->pep->fid, &addr_in6, &addrlen);
if (ret) {
RPMEMD_FI_ERR(ret, "getting local endpoint address");
goto err_fi_getname;
}
if (!addr_in6.sin6_port) {
RPMEMD_LOG(ERR, "dynamic allocation of port failed");
goto err_port;
}
resp->port = htons(addr_in6.sin6_port);
} else {
RPMEMD_LOG(ERR, "invalid address format");
return -1;
}
resp->rkey = fi_mr_key(fip->mr);
resp->persist_method = fip->persist_method;
resp->raddr = (uint64_t)fip->addr;
resp->nlanes = fip->nlanes;
return 0;
err_port:
err_fi_getname:
return -1;
}
/*
* rpmemd_fip_init_fabric_res -- initialize common fabric's resources
*/
static int
rpmemd_fip_init_fabric_res(struct rpmemd_fip *fip)
{
int ret;
ret = fi_fabric(fip->fi->fabric_attr, &fip->fabric, NULL);
if (ret) {
RPMEMD_FI_ERR(ret, "opening fabric domain");
goto err_fi_fabric;
}
ret = fi_domain(fip->fabric, fip->fi, &fip->domain, NULL);
if (ret) {
RPMEMD_FI_ERR(ret, "opening fabric access domain");
goto err_fi_domain;
}
struct fi_eq_attr eq_attr = {
.size = 0, /* use default */
.flags = 0,
.wait_obj = FI_WAIT_UNSPEC,
.signaling_vector = 0,
.wait_set = NULL,
};
ret = fi_eq_open(fip->fabric, &eq_attr, &fip->eq, NULL);
if (ret) {
RPMEMD_FI_ERR(ret, "opening event queue");
goto err_eq_open;
}
ret = fi_passive_ep(fip->fabric, fip->fi, &fip->pep, NULL);
if (ret) {
RPMEMD_FI_ERR(ret, "allocating passive endpoint");
goto err_pep;
}
ret = fi_pep_bind(fip->pep, &fip->eq->fid, 0);
if (ret) {
RPMEMD_FI_ERR(ret, "binding event queue to passive endpoint");
goto err_pep_bind_eq;
}
return 0;
err_pep_bind_eq:
RPMEMD_FI_CLOSE(fip->pep, "closing passive endpoint");
err_pep:
RPMEMD_FI_CLOSE(fip->eq, "closing event queue");
err_eq_open:
RPMEMD_FI_CLOSE(fip->domain, "closing fabric access domain");
err_fi_domain:
RPMEMD_FI_CLOSE(fip->fabric, "closing fabric domain");
err_fi_fabric:
return ret;
}
/*
* rpmemd_fip_fini_fabric_res -- deinitialize common fabric resources
*/
static void
rpmemd_fip_fini_fabric_res(struct rpmemd_fip *fip)
{
RPMEMD_FI_CLOSE(fip->pep, "closing passive endpoint");
RPMEMD_FI_CLOSE(fip->eq, "closing event queue");
RPMEMD_FI_CLOSE(fip->domain, "closing fabric access domain");
RPMEMD_FI_CLOSE(fip->fabric, "closing fabric domain");
}
/*
* rpmemd_fip_init_memory -- initialize memory pool's resources
*/
static int
rpmemd_fip_init_memory(struct rpmemd_fip *fip)
{
int ret;
/*
* Register memory region with appropriate access bits:
* - FI_REMOTE_READ - remote peer can issue READ operation,
* - FI_REMOTE_WRITE - remote peer can issue WRITE operation,
*/
ret = fi_mr_reg(fip->domain, fip->addr, fip->size,
FI_REMOTE_READ | FI_REMOTE_WRITE, 0, 0, 0,
&fip->mr, NULL);
if (ret) {
RPMEMD_FI_ERR(ret, "registering memory");
return -1;
}
return 0;
}
/*
* rpmemd_fip_fini_memory -- deinitialize memory pool's resources
*/
static void
rpmemd_fip_fini_memory(struct rpmemd_fip *fip)
{
RPMEMD_FI_CLOSE(fip->mr, "unregistering memory");
}
/*
* rpmemd_fip_init_ep -- initialize active endpoint
*/
static int
rpmemd_fip_init_ep(struct rpmemd_fip *fip, struct fi_info *info,
struct rpmem_fip_lane *lanep)
{
int ret;
info->tx_attr->size = rpmem_fip_wq_size(fip->persist_method,
RPMEM_FIP_NODE_SERVER);
info->rx_attr->size = rpmem_fip_rx_size(fip->persist_method,
RPMEM_FIP_NODE_SERVER);
/* create an endpoint from fabric interface info */
ret = fi_endpoint(fip->domain, info, &lanep->ep, NULL);
if (ret) {
RPMEMD_FI_ERR(ret, "allocating endpoint");
goto err_endpoint;
}
/* bind event queue to the endpoint */
ret = fi_ep_bind(lanep->ep, &fip->eq->fid, 0);
if (ret) {
RPMEMD_FI_ERR(ret, "binding event queue to endpoint");
goto err_bind_eq;
}
/*
* Bind completion queue to the endpoint.
* Use a single completion queue for outbound and inbound work
* requests. Use selective completion implies adding FI_COMPLETE
* flag to each WR which needs a completion.
*/
ret = fi_ep_bind(lanep->ep, &lanep->cq->fid,
FI_RECV | FI_TRANSMIT | FI_SELECTIVE_COMPLETION);
if (ret) {
RPMEMD_FI_ERR(ret, "binding completion queue to endpoint");
goto err_bind_cq;
}
/* enable the endpoint */
ret = fi_enable(lanep->ep);
if (ret) {
RPMEMD_FI_ERR(ret, "enabling endpoint");
goto err_enable;
}
return 0;
err_enable:
err_bind_cq:
err_bind_eq:
RPMEMD_FI_CLOSE(lanep->ep, "closing endpoint");
err_endpoint:
return -1;
}
/*
* rpmemd_fip_fini_ep -- close endpoint
*/
static int
rpmemd_fip_fini_ep(struct rpmem_fip_lane *lanep)
{
return RPMEMD_FI_CLOSE(lanep->ep, "closing endpoint");
}
/*
* rpmemd_fip_post_msg -- post RECV buffer
*/
static inline int
rpmemd_fip_post_msg(struct rpmemd_fip_lane *lanep)
{
int ret = rpmem_fip_recvmsg(lanep->base.ep, &lanep->recv);
if (ret) {
RPMEMD_FI_ERR(ret, "posting recv buffer");
return ret;
}
lanep->recv_posted = 1;
return 0;
}
/*
* rpmemd_fip_post_resp -- post SEND buffer
*/
static inline int
rpmemd_fip_post_resp(struct rpmemd_fip_lane *lanep)
{
int ret = rpmem_fip_sendmsg(lanep->base.ep, &lanep->send,
sizeof(struct rpmem_msg_persist_resp));
if (ret) {
RPMEMD_FI_ERR(ret, "posting send buffer");
return ret;
}
lanep->send_posted = 1;
return 0;
}
/*
* rpmemd_fip_post_common -- post all RECV messages
*/
static int
rpmemd_fip_post_common(struct rpmemd_fip *fip, struct rpmemd_fip_lane *lanep)
{
int ret = rpmem_fip_recvmsg(lanep->base.ep, &lanep->recv);
if (ret) {
RPMEMD_FI_ERR(ret, "posting recv buffer");
return ret;
}
lanep->recv_posted = 1;
return 0;
}
/*
* rpmemd_fip_lanes_init -- initialize all lanes
*/
static int
rpmemd_fip_lanes_init(struct rpmemd_fip *fip)
{
fip->lanes = calloc(fip->nlanes, sizeof(*fip->lanes));
if (!fip->lanes) {
RPMEMD_ERR("!allocating lanes");
goto err_alloc;
}
return 0;
err_alloc:
return -1;
}
/*
* rpmemd_fip_fini_lanes -- deinitialize all lanes
*/
static void
rpmemd_fip_fini_lanes(struct rpmemd_fip *fip)
{
free(fip->lanes);
}
/*
* rpmemd_fip_init_common -- initialize common resources
*/
static int
rpmemd_fip_init_common(struct rpmemd_fip *fip)
{
int ret;
/* allocate persist message buffer */
size_t msg_size = fip->nlanes * fip->pmsg_size;
fip->pmsg = malloc(msg_size);
if (!fip->pmsg) {
RPMEMD_LOG(ERR, "!allocating messages buffer");
goto err_msg_malloc;
}
/* register persist message buffer */
ret = fi_mr_reg(fip->domain, fip->pmsg, msg_size, FI_RECV,
0, 0, 0, &fip->pmsg_mr, NULL);
if (ret) {
RPMEMD_FI_ERR(ret, "registering messages buffer");
goto err_mr_reg_msg;
}
/* get persist message buffer's local descriptor */
fip->pmsg_mr_desc = fi_mr_desc(fip->pmsg_mr);
/* allocate persist response message buffer */
size_t msg_resp_size = fip->nlanes *
sizeof(struct rpmem_msg_persist_resp);
fip->pres = malloc(msg_resp_size);
if (!fip->pres) {
RPMEMD_FI_ERR(ret, "allocating messages response buffer");
goto err_msg_resp_malloc;
}
/* register persist response message buffer */
ret = fi_mr_reg(fip->domain, fip->pres, msg_resp_size, FI_SEND,
0, 0, 0, &fip->pres_mr, NULL);
if (ret) {
RPMEMD_FI_ERR(ret, "registering messages "
"response buffer");
goto err_mr_reg_msg_resp;
}
/* get persist message buffer's local descriptor */
fip->pres_mr_desc = fi_mr_desc(fip->pres_mr);
/* initialize lanes */
unsigned i;
for (i = 0; i < fip->nlanes; i++) {
struct rpmemd_fip_lane *lanep = &fip->lanes[i];
/* initialize RECV message */
rpmem_fip_msg_init(&lanep->recv,
fip->pmsg_mr_desc, 0,
lanep,
rpmemd_fip_get_pmsg(fip, i),
fip->pmsg_size,
FI_COMPLETION);
/* initialize SEND message */
rpmem_fip_msg_init(&lanep->send,
fip->pres_mr_desc, 0,
lanep,
&fip->pres[i],
sizeof(fip->pres[i]),
FI_COMPLETION);
}
return 0;
err_mr_reg_msg_resp:
free(fip->pres);
err_msg_resp_malloc:
RPMEMD_FI_CLOSE(fip->pmsg_mr,
"unregistering messages buffer");
err_mr_reg_msg:
free(fip->pmsg);
err_msg_malloc:
return -1;
}
/*
* rpmemd_fip_fini_common -- deinitialize common resources and return last
* error code
*/
static int
rpmemd_fip_fini_common(struct rpmemd_fip *fip)
{
int lret = 0;
int ret;
ret = RPMEMD_FI_CLOSE(fip->pmsg_mr,
"unregistering messages buffer");
if (ret)
lret = ret;
ret = RPMEMD_FI_CLOSE(fip->pres_mr,
"unregistering messages response buffer");
if (ret)
lret = ret;
free(fip->pmsg);
free(fip->pres);
return lret;
}
/*
* rpmemd_fip_check_pmsg -- verify persist message
*/
static inline int
rpmemd_fip_check_pmsg(struct rpmemd_fip *fip, struct rpmem_msg_persist *pmsg)
{
if (pmsg->lane >= fip->nlanes) {
RPMEMD_LOG(ERR, "invalid lane number -- %u", pmsg->lane);
return -1;
}
uintptr_t raddr = pmsg->addr;
uintptr_t laddr = (uintptr_t)fip->addr;
if (raddr < laddr || raddr + pmsg->size > laddr + fip->size) {
RPMEMD_LOG(ERR, "invalid address or size requested "
"for persist operation (0x%lx, %lu)",
raddr, pmsg->size);
return -1;
}
return 0;
}
/*
* rpmemd_fip_process_send -- process FI_SEND completion
*/
static int
rpmemd_fip_process_send(struct rpmemd_fip *fip, struct rpmemd_fip_lane *lanep)
{
lanep->send_posted = 0;
if (lanep->recv_posted)
return 0;
struct rpmem_msg_persist_resp *pres =
rpmem_fip_msg_get_pres(&lanep->send);
*pres = lanep->resp;
int ret;
/* post lane's RECV buffer */
ret = rpmemd_fip_post_msg(lanep);
if (unlikely(ret))
goto err;
/* post lane's SEND buffer */
ret = rpmemd_fip_post_resp(lanep);
err:
return ret;
}
/*
* rpmemd_fip_process_recv -- process FI_RECV completion
*/
static int
rpmemd_fip_process_recv(struct rpmemd_fip *fip, struct rpmemd_fip_lane *lanep)
{
int ret = 0;
lanep->recv_posted = 0;
/*
* Get persist message and persist message response from appropriate
* buffers. The persist message is in lane's RECV buffer and the
* persist response message in lane's SEND buffer.
*/
struct rpmem_msg_persist *pmsg = rpmem_fip_msg_get_pmsg(&lanep->recv);
VALGRIND_DO_MAKE_MEM_DEFINED(pmsg, sizeof(*pmsg));
/* verify persist message */
ret = rpmemd_fip_check_pmsg(fip, pmsg);
if (unlikely(ret))
goto err;
unsigned mode = pmsg->flags & RPMEM_FLUSH_PERSIST_MASK;
if (mode == RPMEM_DEEP_PERSIST) {
fip->deep_persist((void *)pmsg->addr, pmsg->size, fip->ctx);
} else if (mode == RPMEM_PERSIST_SEND) {
fip->memcpy_persist((void *)pmsg->addr, pmsg->data, pmsg->size);
} else {
fip->persist((void *)pmsg->addr, pmsg->size);
}
struct rpmem_msg_persist_resp *pres = lanep->send_posted ?
&lanep->resp : rpmem_fip_msg_get_pres(&lanep->send);
/* return back the lane id */
pres->lane = pmsg->lane;
if (!lanep->send_posted) {
/* post lane's RECV buffer */
ret = rpmemd_fip_post_msg(lanep);
if (unlikely(ret))
goto err;
/* post lane's SEND buffer */
ret = rpmemd_fip_post_resp(lanep);
}
err:
return ret;
}
/*
* rpmemd_fip_cq_read -- wait for specific events on completion queue
*/
static int
rpmemd_fip_cq_read(struct rpmemd_fip *fip, struct fid_cq *cq,
struct rpmemd_fip_lane **lanep, uint64_t *event, uint64_t event_mask)
{
struct fi_cq_err_entry err;
struct fi_cq_msg_entry cq_entry;
const char *str_err;
ssize_t sret;
int ret;
while (!fip->closing) {
sret = fi_cq_sread(cq, &cq_entry, 1, NULL,
RPMEM_FIP_CQ_WAIT_MS);
if (unlikely(fip->closing))
break;
if (unlikely(sret == -FI_EAGAIN || sret == 0))
continue;
if (unlikely(sret < 0)) {
ret = (int)sret;
goto err_cq_read;
}
if (!(cq_entry.flags & event_mask)) {
RPMEMD_LOG(ERR, "unexpected event received %lx",
cq_entry.flags);
ret = -1;
goto err;
}
if (!cq_entry.op_context) {
RPMEMD_LOG(ERR, "null context received");
ret = -1;
goto err;
}
*event = cq_entry.flags & event_mask;
*lanep = cq_entry.op_context;
return 0;
}
return 0;
err_cq_read:
sret = fi_cq_readerr(cq, &err, 0);
if (sret < 0) {
RPMEMD_FI_ERR((int)sret, "error reading from completion queue: "
"cannot read error from completion queue");
goto err;
}
str_err = fi_cq_strerror(cq, err.prov_errno, NULL, NULL, 0);
RPMEMD_LOG(ERR, "error reading from completion queue: %s", str_err);
err:
return ret;
}
/*
* rpmemd_fip_thread -- thread callback which processes persist
* operation
*/
static void *
rpmemd_fip_thread(void *arg)
{
struct rpmemd_fip_thread *thread = arg;
struct rpmemd_fip *fip = thread->fip;
struct rpmemd_fip_lane *lanep = NULL;
uint64_t event = 0;
int ret = 0;
while (!fip->closing) {
ret = rpmemd_fip_cq_read(fip, thread->cq, &lanep, &event,
FI_SEND|FI_RECV);
if (ret)
goto err;
if (unlikely(fip->closing))
break;
RPMEMD_ASSERT(lanep != NULL);
if (event & FI_RECV)
ret = rpmemd_fip_process_recv(fip, lanep);
else if (event & FI_SEND)
ret = rpmemd_fip_process_send(fip, lanep);
if (ret)
goto err;
}
return 0;
err:
return (void *)(uintptr_t)ret;
}
/*
* rpmemd_fip_get_def_nthreads -- get default number of threads for given
* persistency method
*/
static size_t
rpmemd_fip_get_def_nthreads(struct rpmemd_fip *fip)
{
RPMEMD_ASSERT(fip->nlanes > 0);
switch (fip->persist_method) {
case RPMEM_PM_APM:
case RPMEM_PM_GPSPM:
return fip->nlanes;
default:
RPMEMD_ASSERT(0);
return 0;
}
}
/*
* rpmemd_fip_set_attr -- save required attributes in rpmemd_fip handle
*/
static void
rpmemd_fip_set_attr(struct rpmemd_fip *fip, struct rpmemd_fip_attr *attr)
{
fip->addr = attr->addr;
fip->size = attr->size;
fip->persist_method = attr->persist_method;
fip->persist = attr->persist;
fip->memcpy_persist = attr->memcpy_persist;
fip->deep_persist = attr->deep_persist;
fip->ctx = attr->ctx;
fip->buff_size = attr->buff_size;
fip->pmsg_size = roundup(sizeof(struct rpmem_msg_persist) +
fip->buff_size, (size_t)64);
size_t max_nlanes = rpmem_fip_max_nlanes(fip->fi);
RPMEMD_ASSERT(max_nlanes < UINT_MAX);
fip->nlanes = min((unsigned)max_nlanes, attr->nlanes);
if (attr->nthreads) {
fip->nthreads = attr->nthreads;
} else {
/* use default */
fip->nthreads = rpmemd_fip_get_def_nthreads(fip);
}
fip->lanes_per_thread = (fip->nlanes - 1) / fip->nthreads + 1;
size_t cq_size_per_lane = rpmem_fip_cq_size(fip->persist_method,
RPMEM_FIP_NODE_SERVER);
fip->cq_size = fip->lanes_per_thread * cq_size_per_lane;
RPMEMD_ASSERT(fip->persist_method < MAX_RPMEM_PM);
}
/*
* rpmemd_fip_init_thread -- init worker thread
*/
static int
rpmemd_fip_init_thread(struct rpmemd_fip *fip, struct rpmemd_fip_thread *thread)
{
thread->fip = fip;
thread->lanes = malloc(fip->lanes_per_thread * sizeof(*thread->lanes));
if (!thread->lanes) {
RPMEMD_LOG(ERR, "!allocating thread lanes");
goto err_alloc_lanes;
}
struct fi_cq_attr cq_attr = {
.size = fip->cq_size,
.flags = 0,
.format = FI_CQ_FORMAT_MSG, /* need context and flags */
.wait_obj = FI_WAIT_UNSPEC,
.signaling_vector = 0,
.wait_cond = FI_CQ_COND_NONE,
.wait_set = NULL,
};
int ret = fi_cq_open(fip->domain, &cq_attr, &thread->cq, NULL);
if (ret) {
RPMEMD_FI_ERR(ret, "opening completion queue");
goto err_cq_open;
}
return 0;
err_cq_open:
free(thread->lanes);
err_alloc_lanes:
return -1;
}
/*
* rpmemd_fip_fini_thread -- deinitialize worker thread
*/
static void
rpmemd_fip_fini_thread(struct rpmemd_fip *fip, struct rpmemd_fip_thread *thread)
{
RPMEMD_FI_CLOSE(thread->cq, "closing completion queue");
free(thread->lanes);
}
/*
* rpmemd_fip_init_threads -- initialize worker threads
*/
static int
rpmemd_fip_init_threads(struct rpmemd_fip *fip)
{
RPMEMD_ASSERT(fip->lanes != NULL);
RPMEMD_ASSERT(fip->nthreads > 0);
fip->threads = calloc(fip->nthreads, sizeof(*fip->threads));
if (!fip->threads) {
RPMEMD_LOG(ERR, "!allocating threads");
goto err_alloc_threads;
}
int ret;
size_t i;
for (i = 0; i < fip->nthreads; i++) {
ret = rpmemd_fip_init_thread(fip, &fip->threads[i]);
if (ret) {
RPMEMD_LOG(ERR, "!initializing thread %zu", i);
goto err_init_thread;
}
}
for (size_t i = 0; i < fip->nlanes; i++) {
size_t w = i % fip->nthreads;
struct rpmemd_fip_thread *thread = &fip->threads[w];
fip->lanes[i].base.cq = thread->cq;
thread->lanes[thread->nlanes++] = &fip->lanes[i];
}
return 0;
err_init_thread:
for (size_t j = 0; j < i; j++)
rpmemd_fip_fini_thread(fip, &fip->threads[j]);
free(fip->threads);
err_alloc_threads:
return -1;
}
/*
* rpmemd_fip_fini_threads -- deinitialize worker threads
*/
static void
rpmemd_fip_fini_threads(struct rpmemd_fip *fip)
{
for (size_t i = 0; i < fip->nthreads; i++)
rpmemd_fip_fini_thread(fip, &fip->threads[i]);
free(fip->threads);
}
/*
* rpmemd_fip_init -- initialize fabric provider
*/
struct rpmemd_fip *
rpmemd_fip_init(const char *node, const char *service,
struct rpmemd_fip_attr *attr, struct rpmem_resp_attr *resp,
enum rpmem_err *err)
{
int ret;
RPMEMD_ASSERT(resp);
RPMEMD_ASSERT(err);
RPMEMD_ASSERT(attr);
RPMEMD_ASSERT(attr->persist);
struct rpmemd_fip *fip = calloc(1, sizeof(*fip));
if (!fip) {
RPMEMD_LOG(ERR, "!allocating fabric handle");
*err = RPMEM_ERR_FATAL;
return NULL;
}
ret = rpmemd_fip_getinfo(fip, service, node, attr->provider);
if (ret) {
*err = RPMEM_ERR_BADPROVIDER;
goto err_getinfo;
}
rpmemd_fip_set_attr(fip, attr);
ret = rpmemd_fip_init_fabric_res(fip);
if (ret) {
*err = RPMEM_ERR_FATAL;
goto err_init_fabric_res;
}
ret = rpmemd_fip_init_memory(fip);
if (ret) {
*err = RPMEM_ERR_FATAL;
goto err_init_memory;
}
ret = rpmemd_fip_lanes_init(fip);
if (ret) {
*err = RPMEM_ERR_FATAL;
goto err_init_lanes;
}
ret = rpmemd_fip_init_threads(fip);
if (ret) {
*err = RPMEM_ERR_FATAL;
goto err_init_threads;
}
ret = rpmemd_fip_init_common(fip);
if (ret) {
*err = RPMEM_ERR_FATAL;
goto err_init;
}
ret = fi_listen(fip->pep);
if (ret) {
*err = RPMEM_ERR_FATAL_CONN;
goto err_fi_listen;
}
ret = rpmemd_fip_set_resp(fip, resp);
if (ret) {
*err = RPMEM_ERR_FATAL;
goto err_set_resp;
}
return fip;
err_set_resp:
RPMEMD_FI_CLOSE(fip->pep, "closing passive endpoint");
err_fi_listen:
rpmemd_fip_fini_common(fip);
err_init:
rpmemd_fip_fini_threads(fip);
err_init_threads:
rpmemd_fip_fini_lanes(fip);
err_init_lanes:
rpmemd_fip_fini_memory(fip);
err_init_memory:
rpmemd_fip_fini_fabric_res(fip);
err_init_fabric_res:
fi_freeinfo(fip->fi);
err_getinfo:
free(fip);
return NULL;
}
/*
* rpmemd_fip_fini -- deinitialize fabric provider
*/
void
rpmemd_fip_fini(struct rpmemd_fip *fip)
{
rpmemd_fip_fini_common(fip);
rpmemd_fip_fini_threads(fip);
rpmemd_fip_fini_lanes(fip);
rpmemd_fip_fini_memory(fip);
rpmemd_fip_fini_fabric_res(fip);
fi_freeinfo(fip->fi);
free(fip);
}
/*
* rpmemd_fip_accept_one -- accept a single connection
*/
static int
rpmemd_fip_accept_one(struct rpmemd_fip *fip,
struct fi_info *info, struct rpmemd_fip_lane *lanep)
{
int ret;
ret = rpmemd_fip_init_ep(fip, info, &lanep->base);
if (ret)
goto err_init_ep;
ret = rpmemd_fip_post_common(fip, lanep);
if (ret)
goto err_post;
ret = fi_accept(lanep->base.ep, NULL, 0);
if (ret) {
RPMEMD_FI_ERR(ret, "accepting connection request");
goto err_accept;
}
fi_freeinfo(info);
return 0;
err_accept:
err_post:
rpmemd_fip_fini_ep(&lanep->base);
err_init_ep:
fi_freeinfo(info);
return -1;
}
/*
* rpmemd_fip_accept -- accept a single connection request
*/
int
rpmemd_fip_accept(struct rpmemd_fip *fip, int timeout)
{
int ret;
struct fi_eq_cm_entry entry;
uint32_t event;
unsigned nreq = 0; /* number of connection requests */
unsigned ncon = 0; /* number of connected endpoints */
int connecting = 1;
while (connecting && (nreq < fip->nlanes || ncon < fip->nlanes)) {
ret = rpmem_fip_read_eq(fip->eq, &entry,
&event, timeout);
if (ret)
goto err_read_eq;
switch (event) {
case FI_CONNREQ:
ret = rpmemd_fip_accept_one(fip, entry.info,
&fip->lanes[nreq]);
if (ret)
goto err_accept_one;
nreq++;
break;
case FI_CONNECTED:
ncon++;
break;
case FI_SHUTDOWN:
connecting = 0;
break;
default:
RPMEMD_ERR("unexpected event received (%u)", event);
goto err_read_eq;
}
}
return 0;
err_accept_one:
err_read_eq:
return -1;
}
/*
* rpmemd_fip_wait_close -- wait specified time for connection closed event
*/
int
rpmemd_fip_wait_close(struct rpmemd_fip *fip, int timeout)
{
struct fi_eq_cm_entry entry;
int lret = 0;
uint32_t event;
int ret;
for (unsigned i = 0; i < fip->nlanes; i++) {
ret = rpmem_fip_read_eq(fip->eq, &entry, &event, timeout);
if (ret)
lret = ret;
if (event != FI_SHUTDOWN) {
RPMEMD_ERR("unexpected event received "
"(is %u expected %u)",
event, FI_SHUTDOWN);
errno = EINVAL;
lret = -1;
}
}
return lret;
}
/*
* rpmemd_fip_close -- close the connection
*/
int
rpmemd_fip_close(struct rpmemd_fip *fip)
{
int lret = 0;
int ret;
for (unsigned i = 0; i < fip->nlanes; i++) {
ret = rpmemd_fip_fini_ep(&fip->lanes[i].base);
if (ret)
lret = ret;
}
return lret;
}
/*
* rpmemd_fip_process_start -- start processing
*/
int
rpmemd_fip_process_start(struct rpmemd_fip *fip)
{
unsigned i;
for (i = 0; i < fip->nthreads; i++) {
errno = os_thread_create(&fip->threads[i].thread, NULL,
rpmemd_fip_thread, &fip->threads[i]);
if (errno) {
RPMEMD_ERR("!running thread thread");
goto err_thread_create;
}
}
return 0;
err_thread_create:
return -1;
}
/*
* rpmemd_fip_process_stop -- stop processing
*/
int
rpmemd_fip_process_stop(struct rpmemd_fip *fip)
{
/* this stops all threads */
util_fetch_and_or32(&fip->closing, 1);
int ret;
int lret = 0;
for (size_t i = 0; i < fip->nthreads; i++) {
struct rpmemd_fip_thread *thread = &fip->threads[i];
ret = fi_cq_signal(thread->cq);
if (ret) {
RPMEMD_FI_ERR(ret, "sending signal to CQ");
lret = ret;
}
void *tret;
errno = os_thread_join(&thread->thread, &tret);
if (errno) {
RPMEMD_LOG(ERR, "!joining cq thread");
lret = -1;
} else {
ret = (int)(uintptr_t)tret;
if (ret) {
RPMEMD_LOG(ERR,
"cq thread failed with code -- %d",
ret);
lret = ret;
}
}
}
return lret;
}
| 27,089 | 21.259655 | 80 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016, Intel Corporation */
/*
* rpmemd.h -- rpmemd main header file
*/
#define DAEMON_NAME "rpmemd"
| 158 | 16.666667 | 40 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/rpmemd/rpmemd_obc.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* rpmemd_obc.h -- rpmemd out-of-band connection declarations
*/
#include <stdint.h>
#include <sys/types.h>
#include <sys/socket.h>
struct rpmemd_obc;
struct rpmemd_obc_requests {
int (*create)(struct rpmemd_obc *obc, void *arg,
const struct rpmem_req_attr *req,
const struct rpmem_pool_attr *pool_attr);
int (*open)(struct rpmemd_obc *obc, void *arg,
const struct rpmem_req_attr *req);
int (*close)(struct rpmemd_obc *obc, void *arg, int flags);
int (*set_attr)(struct rpmemd_obc *obc, void *arg,
const struct rpmem_pool_attr *pool_attr);
};
struct rpmemd_obc *rpmemd_obc_init(int fd_in, int fd_out);
void rpmemd_obc_fini(struct rpmemd_obc *obc);
int rpmemd_obc_status(struct rpmemd_obc *obc, uint32_t status);
int rpmemd_obc_process(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg);
int rpmemd_obc_create_resp(struct rpmemd_obc *obc,
int status, const struct rpmem_resp_attr *res);
int rpmemd_obc_open_resp(struct rpmemd_obc *obc,
int status, const struct rpmem_resp_attr *res,
const struct rpmem_pool_attr *pool_attr);
int rpmemd_obc_set_attr_resp(struct rpmemd_obc *obc, int status);
int rpmemd_obc_close_resp(struct rpmemd_obc *obc,
int status);
| 1,296 | 31.425 | 65 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/binaryoutputhandler.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018, Intel Corporation
import utils
from reorderexceptions import InconsistentFileException
class BinaryOutputHandler:
"""
Handle :class:`BinaryFile` objects.
Creates and aggregates :class:`BinaryFile` objects for ease of use.
Implements methods for batch handling of aggregated files.
:ivar _files: A list of registered files, most recent last.
:type _files: list
"""
def __init__(self, checker):
"""
Binary handler constructor.
:param checker: consistency checker object
:type checker: ConsistencyCheckerBase
"""
self._files = []
self._checker = checker
def add_file(self, file, map_base, size):
"""
Create and append a mapped file to :attr:`_files`.
:param file: Full path of the mapped file to be added.
:type file: str
:param map_base: Base address of the mapped file.
:type map_base: int
:param size: Size of the file.
:type size: int
:return: None
"""
self._files.append(BinaryFile(file, map_base, size, self._checker))
def remove_file(self, file):
"""Remove file from :attr:`_files`.
:param file: File to be removed.
:type file: str
:return: None
"""
for bf in self._files:
if bf.file_name is file:
self._files.remove(bf)
def do_store(self, store_op):
"""
Perform a store to the given file.
The file is chosen based on the address and size
of the store.
:param store_op: The store operation to be performed.
:type store_op: Store
:return: None
:raises: Generic exception - to be precised later.
"""
store_ok = False
for bf in self._files:
if utils.range_cmp(store_op, bf) == 0:
bf.do_store(store_op)
store_ok = True
if not store_ok:
raise OSError(
"No suitable file found for store {}"
.format(store_op))
def do_revert(self, store_op):
"""
Reverts a store made to a file.
Performing a revert on a store that has not been made
previously yields undefined behavior.
:param store_op: The store to be reverted.
:type store_op: Store
:return: None
:raises: Generic exception - to be precised later.
"""
revert_ok = False
for bf in self._files:
if utils.range_cmp(store_op, bf) == 0:
bf.do_revert(store_op)
revert_ok = True
if not revert_ok:
raise OSError(
"No suitable file found for store {}"
.format(store_op))
def check_consistency(self):
"""
Checks consistency of each registered file.
:return: None
:raises: Generic exception - to be precised later.
"""
for bf in self._files:
if not bf.check_consistency():
raise InconsistentFileException(
"File {} inconsistent".format(bf))
class BinaryFile(utils.Rangeable):
"""Binary file handler.
It is a handler for binary file operations. Internally it
uses mmap to write to and read from the file.
:ivar _file_name: Full path of the mapped file.
:type _file_name: str
:ivar _map_base: Base address of the mapped file.
:type _map_base: int
:ivar _map_max: Max address of the mapped file.
:type _map_max: int
:ivar _file_map: Memory mapped from the file.
:type _file_map: mmap.mmap
:ivar _checker: consistency checker object
:type _checker: ConsistencyCheckerBase
"""
def __init__(self, file_name, map_base, size, checker):
"""
Initializes the binary file handler.
:param file_name: Full path of the mapped file to be added.
:type file_name: str
:param map_base: Base address of the mapped file.
:type map_base: int
:param size: Size of the file.
:type size: int
:param checker: consistency checker object
:type checker: ConsistencyCheckerBase
:return: None
"""
self._file_name = file_name
self._map_base = map_base
self._map_max = map_base + size
# TODO consider mmaping only necessary parts on demand
self._file_map = utils.memory_map(file_name)
self._checker = checker
def __str__(self):
return self._file_name
def do_store(self, store_op):
"""
Perform the store on the file.
The store records the old value for reverting.
:param store_op: The store to be performed.
:type store_op: Store
:return: None
"""
base_off = store_op.get_base_address() - self._map_base
max_off = store_op.get_max_address() - self._map_base
# read and save old value
store_op.old_value = bytes(self._file_map[base_off:max_off])
# write out the new value
self._file_map[base_off:max_off] = store_op.new_value
self._file_map.flush(base_off & ~4095, 4096)
def do_revert(self, store_op):
"""
Reverts the store.
Write back the old value recorded while doing the store.
Reverting a store which has not been made previously has
undefined behavior.
:param store_op: The store to be reverted.
:type store_op: Store
:return: None
"""
base_off = store_op.get_base_address() - self._map_base
max_off = store_op.get_max_address() - self._map_base
# write out the old value
self._file_map[base_off:max_off] = store_op.old_value
self._file_map.flush(base_off & ~4095, 4096)
def check_consistency(self):
"""
Check consistency of the file.
:return: True if consistent, False otherwise.
:rtype: bool
"""
return self._checker.check_consistency(self._file_name) == 0
def get_base_address(self):
"""
Returns the base address of the file.
Overrides from :class:`utils.Rangeable`.
:return: The base address of the mapping passed to the constructor.
:rtype: int
"""
return self._map_base
def get_max_address(self):
"""
Get max address of the file mapping.
Overrides from :class:`utils.Rangeable`.
:return: The max address of the mapping.
:rtype: int
"""
return self._map_max
| 6,672 | 29.47032 | 75 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/pmreorder.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018-2019, Intel Corporation
import argparse
import statemachine
import opscontext
import consistencycheckwrap
import loggingfacility
import markerparser
import sys
import reorderengines
def main():
pmreorder_version = "unknown"
'''
Argv[1] should be given in order to use -v or --version flag. It is passed
from the installed script. We check whether argv[1] was given and if it's
not any of regular parameters we use it as a version of pmreorder and
remove it from the arguments list.
'''
if len(sys.argv) > 1 and sys.argv[1][0] != "-":
pmreorder_version = sys.argv[1]
del sys.argv[1]
# TODO unicode support
# TODO parameterize reorder engine type
parser = argparse.ArgumentParser(description="Store reordering tool")
parser.add_argument("-l", "--logfile",
required=True,
help="the pmemcheck log file to process")
parser.add_argument("-c", "--checker",
choices=consistencycheckwrap.checkers,
default=consistencycheckwrap.checkers[0],
help="choose consistency checker type")
parser.add_argument("-p", "--path",
required=True,
help="path to the consistency checker and arguments",
nargs='+')
parser.add_argument("-n", "--name",
help="consistency check function " +
"for the 'lib' checker")
parser.add_argument("-o", "--output",
help="set the logger output file")
parser.add_argument("-e", "--output-level",
choices=loggingfacility.log_levels,
help="set the output log level")
parser.add_argument("-x", "--extended-macros",
help="list of pairs MARKER=ENGINE or " +
"json config file")
parser.add_argument("-v", "--version",
help="print version of the pmreorder",
action="version",
version="%(prog)s " + pmreorder_version)
engines_keys = list(reorderengines.engines.keys())
parser.add_argument("-r", "--default-engine",
help="set default reorder engine " +
"default=NoReorderNoChecker",
choices=engines_keys,
default=engines_keys[0])
args = parser.parse_args()
logger = loggingfacility.get_logger(
args.output,
args.output_level)
checker = consistencycheckwrap.get_checker(
args.checker,
' '.join(args.path),
args.name)
markers = markerparser.MarkerParser().get_markers(args.extended_macros)
# create the script context
context = opscontext.OpsContext(
args.logfile,
checker,
logger,
args.default_engine,
markers)
# init and run the state machine
a = statemachine.StateMachine(statemachine.InitState(context))
if a.run_all(context.extract_operations()) is False:
sys.exit(1)
if __name__ == "__main__":
main()
| 3,546 | 38.853933 | 78 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/opscontext.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018, Intel Corporation
from operationfactory import OperationFactory
from binaryoutputhandler import BinaryOutputHandler
import reorderengines
import memoryoperations
from itertools import repeat
class OpsContext:
"""
Holds the context of the performed operations.
:ivar _operations: The operations to be performed, based on the log file.
:type _operations: list of strings
:ivar reorder_engine: The reordering engine used at the moment.
:type one of the reorderengine Class
:ivar default_engine: The default reordering engine.
:type default_engine: One of the reorderengines Class
:ivar test_on_barrier: Check consistency on barrier.
:type test_on_barrier: bool
:ivar default_barrier: Default consistency barrier status.
:type default_barrier: bool
:ivar file_handler: The file handler used.
"""
def __init__(self, log_file, checker, logger, arg_engine, markers):
"""
Splits the operations in the log file and sets the instance variables
to default values.
:param log_file: The full name of the log file.
:type log_file: str
:return: None
"""
# TODO reading the whole file at once is rather naive
# change in the future
self._operations = open(log_file).read().split("|")
engine = reorderengines.get_engine(arg_engine)
self.reorder_engine = engine
self.test_on_barrier = engine.test_on_barrier
self.default_engine = self.reorder_engine
self.default_barrier = self.default_engine.test_on_barrier
self.file_handler = BinaryOutputHandler(checker)
self.checker = checker
self.logger = logger
self.markers = markers
self.stack_engines = [('START', getattr(memoryoperations, arg_engine))]
# TODO this should probably be made a generator
def extract_operations(self):
"""
Creates specific operation objects based on the labels available
in the split log file.
:return: list of subclasses of :class:`memoryoperations.BaseOperation`
"""
stop_index = start_index = 0
for i, elem in enumerate(self._operations):
if "START" in elem:
start_index = i
elif "STOP" in elem:
stop_index = i
return list(map(OperationFactory.create_operation,
self._operations[start_index + 1:stop_index],
repeat(self.markers), repeat(self.stack_engines)))
| 2,580 | 36.405797 | 79 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/reorderexceptions.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018, Intel Corporation
class InconsistentFileException(Exception):
pass
class NotSupportedOperationException(Exception):
pass
| 191 | 16.454545 | 48 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/markerparser.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018, Intel Corporation
import os
import json
class MarkerParser:
"""
Parse marker config file and command line arg provided by user
via -x parameter.
"""
def marker_file_parser(self, macros):
"""
Parse markers passed by file.
They should be in json format:
{ "MARKER_NAME"="ENGINE_TYPE" } and separated by commas.
"""
markers = {}
try:
with open(macros) as config_file:
markers = json.load(config_file)
except json.decoder.JSONDecodeError:
print("Invalid config macros file format: ", macros,
"Use: {\"MARKER_NAME1\"=\"ENGINE_TYPE1\","
"\"MARKER_NAME2\"=\"ENGINE_TYPE2\"}")
return markers
def marker_cli_parser(self, macros):
"""
Parse markers passed by cli.
They should be in specific format:
MARKER_NAME=ENGINE_TYPE and separated by commas.
"""
try:
markers_array = macros.split(",")
return dict(pair.split('=') for pair in markers_array)
except ValueError:
print("Invalid extended macros format: ", macros,
"Use: MARKER_NAME1=ENGINE_TYPE1,MARKER_NAME2=ENGINE_TYPE2")
def get_markers(self, markerset):
"""
Parse markers based on their format.
"""
if markerset is not None:
if os.path.exists(markerset):
return self.marker_file_parser(markerset)
else:
return self.marker_cli_parser(markerset)
| 1,628 | 29.735849 | 77 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/consistencycheckwrap.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018, Intel Corporation
from sys import exit
from os import path
from ctypes import cdll, c_char_p, c_int
import os
checkers = ["prog", "lib"]
class ConsistencyCheckerBase:
"""
Base class for consistency checker classes.
Checker of each type should implement check_consistency method.
"""
def check_consistency(self, filename):
pass
class LibChecker(ConsistencyCheckerBase):
"""
Allows registration of a consistency checking function and verifying
the consistency of a file.
The function has to be in a shared library. It is then used to check
consistency of an arbitrary file. The function has to take a file name
as the only parameter and return an int: 0 for inconsistent, 1 for
consistent. The prototype of the function::
int func_name(const char* file_name)
"""
def __init__(self, library_name, func_name):
"""
Loads the consistency checking function from the given library.
:param library_name: The full name of the library.
:type library_name: str
:param func_name: The name of the consistency
checking function within the library.
:type func_name: str
:return: None
"""
self._lib_func = getattr(cdll.LoadLibrary(library_name), func_name)
self._lib_func.argtypes = [c_char_p]
self._lib_func.restype = c_int
def check_consistency(self, filename):
"""
Checks the consistency of a given file
using the previously loaded function.
:param filename: The full name of the file to be checked.
:type filename: str
:return: 1 if file is consistent, 0 otherwise.
:rtype: int
:raises: Generic exception, when no function has been loaded.
"""
if self._lib_func is None:
raise RuntimeError("Consistency check function not loaded")
return self._lib_func(filename)
class ProgChecker(ConsistencyCheckerBase):
"""
Allows registration of a consistency checking program and verifying
the consistency of a file.
"""
def __init__(self, bin_path, bin_args):
self._bin_path = bin_path
self._bin_cmd = bin_args
def check_consistency(self, filename):
"""
Checks the consistency of a given file
using the previously loaded function.
:param filename: The full name of the file to be checked.
:type filename: str
:return: 1 if file is consistent, 0 otherwise.
:rtype: int
:raises: Generic exception, when no function has been loaded.
"""
if self._bin_path is None or self._bin_cmd is None:
raise RuntimeError("consistency check handle not set")
return os.system(self._bin_path + " " + self._bin_cmd + " " + filename)
def get_checker(checker_type, checker_path_args, name):
checker_path_args = checker_path_args.split(" ", 1)
checker_path = checker_path_args[0]
# check for params
if len(checker_path_args) > 1:
args = checker_path_args[1]
else:
args = ""
if not path.exists(checker_path):
print("Invalid path:" + checker_path)
exit(1)
checker = None
if checker_type == "prog":
checker = ProgChecker(checker_path, args)
elif checker_type == "lib":
checker = LibChecker(checker_path, name)
return checker
| 3,475 | 29.761062 | 79 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/operationfactory.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018-2019, Intel Corporation
import memoryoperations
from reorderexceptions import NotSupportedOperationException
class OperationFactory:
"""
An abstract memory operation factory.
This object factory puts special constraints on names of classes.
It creates objects based on log in string format, as such the
classes have to start with a capital letter and the rest of the
name has to be in lowercase. For example::
STORE -> Store
FULL_REORDER -> Full_reorder
The object to be created has to have and internal **Factory** class
with a :func:`create` method taking a string parameter. For example see
:class:`memoryoperations.Store`.
:cvar __factories: The registered object factories.
:type __factories: dict
"""
__factories = {}
__suffix = ['.BEGIN', '.END']
memoryoperations.BaseOperation()
@staticmethod
def add_factory(id_, operation_factory):
"""
Explicitly register an object factory.
This method should be used when the factory cannot be inferred
from the name of the object to be created.
:param id_: The id under which this factory is to be registered
in the dictionary.
:type id_: str
:param operation_factory: The operation factory to be registered.
:return: None
"""
OperationFactory.__factories[id_] = operation_factory
@staticmethod
def create_operation(string_operation, markers, stack):
def check_marker_format(marker):
"""
Checks if marker has proper suffix.
"""
for s in OperationFactory.__suffix:
if marker.endswith(s):
return
raise NotSupportedOperationException(
"Incorrect marker format {}, suffix is missing."
.format(marker))
def check_pair_consistency(stack, marker):
"""
Checks if markers do not cross.
You can pop from stack only if end
marker match previous one.
Example OK:
MACRO1.BEGIN
MACRO2.BEGIN
MACRO2.END
MACRO1.END
Example NOT OK:
MACRO1.BEGIN
MACRO2.BEGIN
MACRO1.END
MACRO2.END
"""
top = stack[-1][0]
if top.endswith(OperationFactory.__suffix[0]):
top = top[:-len(OperationFactory.__suffix[0])]
if marker.endswith(OperationFactory.__suffix[-1]):
marker = marker[:-len(OperationFactory.__suffix[-1])]
if top != marker:
raise NotSupportedOperationException(
"Cannot cross markers: {0}, {1}"
.format(top, marker))
"""
Creates the object based on the pre-formatted string.
The string needs to be in the specific format. Each specific value
in the string has to be separated with a `;`. The first field
has to be the name of the operation, the rest are operation
specific values.
:param string_operation: The string describing the operation.
:param markers: The dict describing the pair marker-engine.
:param stack: The stack describing the order of engine changes.
:return: The specific object instantiated based on the string.
"""
id_ = string_operation.split(";")[0]
id_case_sensitive = id_.lower().capitalize()
# checks if id_ is one of memoryoperation classes
mem_ops = getattr(memoryoperations, id_case_sensitive, None)
# if class is not one of memoryoperations
# it means it can be user defined marker
if mem_ops is None:
check_marker_format(id_)
# if id_ is section BEGIN
if id_.endswith(OperationFactory.__suffix[0]):
# BEGIN defined by user
marker_name = id_.partition('.')[0]
if markers is not None and marker_name in markers:
engine = markers[marker_name]
try:
mem_ops = getattr(memoryoperations, engine)
except AttributeError:
raise NotSupportedOperationException(
"Not supported reorder engine: {}"
.format(engine))
# BEGIN but not defined by user
else:
mem_ops = stack[-1][1]
if issubclass(mem_ops, memoryoperations.ReorderBase):
stack.append((id_, mem_ops))
# END section
elif id_.endswith(OperationFactory.__suffix[-1]):
check_pair_consistency(stack, id_)
stack.pop()
mem_ops = stack[-1][1]
# here we have proper memory operation to perform,
# it can be Store, Fence, ReorderDefault etc.
id_ = mem_ops.__name__
if id_ not in OperationFactory.__factories:
OperationFactory.__factories[id_] = mem_ops.Factory()
return OperationFactory.__factories[id_].create(string_operation)
| 5,329 | 35.506849 | 75 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/utils.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018, Intel Corporation
import os
import mmap
class Rangeable:
"""
Interface for all rangeable objects.
All rangeable objects must be able to return their base and max
addresses.
"""
def get_base_address(self):
"""
Getter for the base address of the object.
:return: The base address of the object.
:rtype: int
"""
raise NotImplementedError
def get_max_address(self):
"""
Getter for the max address of the object.
:return: The max address of the object.
:rtype: int
"""
raise NotImplementedError
class StackTrace:
def __init__(self, trace=None):
self.trace = trace
def __str__(self):
ret = ""
if self.trace is not None:
for line in self.trace:
ret += " by\t{}\n".format(line)
return ret
def memory_map(filename, size=0, access=mmap.ACCESS_WRITE, offset=0):
"""
Memory map a file.
:Warning:
`offset` has to be a non-negative multiple of PAGESIZE or
ALLOCATIONGRANULARITY
:param filename: The file to be mapped.
:type filename: str
:param size: Number of bytes to be mapped. If is equal 0, the
whole file at the moment of the call will be mapped.
:type size: int
:param offset: The offset within the file to be mapped.
:type offset: int
:param access: The type of access provided to mmap.
:return: The mapped file.
:rtype: mmap.mmap
"""
fd = os.open(filename, os.O_RDWR)
m_file = mmap.mmap(fd, size, access=access, offset=offset)
os.close(fd)
return m_file
def range_cmp(lhs, rhs):
"""
A range compare function.
:param lhs: The left hand side of the comparison.
:type lhs: Rangeable
:param rhs: The right hand side of the comparison.
:type rhs: Rangeable
:return: -1 if lhs is before rhs, 1 when after and 0 on overlap.
:rtype: int
The comparison function may be explained as::
Will return -1:
|___lhs___|
|___rhs___|
Will return +1:
|___rhs___|
|___lhs___|
Will return 0:
|___lhs___|
|___rhs___|
"""
if lhs.get_max_address() <= rhs.get_base_address():
return -1
elif lhs.get_base_address() >= rhs.get_max_address():
return 1
else:
return 0
| 2,487 | 23.15534 | 69 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/memoryoperations.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018, Intel Corporation
from utils import Rangeable
from utils import range_cmp
from utils import StackTrace
from sys import byteorder
class BaseOperation:
"""
Base class for all memory operations.
"""
pass
class Fence(BaseOperation):
"""
Describes a fence operation.
The exact type of the memory barrier is not important,
it is interpreted as an SFENCE or MFENCE.
"""
class Factory:
"""
Internal factory class to be used in dynamic object creation.
"""
def create(self, values):
"""
Factory object creation method.
:param values: Ignored.
:type values: str
:return: New Fence object.
:rtype: Fence
"""
return Fence()
class Store(BaseOperation, Rangeable):
"""
Describes a store operation.
:ivar address: The virtual address at which to store the new value.
:type address: int
:ivar new_value: The new value to be written.
:type new_value: bytearray
:ivar size: The size of the store in bytes.
:type size: int
:ivar old_value: The old value read from the file.
:type old_value: bytearray
:ivar flushed: Indicates whether the store has been flushed.
:type flushed: bool
"""
def __init__(self, values):
"""
Initializes the object based on the describing string.
:param values: Pre-formatted string describing the store.
:type values: str
:return: None
"""
params = values.split(";")
# calculate the offset given the registered file mapping
self.address = int(params[1], 16)
self.size = int(params[3], 16)
self.new_value = \
int(params[2], 16).to_bytes(self.size, byteorder=byteorder)
if len(params) > 4:
self.trace = StackTrace(params[4:])
else:
self.trace = StackTrace(["No trace available", ])
self.old_value = None
self.flushed = False
def __str__(self):
return "addr: " + hex(self.address) + " size " + \
str(self.size) + " value " + str(self.new_value)
def get_base_address(self):
"""
Override from :class:`utils.Rangeable`.
:return: Virtual address of the store.
:rtype: int
"""
return self.address
def get_max_address(self):
"""
Override from :class:`utils.Rangeable`.
:return: Virtual address of the first byte after the store.
:rtype: int
"""
return self.address + self.size
class Factory():
"""
Internal factory class to be used in dynamic object creation.
"""
def create(self, values):
"""
Factory object creation method.
:param values: Pre-formatted string describing the store.
:type values: str
:return: New Store object.
:rtype: Store
"""
return Store(values)
class FlushBase(BaseOperation, Rangeable):
"""
Base class for flush operations.
"""
def is_in_flush(self, store_op):
"""
Check if a given store is within the flush.
:param store_op: Store operation to check.
:return: True if store is in flush, false otherwise.
:rtype: bool
"""
raise NotImplementedError
class Flush(FlushBase):
"""
Describes a flush operation.
Examples of flush instructions are CLFLUSH, CLFLUSHOPT or CLWB.
:ivar _address: Virtual address of the flush.
:type _address: int
:ivar _size: The size of the flush in bytes (should be cache line aligned).
:type _size: int
"""
def __init__(self, values):
"""
Initializes the object based on the describing string.
:param values: Pre-formatted string describing the flush.
:type values: str
:return: None
"""
params = values.split(";")
self._address = int(params[1], 16)
self._size = int(params[2], 16)
def is_in_flush(self, store_op):
"""
Override from :class:`FlushBase`.
:param store_op: Store operation to check.
:return: True if store is in flush, false otherwise.
:rtype: bool
"""
if range_cmp(store_op, self) == 0:
return True
else:
return False
def get_base_address(self):
"""
Override from :class:`utils.Rangeable`.
:return: Virtual address of the flush.
:rtype: int
"""
return self._address
def get_max_address(self):
"""
Override from :class:`utils.Rangeable`.
:return: Virtual address of the first byte after the flush.
:rtype: int
"""
return self._address + self._size
class Factory:
"""
Internal factory class to be used in dynamic object creation.
"""
def create(self, values):
"""
Factory object creation method.
:param values: Pre-formatted string describing the flush.
:type values: str
:return: New Flush object.
:rtype: Flush
"""
return Flush(values)
class ReorderBase(BaseOperation):
"""
Base class for all reorder type classes.
"""
pass
class NoReorderDoCheck(ReorderBase):
"""
Describes the type of reordering engine to be used.
This marker class triggers writing the whole sequence of stores
between barriers.
"""
class Factory:
"""
Internal factory class to be used in dynamic object creation.
"""
def create(self, values):
"""
Factory object creation method.
:param values: Ignored.
:type values: str
:return: New NoReorderDoCheck object.
:rtype: NoReorderDoCheck
"""
return NoReorderDoCheck()
class ReorderFull(ReorderBase):
"""
Describes the type of reordering engine to be used.
This marker class triggers writing all possible sequences of stores
between barriers.
"""
class Factory:
"""
Internal factory class to be used in dynamic object creation.
"""
def create(self, values):
"""
Factory object creation method.
:param values: Ignored.
:type values: str
:return: New ReorderFull object.
:rtype: ReorderFull
"""
return ReorderFull()
class ReorderAccumulative(ReorderBase):
"""
Describes the type of reordering engine to be used.
This marker class triggers writing all
possible accumulative sequences of stores
between barriers.
"""
class Factory:
"""
Internal factory class to be used in dynamic object creation.
"""
def create(self, values):
"""
Factory object creation method.
:param values: Ignored.
:type values: str
:return: New ReorderAccumulative object.
:rtype: ReorderAccumulative
"""
return ReorderAccumulative()
class ReorderReverseAccumulative(ReorderBase):
"""
Describes the type of reordering engine to be used.
This marker class triggers writing all
possible reverted accumulative sequences of stores
between barriers.
"""
class Factory:
"""
Internal factory class to be used in dynamic object creation.
"""
def create(self, values):
"""
Factory object creation method.
:param values: Ignored.
:type values: str
:return: New ReorderReverseAccumulative object.
:rtype: ReorderReverseAccumulative
"""
return ReorderReverseAccumulative()
class NoReorderNoCheck(ReorderBase):
"""
Describes the type of reordering engine to be used.
This marker class triggers writing the whole sequence of stores
between barriers. It additionally marks that no consistency checking
is to be made.
"""
class Factory:
"""
Internal factory class to be used in dynamic object creation.
"""
def create(self, values):
"""
Factory object creation method.
:param values: Ignored.
:type values: str
:return: New NoReorderNoCheck object.
:rtype: NoReorderNoCheck
"""
return NoReorderNoCheck()
class ReorderDefault(ReorderBase):
"""
Describes the default reordering engine to be used.
This marker class triggers default reordering.
"""
class Factory:
"""
Internal factory class to be used in dynamic object creation.
"""
def create(self, values):
"""
Factory object creation method.
:param values: Ignored.
:type values: str
:return: ReorderDefault object.
:rtype: ReorderDefault
"""
return ReorderDefault()
class ReorderPartial(ReorderBase):
"""
Describes the type of reordering engine to be used.
This marker class triggers writing a subset of all possible
sequences of stores between barriers.
The type of partial reordering is chosen at runtime. Not yet
implemented.
"""
class Factory:
"""
Internal factory class to be used in dynamic object creation.
"""
def create(self, values):
"""
Factory object creation method.
:param values: Ignored.
:type values: str
:return: New ReorderPartial object.
:rtype: ReorderPartial
"""
return ReorderPartial()
class Register_file(BaseOperation):
"""
Describes the file to be mapped into processes address space.
:ivar name: The full name of the file.
:type name: str
:ivar address: The base address where the file was mapped.
:type address: int
:ivar size: The size of the mapping.
:type size: int
:ivar offset: The start offset of the mapping within the file.
:type offset: int
"""
def __init__(self, values):
"""
Initializes the object based on the describing string.
:param values: Pre-formatted string describing the flush.
:type values: str
:return: None
"""
params = values.split(";")
self.name = params[1]
self.address = int(params[2], 16)
self.size = int(params[3], 16)
self.offset = int(params[4], 16)
class Factory():
"""
Internal factory class to be used in dynamic object creation.
"""
def create(self, values):
"""
Factory object creation method.
:param values: Pre-formatted string
describing the file registration.
:type values: str
:return: New Register_file object.
:rtype: Register_file
"""
return Register_file(values)
| 11,289 | 26.270531 | 79 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/loggingfacility.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018-2020, Intel Corporation
import logging
log_levels = ["debug", "info", "warning", "error", "critical"]
class LoggingBase:
def debug(self, text):
pass
def info(self, text):
pass
def warning(self, text):
pass
def error(self, text):
pass
def critical(self, text):
pass
class DefaultFileLogger(LoggingBase):
def __init__(self, name="pmreorder", **kwargs):
logging.basicConfig(**kwargs)
self.__logger = logging.getLogger(name)
def debug(self, text):
self.__logger.debug(text)
def info(self, text):
self.__logger.info(text)
def warning(self, text):
self.__logger.warning(text)
def error(self, text):
self.__logger.error(text)
def critical(self, text):
self.__logger.critical(text)
class DefaultPrintLogger(LoggingBase):
def debug(self, text):
print("DEBUG:", text)
def info(self, text):
print("INFO:", text)
def warning(self, text):
print("WARNING:", text)
def error(self, text):
print("ERROR:", text)
def critical(self, text):
print("CRITICAL:", text)
def get_logger(log_output, log_level=None):
logger = None
# check if log_level is valid
log_level = "warning" if log_level is None else log_level
numeric_level = getattr(logging, log_level.upper())
if not isinstance(numeric_level, int):
raise ValueError('Invalid log level: {}'.format(log_level.upper()))
if log_output is None:
logger = DefaultPrintLogger()
else:
logger = DefaultFileLogger(filename=log_output, level=numeric_level)
return logger
| 1,731 | 21.205128 | 76 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/statemachine.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018-2020, Intel Corporation
import memoryoperations as memops
import reorderengines
from reorderexceptions import InconsistentFileException
from reorderexceptions import NotSupportedOperationException
class State:
"""
The base class of all states.
:ivar _context: The reordering context.
:type _context: opscontext.OpsContext
:ivar trans_stores: The list of unflushed stores.
:type trans_stores: list of :class:`memoryoperations.Store`
"""
trans_stores = []
def __init__(self, context):
"""
Default state constructor.
:param context: The context of the reordering.
:type context: opscontext.OpsContext
"""
self._context = context
def next(self, in_op):
"""
Go to the next state based on the input.
:Note:
The next state might in fact be the same state.
:param in_op: The state switch trigger operation.
:type in_op: subclass of :class:`memoryoperations.BaseOperation`
:return: The next state.
:rtype: subclass of :class:`State`
"""
raise NotImplementedError
def run(self, in_op):
"""
Perform the required operation in this state.
:param in_op: The operation to be performed in this state.
:type in_op: subclass of :class:`memoryoperations.BaseOperation`
:return: None
"""
raise NotImplementedError
class InitState(State):
"""
The initial no-op state.
"""
def __init__(self, context):
"""
Saves the reordering context.
:param context: The reordering context.
:type context: opscontext.OpsContext
"""
super(InitState, self).__init__(context)
def next(self, in_op):
"""
Switch to the next valid state.
:param in_op: Ignored.
:return: The next valid state.
:rtype: CollectingState
"""
return CollectingState(self._context)
def run(self, in_op):
"""
Does nothing.
:param in_op: Ignored.
:return: always True
"""
return True
class CollectingState(State):
"""
Collects appropriate operations.
This state mostly aggregates stores and flushes. It also
validates which stores will be made persistent and passes
them on to the next state.
:ivar _ops_list: The list of collected stores.
:type _ops_list: list of :class:`memoryoperations.Store`
:ivar _inner_state: The internal state of operations.
:type _inner_state: str
"""
def __init__(self, context):
"""
Saves the reordering context.
:param context: The reordering context.
:type context: opscontext.OpsContext
"""
super(CollectingState, self).__init__(context)
self._ops_list = []
self._ops_list += State.trans_stores
self._inner_state = "init"
def next(self, in_op):
"""
Switch to the next valid state.
:param in_op: The state switch trigger operation.
:type in_op: subclass of :class:`memoryoperations.BaseOperation`
:return: The next state.
:rtype: subclass of :class:`State`
"""
if isinstance(in_op, memops.Fence) and \
self._inner_state == "flush":
return ReplayingState(self._ops_list, self._context)
else:
return self
def run(self, in_op):
"""
Perform operations in this state.
Based on the type of operation, different handling is employed.
The recognized and handled types of operations are:
* :class:`memoryoperations.ReorderBase`
* :class:`memoryoperations.FlushBase`
* :class:`memoryoperations.Store`
* :class:`memoryoperations.Register_file`
:param in_op: The operation to be performed in this state.
:type in_op: subclass of :class:`memoryoperations.BaseOperation`
:return: always True
"""
self.move_inner_state(in_op)
if isinstance(in_op, memops.ReorderBase):
self.substitute_reorder(in_op)
elif isinstance(in_op, memops.FlushBase):
self.flush_stores(in_op)
elif isinstance(in_op, memops.Store):
self._ops_list.append(in_op)
elif isinstance(in_op, memops.Register_file):
self.reg_file(in_op)
return True
def substitute_reorder(self, order_ops):
"""
Changes the reordering engine based on the log marker class.
:param order_ops: The reordering marker class.
:type order_ops: subclass of :class:`memoryoperations.ReorderBase`
:return: None
"""
if isinstance(order_ops, memops.ReorderFull):
self._context.reorder_engine = \
reorderengines.FullReorderEngine()
self._context.test_on_barrier = \
self._context.reorder_engine.test_on_barrier
elif isinstance(order_ops, memops.ReorderPartial):
# TODO add macro in valgrind or
# parameter inside the tool to support parameters?
self._context.reorder_engine = \
reorderengines.RandomPartialReorderEngine(3)
self._context.test_on_barrier = \
self._context.reorder_engine.test_on_barrier
elif isinstance(order_ops, memops.ReorderAccumulative):
self._context.reorder_engine = \
reorderengines.AccumulativeReorderEngine()
self._context.test_on_barrier = \
self._context.reorder_engine.test_on_barrier
elif isinstance(order_ops, memops.ReorderReverseAccumulative):
self._context.reorder_engine = \
reorderengines.AccumulativeReverseReorderEngine()
self._context.test_on_barrier = \
self._context.reorder_engine.test_on_barrier
elif isinstance(order_ops, memops.NoReorderDoCheck):
self._context.reorder_engine = reorderengines.NoReorderEngine()
self._context.test_on_barrier = \
self._context.reorder_engine.test_on_barrier
elif isinstance(order_ops, memops.NoReorderNoCheck):
self._context.reorder_engine = reorderengines.NoCheckerEngine()
self._context.test_on_barrier = \
self._context.reorder_engine.test_on_barrier
elif isinstance(order_ops, memops.ReorderDefault):
self._context.reorder_engine = self._context.default_engine
self._context.test_on_barrier = self._context.default_barrier
else:
raise NotSupportedOperationException(
"Not supported reorder engine: {}"
.format(order_ops))
def flush_stores(self, flush_op):
"""
Marks appropriate stores as flushed.
Does not align the flush, the log is expected to have the
flushes properly aligned.
:param flush_op: The flush operation marker.
:type flush_op: subclass of :class:`memoryoperations.FlushBase`
:return: None
"""
for st in self._ops_list:
if flush_op.is_in_flush(st):
st.flushed = True
def reg_file(self, file_op):
"""
Register a new file mapped into virtual memory.
:param file_op: File registration operation marker.
:type file_op: memoryoperations.Register_file
:return: None
"""
self._context.file_handler.add_file(file_op.name,
file_op.address,
file_op.size)
def move_inner_state(self, in_op):
"""
Tracks the internal state of the collection.
The collected stores need to be processed only at specific moments -
after full persistent memory barriers (flush-fence).
:param in_op: The performed operation.
:type in_op: subclass of :class:`memoryoperations.BaseOperation`
:return: None
"""
if isinstance(in_op, memops.Store) and \
self._inner_state == "init":
self._inner_state = "dirty"
elif isinstance(in_op, memops.FlushBase) and \
self._inner_state == "dirty":
self._inner_state = "flush"
elif isinstance(in_op, memops.Fence) and \
self._inner_state == "flush":
self._inner_state = "fence"
elif isinstance(in_op, memops.Flush) and \
self._inner_state == "init":
self._inner_state = "flush"
class ReplayingState(State):
"""
Replays all collected stores according to the reordering context.
:ivar _ops_list: The list of stores to be reordered and replayed.
:type _ops_list: list of :class:`memoryoperations.Store`
"""
def __init__(self, in_ops_list, context):
"""
:param in_ops_list:
:param context:
:return:
"""
super(ReplayingState, self).__init__(context)
self._ops_list = in_ops_list
def next(self, in_op):
"""
Switches to the collecting state regardless of the input.
:param in_op: Ignored.
:type in_op: subclass of :class:`memoryoperations.BaseOperation`
:return: The next state.
:rtype: CollectingState
"""
return CollectingState(self._context)
def run(self, in_op):
"""
Perform operations in this state.
The replaying state performs reordering and if necessary checks
the consistency of the registered files. The decisions and
type of reordering to be used is defined by the context.
:param in_op: The operation to be performed in this state.
:type in_op: subclass of :class:`memoryoperations.BaseOperation`
:return: State of consistency check.
"""
# specifies consistency state of sequence
consistency = True
# consider only flushed stores
flushed_stores = list(filter(lambda x: x.flushed, self._ops_list))
# not-flushed stores should be passed to next state
State.trans_stores = list(filter(lambda x: x.flushed is False,
self._ops_list))
if self._context.test_on_barrier:
for seq in self._context.reorder_engine.generate_sequence(
flushed_stores):
for op in seq:
# do stores
self._context.file_handler.do_store(op)
# check consistency of all files
try:
self._context.file_handler.check_consistency()
except InconsistentFileException as e:
consistency = False
self._context.logger.warning(e)
stacktrace = "Call trace:\n"
for num, op in enumerate(seq):
stacktrace += "Store [{}]:\n".format(num)
stacktrace += str(op.trace)
self._context.logger.warning(stacktrace)
for op in reversed(seq):
# revert the changes
self._context.file_handler.do_revert(op)
# write all flushed stores
for op in flushed_stores:
self._context.file_handler.do_store(op)
return consistency
class StateMachine:
"""
The state machine driver.
:ivar _curr_state: The current state.
:type _curr_state: subclass of :class:`State`
"""
def __init__(self, init_state):
"""
Initialize the state machine with a specified state.
:param init_state: The initial state to be used.
:type init_state: subclass of :class:`State`
"""
self._curr_state = init_state
def run_all(self, operations):
"""
Starts the state machine.
:param operations: The operations to be performed by the state
machine.
:type operations: list of :class:`memoryoperations.BaseOperation`
:return: None
"""
all_consistent = True
for ops in operations:
self._curr_state = self._curr_state.next(ops)
check = self._curr_state.run(ops)
if check is False:
all_consistent = check
return all_consistent
| 12,546 | 33.375342 | 78 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmreorder/reorderengines.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018, Intel Corporation
from itertools import combinations
from itertools import permutations
from itertools import islice
from itertools import chain
from random import sample
from functools import partial
from reorderexceptions import NotSupportedOperationException
import collections
class FullReorderEngine:
def __init__(self):
self.test_on_barrier = True
"""
Realizes a full reordering of stores within a given list.
Example:
input: (a, b, c)
output:
()
('a',)
('b',)
('c',)
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'c')
('c', 'a')
('c', 'b')
('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
"""
def generate_sequence(self, store_list):
"""
Generates all possible combinations of all possible lengths,
based on the operations in the list.
:param store_list: The list of stores to be reordered.
:type store_list: list of :class:`memoryoperations.Store`
:return: Yields all combinations of stores.
:rtype: iterable
"""
for length in range(0, len(store_list) + 1):
for permutation in permutations(store_list, length):
yield permutation
class AccumulativeReorderEngine:
def __init__(self):
self.test_on_barrier = True
"""
Realizes an accumulative reorder of stores within a given list.
Example:
input: (a, b, c)
output:
()
('a')
('a', 'b')
('a', 'b', 'c')
"""
def generate_sequence(self, store_list):
"""
Generates all accumulative lists,
based on the operations in the store list.
:param store_list: The list of stores to be reordered.
:type store_list: list of :class:`memoryoperations.Store`
:return: Yields all accumulative combinations of stores.
:rtype: iterable
"""
for i in range(0, len(store_list) + 1):
out_list = [store_list[i] for i in range(0, i)]
yield out_list
class AccumulativeReverseReorderEngine:
def __init__(self):
self.test_on_barrier = True
"""
Realizes an accumulative reorder of stores
within a given list in reverse order.
Example:
input: (a, b, c)
output:
()
('c')
('c', 'b')
('c', 'b', 'a')
"""
def generate_sequence(self, store_list):
"""
Reverse all elements order and
generates all accumulative lists.
:param store_list: The list of stores to be reordered.
:type store_list: list of :class:`memoryoperations.Store`
:return: Yields all accumulative combinations of stores.
:rtype: iterable
"""
store_list = list(reversed(store_list))
for i in range(len(store_list) + 1):
yield [store_list[j] for j in range(i)]
class SlicePartialReorderEngine:
"""
Generates a slice of the full reordering of stores within a given list.
Example:
input: (a, b, c), start = 2, stop = None, step = 2
output:
('b')
('a', 'b')
('b', 'c')
"""
def __init__(self, start, stop, step=1):
"""
Initializes the generator with the provided parameters.
:param start: Number of preceding elements to be skipped.
:param stop: The element at which the slice is to stop.
:param step: How many values are skipped between successive calls.
"""
self._start = start
self._stop = stop
self._step = step
self.test_on_barrier = True
def generate_sequence(self, store_list):
"""
This generator yields a slice of all possible combinations.
The result may be a set of combinations of different lengths,
depending on the slice parameters provided at object creation.
:param store_list: The list of stores to be reordered.
:type store_list: list of :class:`memoryoperations.Store`
:return: Yields a slice of all combinations of stores.
:rtype: iterable
"""
for sl in islice(chain(*map(lambda x: combinations(store_list, x),
range(0, len(store_list) + 1))),
self._start, self._stop, self._step):
yield sl
class FilterPartialReorderEngine:
"""
Generates a filtered set of the combinations
without duplication of stores within a given list.
Example:
input: (a, b, c), filter = filter_min_elem, kwarg1 = 2
output:
(a, b)
(a, c)
(b, c)
(a, b, c)
input: (a, b, c), filter = filter_max_elem, kwarg1 = 2
output:
()
(a)
(b)
(c)
(a, b)
(a, c)
(b, c)
input: (a, b, c), filter = filter_between_elem, kwarg1 = 2, kwarg2 = 2
output:
(a, b)
(a, c)
(b, c)
"""
def __init__(self, func, **kwargs):
"""
Initializes the generator with the provided parameters.
:param func: The filter function.
:param **kwargs: Arguments to the filter function.
"""
self._filter = func
self._filter_kwargs = kwargs
self.test_on_barrier = True
@staticmethod
def filter_min_elem(store_list, **kwargs):
"""
Filter stores list if number of element is less than kwarg1
"""
if (len(store_list) < kwargs["kwarg1"]):
return False
return True
@staticmethod
def filter_max_elem(store_list, **kwargs):
"""
Filter stores list if number of element is greater than kwarg1.
"""
if (len(store_list) > kwargs["kwarg1"]):
return False
return True
@staticmethod
def filter_between_elem(store_list, **kwargs):
"""
Filter stores list if number of element is
greater or equal kwarg1 and less or equal kwarg2.
"""
store_len = len(store_list)
if (store_len >= kwargs["kwarg1"] and store_len <= kwargs["kwarg2"]):
return True
return False
def generate_sequence(self, store_list):
"""
This generator yields a filtered set of combinations.
:param store_list: The list of stores to be reordered.
:type store_list: list of :class:`memoryoperations.Store`
:return: Yields a filtered set of combinations.
:rtype: iterable
"""
filter_fun = getattr(self, self._filter, None)
for elem in filter(
partial(filter_fun, **self._filter_kwargs), chain(
*map(lambda x: combinations(store_list, x), range(
0, len(store_list) + 1)))):
yield elem
class RandomPartialReorderEngine:
"""
Generates a random sequence of combinations of stores.
Example:
input: (a, b, c), max_seq = 3
output:
('b', 'c')
('b',)
('a', 'b', 'c')
"""
def __init__(self, max_seq=3):
"""
Initializes the generator with the provided parameters.
:param max_seq: The number of combinations to be generated.
"""
self.test_on_barrier = True
self._max_seq = max_seq
def generate_sequence(self, store_list):
"""
This generator yields a random sequence of combinations.
Number of combinations without replacement has to be limited to
1000 because of exponential growth of elements.
Example:
for 10 element from 80 -> 1646492110120 combinations
for 20 element from 80 -> 3.5353161422122E+18 combinations
for 40 element from 80 -> 1.0750720873334E+23 combinations
:param store_list: The list of stores to be reordered.
:type store_list: list of :class:`memoryoperations.Store`
:return: Yields a random sequence of combinations.
:rtype: iterable
"""
population = list(chain(*map(
lambda x: islice(combinations(store_list, x), 1000),
range(0, len(store_list) + 1))))
population_size = len(population)
for elem in sample(population, self._max_seq if self._max_seq <=
population_size else population_size):
yield elem
class NoReorderEngine:
def __init__(self):
self.test_on_barrier = True
"""
A NULL reorder engine.
Example:
input: (a, b, c)
output: (a, b, c)
"""
def generate_sequence(self, store_list):
"""
This generator does not modify the provided store list.
:param store_list: The list of stores to be reordered.
:type store_list: The list of :class:`memoryoperations.Store`
:return: The unmodified list of stores.
:rtype: iterable
"""
return [store_list]
class NoCheckerEngine:
def __init__(self):
self.test_on_barrier = False
"""
A NULL reorder engine.
Example:
input: (a, b, c)
output: (a, b, c)
"""
def generate_sequence(self, store_list):
"""
This generator does not modify the provided store list
and does not do the check.
:param store_list: The list of stores to be reordered.
:type store_list: The list of :class:`memoryoperations.Store`
:return: The unmodified list of stores.
:rtype: iterable
"""
return [store_list]
def get_engine(engine):
if engine in engines:
reorder_engine = engines[engine]()
else:
raise NotSupportedOperationException(
"Not supported reorder engine: {}"
.format(engine))
return reorder_engine
engines = collections.OrderedDict([
('NoReorderNoCheck', NoCheckerEngine),
('ReorderFull', FullReorderEngine),
('NoReorderDoCheck', NoReorderEngine),
('ReorderAccumulative', AccumulativeReorderEngine),
('ReorderReverseAccumulative', AccumulativeReverseReorderEngine),
('ReorderPartial', RandomPartialReorderEngine)])
| 10,691 | 30.263158 | 78 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/dump.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* create.c -- pmempool create command source file
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <err.h>
#include "common.h"
#include "dump.h"
#include "output.h"
#include "os.h"
#include "libpmemblk.h"
#include "libpmemlog.h"
#define VERBOSE_DEFAULT 1
/*
* pmempool_dump -- context and arguments for dump command
*/
struct pmempool_dump {
char *fname;
char *ofname;
char *range;
FILE *ofh;
int hex;
uint64_t bsize;
struct ranges ranges;
size_t chunksize;
uint64_t chunkcnt;
};
/*
* pmempool_dump_default -- default arguments and context values
*/
static const struct pmempool_dump pmempool_dump_default = {
.fname = NULL,
.ofname = NULL,
.range = NULL,
.ofh = NULL,
.hex = 1,
.bsize = 0,
.chunksize = 0,
.chunkcnt = 0,
};
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"output", required_argument, NULL, 'o' | OPT_ALL},
{"binary", no_argument, NULL, 'b' | OPT_ALL},
{"range", required_argument, NULL, 'r' | OPT_ALL},
{"chunk", required_argument, NULL, 'c' | OPT_LOG},
{"help", no_argument, NULL, 'h' | OPT_ALL},
{NULL, 0, NULL, 0 },
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Dump user data from pool\n"
"\n"
"Available options:\n"
" -o, --output <file> output file name\n"
" -b, --binary dump data in binary format\n"
" -r, --range <range> range of bytes/blocks/data chunks\n"
" -c, --chunk <size> size of chunk for PMEMLOG pool\n"
" -h, --help display this help and exit\n"
"\n"
"For complete documentation see %s-dump(1) manual page.\n"
;
/*
* print_usage -- print application usage short description
*/
static void
print_usage(const char *appname)
{
printf("Usage: %s dump [<args>] <file>\n", appname);
}
/*
* print_version -- print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_dump_help -- print help message for dump command
*/
void
pmempool_dump_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* pmempool_dump_log_process_chunk -- callback for pmemlog_walk
*/
static int
pmempool_dump_log_process_chunk(const void *buf, size_t len, void *arg)
{
struct pmempool_dump *pdp = (struct pmempool_dump *)arg;
if (len == 0)
return 0;
struct range *curp = NULL;
if (pdp->chunksize) {
PMDK_LIST_FOREACH(curp, &pdp->ranges.head, next) {
if (pdp->chunkcnt >= curp->first &&
pdp->chunkcnt <= curp->last &&
pdp->chunksize <= len) {
if (pdp->hex) {
outv_hexdump(VERBOSE_DEFAULT,
buf, pdp->chunksize,
pdp->chunksize * pdp->chunkcnt,
0);
} else {
if (fwrite(buf, pdp->chunksize,
1, pdp->ofh) != 1)
err(1, "%s", pdp->ofname);
}
}
}
pdp->chunkcnt++;
} else {
PMDK_LIST_FOREACH(curp, &pdp->ranges.head, next) {
if (curp->first >= len)
continue;
uint8_t *ptr = (uint8_t *)buf + curp->first;
if (curp->last >= len)
curp->last = len - 1;
uint64_t count = curp->last - curp->first + 1;
if (pdp->hex) {
outv_hexdump(VERBOSE_DEFAULT, ptr,
count, curp->first, 0);
} else {
if (fwrite(ptr, count, 1, pdp->ofh) != 1)
err(1, "%s", pdp->ofname);
}
}
}
return 1;
}
/*
* pmempool_dump_parse_range -- parse range passed by arguments
*/
static int
pmempool_dump_parse_range(struct pmempool_dump *pdp, size_t max)
{
struct range entire;
memset(&entire, 0, sizeof(entire));
entire.last = max;
if (util_parse_ranges(pdp->range, &pdp->ranges, entire)) {
outv_err("invalid range value specified"
" -- '%s'\n", pdp->range);
return -1;
}
if (PMDK_LIST_EMPTY(&pdp->ranges.head))
util_ranges_add(&pdp->ranges, entire);
return 0;
}
/*
* pmempool_dump_log -- dump data from pmem log pool
*/
static int
pmempool_dump_log(struct pmempool_dump *pdp)
{
PMEMlogpool *plp = pmemlog_open(pdp->fname);
if (!plp) {
warn("%s", pdp->fname);
return -1;
}
os_off_t off = pmemlog_tell(plp);
if (off < 0) {
warn("%s", pdp->fname);
pmemlog_close(plp);
return -1;
}
if (off == 0)
goto end;
size_t max = (size_t)off - 1;
if (pdp->chunksize)
max /= pdp->chunksize;
if (pmempool_dump_parse_range(pdp, max))
return -1;
pdp->chunkcnt = 0;
pmemlog_walk(plp, pdp->chunksize, pmempool_dump_log_process_chunk, pdp);
end:
pmemlog_close(plp);
return 0;
}
/*
* pmempool_dump_blk -- dump data from pmem blk pool
*/
static int
pmempool_dump_blk(struct pmempool_dump *pdp)
{
PMEMblkpool *pbp = pmemblk_open(pdp->fname, pdp->bsize);
if (!pbp) {
warn("%s", pdp->fname);
return -1;
}
if (pmempool_dump_parse_range(pdp, pmemblk_nblock(pbp) - 1))
return -1;
uint8_t *buff = malloc(pdp->bsize);
if (!buff)
err(1, "Cannot allocate memory for pmemblk block buffer");
int ret = 0;
uint64_t i;
struct range *curp = NULL;
PMDK_LIST_FOREACH(curp, &pdp->ranges.head, next) {
assert((os_off_t)curp->last >= 0);
for (i = curp->first; i <= curp->last; i++) {
if (pmemblk_read(pbp, buff, (os_off_t)i)) {
ret = -1;
outv_err("reading block number %lu "
"failed\n", i);
break;
}
if (pdp->hex) {
uint64_t offset = i * pdp->bsize;
outv_hexdump(VERBOSE_DEFAULT, buff,
pdp->bsize, offset, 0);
} else {
if (fwrite(buff, pdp->bsize, 1,
pdp->ofh) != 1) {
warn("write");
ret = -1;
break;
}
}
}
}
free(buff);
pmemblk_close(pbp);
return ret;
}
static const struct option_requirement option_requirements[] = {
{ 0, 0, 0}
};
/*
* pmempool_dump_func -- dump command main function
*/
int
pmempool_dump_func(const char *appname, int argc, char *argv[])
{
struct pmempool_dump pd = pmempool_dump_default;
PMDK_LIST_INIT(&pd.ranges.head);
out_set_vlevel(VERBOSE_DEFAULT);
struct options *opts = util_options_alloc(long_options,
sizeof(long_options) / sizeof(long_options[0]),
option_requirements);
int ret = 0;
long long chunksize;
int opt;
while ((opt = util_options_getopt(argc, argv,
"ho:br:c:", opts)) != -1) {
switch (opt) {
case 'o':
pd.ofname = optarg;
break;
case 'b':
pd.hex = 0;
break;
case 'r':
pd.range = optarg;
break;
case 'c':
chunksize = atoll(optarg);
if (chunksize <= 0) {
outv_err("invalid chunk size specified '%s'\n",
optarg);
exit(EXIT_FAILURE);
}
pd.chunksize = (size_t)chunksize;
break;
case 'h':
pmempool_dump_help(appname);
exit(EXIT_SUCCESS);
default:
print_usage(appname);
exit(EXIT_FAILURE);
}
}
if (optind < argc) {
pd.fname = argv[optind];
} else {
print_usage(appname);
exit(EXIT_FAILURE);
}
if (pd.ofname == NULL) {
/* use standard output by default */
pd.ofh = stdout;
} else {
pd.ofh = os_fopen(pd.ofname, "wb");
if (!pd.ofh) {
warn("%s", pd.ofname);
exit(EXIT_FAILURE);
}
}
/* set output stream - stdout or file passed by -o option */
out_set_stream(pd.ofh);
struct pmem_pool_params params;
/* parse pool type and block size for pmem blk pool */
pmem_pool_parse_params(pd.fname, ¶ms, 1);
ret = util_options_verify(opts, params.type);
if (ret)
goto out;
switch (params.type) {
case PMEM_POOL_TYPE_LOG:
ret = pmempool_dump_log(&pd);
break;
case PMEM_POOL_TYPE_BLK:
pd.bsize = params.blk.bsize;
ret = pmempool_dump_blk(&pd);
break;
case PMEM_POOL_TYPE_OBJ:
outv_err("%s: PMEMOBJ pool not supported\n", pd.fname);
ret = -1;
goto out;
case PMEM_POOL_TYPE_UNKNOWN:
outv_err("%s: unknown pool type -- '%s'\n", pd.fname,
params.signature);
ret = -1;
goto out;
default:
outv_err("%s: cannot determine type of pool\n", pd.fname);
ret = -1;
goto out;
}
if (ret)
outv_err("%s: dumping pool file failed\n", pd.fname);
out:
if (pd.ofh != stdout)
fclose(pd.ofh);
util_ranges_clear(&pd.ranges);
util_options_free(opts);
return ret;
}
| 8,081 | 19.617347 | 73 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/check.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* check.h -- pmempool check command header file
*/
int pmempool_check_func(const char *appname, int argc, char *argv[]);
void pmempool_check_help(const char *appname);
| 261 | 25.2 | 69 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/create.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* create.c -- pmempool create command source file
*/
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <errno.h>
#include <libgen.h>
#include <err.h>
#include "common.h"
#include "file.h"
#include "create.h"
#include "os.h"
#include "set.h"
#include "output.h"
#include "libpmemblk.h"
#include "libpmemlog.h"
#include "libpmempool.h"
#define DEFAULT_MODE 0664
/*
* pmempool_create -- context and args for create command
*/
struct pmempool_create {
int verbose;
char *fname;
int fexists;
char *inherit_fname;
int max_size;
char *str_type;
struct pmem_pool_params params;
struct pmem_pool_params inherit_params;
char *str_size;
char *str_mode;
char *str_bsize;
uint64_t csize;
int write_btt_layout;
int force;
char *layout;
struct options *opts;
int clearbadblocks;
};
/*
* pmempool_create_default -- default args for create command
*/
static const struct pmempool_create pmempool_create_default = {
.verbose = 0,
.fname = NULL,
.fexists = 0,
.inherit_fname = NULL,
.max_size = 0,
.str_type = NULL,
.str_bsize = NULL,
.csize = 0,
.write_btt_layout = 0,
.force = 0,
.layout = NULL,
.clearbadblocks = 0,
.params = {
.type = PMEM_POOL_TYPE_UNKNOWN,
.size = 0,
.mode = DEFAULT_MODE,
}
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Create pmem pool of specified size, type and name\n"
"\n"
"Common options:\n"
" -s, --size <size> size of pool\n"
" -M, --max-size use maximum available space on file system\n"
" -m, --mode <octal> set permissions to <octal> (the default is 0664)\n"
" -i, --inherit <file> take required parameters from specified pool file\n"
" -b, --clear-bad-blocks clear bad blocks in existing files\n"
" -f, --force remove the pool first\n"
" -v, --verbose increase verbosity level\n"
" -h, --help display this help and exit\n"
"\n"
"Options for PMEMBLK:\n"
" -w, --write-layout force writing the BTT layout\n"
"\n"
"Options for PMEMOBJ:\n"
" -l, --layout <name> layout name stored in pool's header\n"
"\n"
"For complete documentation see %s-create(1) manual page.\n"
;
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"size", required_argument, NULL, 's' | OPT_ALL},
{"verbose", no_argument, NULL, 'v' | OPT_ALL},
{"help", no_argument, NULL, 'h' | OPT_ALL},
{"max-size", no_argument, NULL, 'M' | OPT_ALL},
{"inherit", required_argument, NULL, 'i' | OPT_ALL},
{"mode", required_argument, NULL, 'm' | OPT_ALL},
{"write-layout", no_argument, NULL, 'w' | OPT_BLK},
{"layout", required_argument, NULL, 'l' | OPT_OBJ},
{"force", no_argument, NULL, 'f' | OPT_ALL},
{"clear-bad-blocks", no_argument, NULL, 'b' | OPT_ALL},
{NULL, 0, NULL, 0 },
};
/*
* print_usage -- print application usage short description
*/
static void
print_usage(const char *appname)
{
printf("Usage: %s create [<args>] <blk|log|obj> [<bsize>] <file>\n",
appname);
}
/*
* print_version -- print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_create_help -- print help message for create command
*/
void
pmempool_create_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* pmempool_create_obj -- create pmem obj pool
*/
static int
pmempool_create_obj(struct pmempool_create *pcp)
{
PMEMobjpool *pop = pmemobj_create(pcp->fname, pcp->layout,
pcp->params.size, pcp->params.mode);
if (!pop) {
outv_err("'%s' -- %s\n", pcp->fname, pmemobj_errormsg());
return -1;
}
pmemobj_close(pop);
return 0;
}
/*
* pmempool_create_blk -- create pmem blk pool
*/
static int
pmempool_create_blk(struct pmempool_create *pcp)
{
ASSERTne(pcp->params.blk.bsize, 0);
int ret = 0;
PMEMblkpool *pbp = pmemblk_create(pcp->fname, pcp->params.blk.bsize,
pcp->params.size, pcp->params.mode);
if (!pbp) {
outv_err("'%s' -- %s\n", pcp->fname, pmemblk_errormsg());
return -1;
}
if (pcp->write_btt_layout) {
outv(1, "Writing BTT layout using block %d.\n",
pcp->write_btt_layout);
if (pmemblk_set_error(pbp, 0) || pmemblk_set_zero(pbp, 0)) {
outv_err("writing BTT layout to block 0 failed\n");
ret = -1;
}
}
pmemblk_close(pbp);
return ret;
}
/*
* pmempool_create_log -- create pmem log pool
*/
static int
pmempool_create_log(struct pmempool_create *pcp)
{
PMEMlogpool *plp = pmemlog_create(pcp->fname,
pcp->params.size, pcp->params.mode);
if (!plp) {
outv_err("'%s' -- %s\n", pcp->fname, pmemlog_errormsg());
return -1;
}
pmemlog_close(plp);
return 0;
}
/*
* pmempool_get_max_size -- return maximum allowed size of file
*/
#ifndef _WIN32
static int
pmempool_get_max_size(const char *fname, uint64_t *sizep)
{
struct statvfs buf;
int ret = 0;
char *name = strdup(fname);
if (name == NULL) {
return -1;
}
char *dir = dirname(name);
if (statvfs(dir, &buf))
ret = -1;
else
*sizep = buf.f_bsize * buf.f_bavail;
free(name);
return ret;
}
#else
static int
pmempool_get_max_size(const char *fname, uint64_t *sizep)
{
int ret = 0;
ULARGE_INTEGER freespace;
char *name = strdup(fname);
if (name == NULL) {
return -1;
}
char *dir = dirname(name);
wchar_t *str = util_toUTF16(dir);
if (str == NULL) {
free(name);
return -1;
}
if (GetDiskFreeSpaceExW(str, &freespace, NULL, NULL) == 0)
ret = -1;
else
*sizep = freespace.QuadPart;
free(str);
free(name);
return ret;
}
#endif
/*
* print_pool_params -- print some parameters of a pool
*/
static void
print_pool_params(struct pmem_pool_params *params)
{
outv(1, "\ttype : %s\n", out_get_pool_type_str(params->type));
outv(1, "\tsize : %s\n", out_get_size_str(params->size, 2));
outv(1, "\tmode : 0%o\n", params->mode);
switch (params->type) {
case PMEM_POOL_TYPE_BLK:
outv(1, "\tbsize : %s\n",
out_get_size_str(params->blk.bsize, 0));
break;
case PMEM_POOL_TYPE_OBJ:
outv(1, "\tlayout: '%s'\n", params->obj.layout);
break;
default:
break;
}
}
/*
* inherit_pool_params -- inherit pool parameters from specified file
*/
static int
inherit_pool_params(struct pmempool_create *pcp)
{
outv(1, "Parsing pool: '%s'\n", pcp->inherit_fname);
/*
* If no type string passed, --inherit option must be passed
* so parse file and get required parameters.
*/
if (pmem_pool_parse_params(pcp->inherit_fname,
&pcp->inherit_params, 1)) {
if (errno)
perror(pcp->inherit_fname);
else
outv_err("%s: cannot determine type of pool\n",
pcp->inherit_fname);
return -1;
}
if (PMEM_POOL_TYPE_UNKNOWN == pcp->inherit_params.type) {
outv_err("'%s' -- unknown pool type\n",
pcp->inherit_fname);
return -1;
}
print_pool_params(&pcp->inherit_params);
return 0;
}
/*
* pmempool_create_parse_args -- parse command line args
*/
static int
pmempool_create_parse_args(struct pmempool_create *pcp, const char *appname,
int argc, char *argv[], struct options *opts)
{
int opt, ret;
while ((opt = util_options_getopt(argc, argv, "vhi:s:Mm:l:wfb",
opts)) != -1) {
switch (opt) {
case 'v':
pcp->verbose = 1;
break;
case 'h':
pmempool_create_help(appname);
exit(EXIT_SUCCESS);
case 's':
pcp->str_size = optarg;
ret = util_parse_size(optarg,
(size_t *)&pcp->params.size);
if (ret || pcp->params.size == 0) {
outv_err("invalid size value specified '%s'\n",
optarg);
return -1;
}
break;
case 'M':
pcp->max_size = 1;
break;
case 'm':
pcp->str_mode = optarg;
if (util_parse_mode(optarg, &pcp->params.mode)) {
outv_err("invalid mode value specified '%s'\n",
optarg);
return -1;
}
break;
case 'i':
pcp->inherit_fname = optarg;
break;
case 'w':
pcp->write_btt_layout = 1;
break;
case 'l':
pcp->layout = optarg;
break;
case 'f':
pcp->force = 1;
break;
case 'b':
pcp->clearbadblocks = 1;
break;
default:
print_usage(appname);
return -1;
}
}
/* check for <type>, <bsize> and <file> strings */
if (optind + 2 < argc) {
pcp->str_type = argv[optind];
pcp->str_bsize = argv[optind + 1];
pcp->fname = argv[optind + 2];
} else if (optind + 1 < argc) {
pcp->str_type = argv[optind];
pcp->fname = argv[optind + 1];
} else if (optind < argc) {
pcp->fname = argv[optind];
pcp->str_type = NULL;
} else {
print_usage(appname);
return -1;
}
return 0;
}
static int
allocate_max_size_available_file(const char *name_of_file, mode_t mode,
os_off_t max_size)
{
int fd = os_open(name_of_file, O_CREAT | O_EXCL | O_RDWR, mode);
if (fd == -1) {
outv_err("!open '%s' failed", name_of_file);
return -1;
}
os_off_t offset = 0;
os_off_t length = max_size - (max_size % (os_off_t)Pagesize);
int ret;
do {
ret = os_posix_fallocate(fd, offset, length);
if (ret == 0)
offset += length;
else if (ret != ENOSPC) {
os_close(fd);
if (os_unlink(name_of_file) == -1)
outv_err("!unlink '%s' failed", name_of_file);
errno = ret;
outv_err("!space allocation for '%s' failed",
name_of_file);
return -1;
}
length /= 2;
length -= (length % (os_off_t)Pagesize);
} while (length > (os_off_t)Pagesize);
os_close(fd);
return 0;
}
/*
* pmempool_create_func -- main function for create command
*/
int
pmempool_create_func(const char *appname, int argc, char *argv[])
{
int ret = 0;
struct pmempool_create pc = pmempool_create_default;
pc.opts = util_options_alloc(long_options, sizeof(long_options) /
sizeof(long_options[0]), NULL);
/* parse command line arguments */
ret = pmempool_create_parse_args(&pc, appname, argc, argv, pc.opts);
if (ret)
exit(EXIT_FAILURE);
/* set verbosity level */
out_set_vlevel(pc.verbose);
umask(0);
int exists = util_file_exists(pc.fname);
if (exists < 0)
return -1;
pc.fexists = exists;
int is_poolset = util_is_poolset_file(pc.fname) == 1;
if (pc.inherit_fname) {
if (inherit_pool_params(&pc)) {
outv_err("parsing pool '%s' failed\n",
pc.inherit_fname);
return -1;
}
}
/*
* Parse pool type and other parameters if --inherit option
* passed. It is possible to either pass --inherit option
* or pool type string in command line arguments. This is
* validated here.
*/
if (pc.str_type) {
/* parse pool type string if passed in command line arguments */
pc.params.type = pmem_pool_type_parse_str(pc.str_type);
if (PMEM_POOL_TYPE_UNKNOWN == pc.params.type) {
outv_err("'%s' -- unknown pool type\n", pc.str_type);
return -1;
}
if (PMEM_POOL_TYPE_BLK == pc.params.type) {
if (pc.str_bsize == NULL) {
outv_err("blk pool requires <bsize> "
"argument\n");
return -1;
}
if (util_parse_size(pc.str_bsize,
(size_t *)&pc.params.blk.bsize)) {
outv_err("cannot parse '%s' as block size\n",
pc.str_bsize);
return -1;
}
}
if (PMEM_POOL_TYPE_OBJ == pc.params.type && pc.layout != NULL) {
size_t max_layout = PMEMOBJ_MAX_LAYOUT;
if (strlen(pc.layout) >= max_layout) {
outv_err(
"Layout name is too long, maximum number of characters (including the terminating null byte) is %zu\n",
max_layout);
return -1;
}
size_t len = sizeof(pc.params.obj.layout);
strncpy(pc.params.obj.layout, pc.layout, len);
pc.params.obj.layout[len - 1] = '\0';
}
} else if (pc.inherit_fname) {
pc.params.type = pc.inherit_params.type;
} else {
/* neither pool type string nor --inherit options passed */
print_usage(appname);
return -1;
}
if (util_options_verify(pc.opts, pc.params.type))
return -1;
if (pc.params.type != PMEM_POOL_TYPE_BLK && pc.str_bsize != NULL) {
outv_err("invalid option specified for %s pool type"
" -- block size\n",
out_get_pool_type_str(pc.params.type));
return -1;
}
if (is_poolset) {
if (pc.params.size) {
outv_err("-s|--size cannot be used with "
"poolset file\n");
return -1;
}
if (pc.max_size) {
outv_err("-M|--max-size cannot be used with "
"poolset file\n");
return -1;
}
}
if (pc.params.size && pc.max_size) {
outv_err("-M|--max-size option cannot be used with -s|--size"
" option\n");
return -1;
}
if (pc.inherit_fname) {
if (!pc.str_size && !pc.max_size)
pc.params.size = pc.inherit_params.size;
if (!pc.str_mode)
pc.params.mode = pc.inherit_params.mode;
switch (pc.params.type) {
case PMEM_POOL_TYPE_BLK:
if (!pc.str_bsize)
pc.params.blk.bsize =
pc.inherit_params.blk.bsize;
break;
case PMEM_POOL_TYPE_OBJ:
if (!pc.layout) {
memcpy(pc.params.obj.layout,
pc.inherit_params.obj.layout,
sizeof(pc.params.obj.layout));
} else {
size_t len = sizeof(pc.params.obj.layout);
strncpy(pc.params.obj.layout, pc.layout,
len - 1);
pc.params.obj.layout[len - 1] = '\0';
}
break;
default:
break;
}
}
/*
* If neither --size nor --inherit options passed, check
* for --max-size option - if not passed use minimum pool size.
*/
uint64_t min_size = pmem_pool_get_min_size(pc.params.type);
if (pc.params.size == 0) {
if (pc.max_size) {
outv(1, "Maximum size option passed "
"- getting available space of file system.\n");
ret = pmempool_get_max_size(pc.fname,
&pc.params.size);
if (ret) {
outv_err("cannot get available space of fs\n");
return -1;
}
if (pc.params.size == 0) {
outv_err("No space left on device\n");
return -1;
}
outv(1, "Available space is %s\n",
out_get_size_str(pc.params.size, 2));
if (allocate_max_size_available_file(pc.fname,
pc.params.mode,
(os_off_t)pc.params.size))
return -1;
/*
* We are going to create pool based
* on file size instead of the pc.params.size.
*/
pc.params.size = 0;
} else {
if (!pc.fexists) {
outv(1, "No size option passed "
"- picking minimum pool size.\n");
pc.params.size = min_size;
}
}
} else {
if (pc.params.size < min_size) {
outv_err("size must be >= %lu bytes\n", min_size);
return -1;
}
}
if (pc.force)
pmempool_rm(pc.fname, PMEMPOOL_RM_FORCE);
outv(1, "Creating pool: %s\n", pc.fname);
print_pool_params(&pc.params);
if (pc.clearbadblocks) {
int ret = util_pool_clear_badblocks(pc.fname,
1 /* ignore non-existing */);
if (ret) {
outv_err("'%s' -- clearing bad blocks failed\n",
pc.fname);
return -1;
}
}
switch (pc.params.type) {
case PMEM_POOL_TYPE_BLK:
ret = pmempool_create_blk(&pc);
break;
case PMEM_POOL_TYPE_LOG:
ret = pmempool_create_log(&pc);
break;
case PMEM_POOL_TYPE_OBJ:
ret = pmempool_create_obj(&pc);
break;
default:
ret = -1;
break;
}
if (ret) {
outv_err("creating pool file failed\n");
if (!pc.fexists)
util_unlink(pc.fname);
}
util_options_free(pc.opts);
return ret;
}
| 14,987 | 21.403587 | 109 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/transform.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* transform.c -- pmempool transform command source file
*/
#include <stdio.h>
#include <libgen.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdbool.h>
#include <sys/mman.h>
#include <endian.h>
#include "common.h"
#include "output.h"
#include "transform.h"
#include "libpmempool.h"
/*
* pmempool_transform_context -- context and arguments for transform command
*/
struct pmempool_transform_context {
unsigned flags; /* flags which modify the command execution */
char *poolset_file_src; /* a path to a source poolset file */
char *poolset_file_dst; /* a path to a target poolset file */
};
/*
* pmempool_transform_default -- default arguments for transform command
*/
static const struct pmempool_transform_context pmempool_transform_default = {
.flags = 0,
.poolset_file_src = NULL,
.poolset_file_dst = NULL,
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Modify internal structure of a poolset\n"
"\n"
"Common options:\n"
" -d, --dry-run do not apply changes, only check for viability of"
" transformation\n"
" -v, --verbose increase verbosity level\n"
" -h, --help display this help and exit\n"
"\n"
"For complete documentation see %s-transform(1) manual page.\n"
;
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"dry-run", no_argument, NULL, 'd'},
{"help", no_argument, NULL, 'h'},
{"verbose", no_argument, NULL, 'v'},
{NULL, 0, NULL, 0 },
};
/*
* print_usage -- print application usage short description
*/
static void
print_usage(const char *appname)
{
printf("usage: %s transform [<options>] <poolset_file_src>"
" <poolset_file_dst>\n", appname);
}
/*
* print_version -- print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_transform_help -- print help message for the transform command
*/
void
pmempool_transform_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* pmempool_check_parse_args -- parse command line arguments
*/
static int
pmempool_transform_parse_args(struct pmempool_transform_context *ctx,
const char *appname, int argc, char *argv[])
{
int opt;
while ((opt = getopt_long(argc, argv, "dhv",
long_options, NULL)) != -1) {
switch (opt) {
case 'd':
ctx->flags = PMEMPOOL_TRANSFORM_DRY_RUN;
break;
case 'h':
pmempool_transform_help(appname);
exit(EXIT_SUCCESS);
case 'v':
out_set_vlevel(1);
break;
default:
print_usage(appname);
exit(EXIT_FAILURE);
}
}
if (optind + 1 < argc) {
ctx->poolset_file_src = argv[optind];
ctx->poolset_file_dst = argv[optind + 1];
} else {
print_usage(appname);
exit(EXIT_FAILURE);
}
return 0;
}
/*
* pmempool_transform_func -- main function for the transform command
*/
int
pmempool_transform_func(const char *appname, int argc, char *argv[])
{
int ret;
struct pmempool_transform_context ctx = pmempool_transform_default;
/* parse command line arguments */
if ((ret = pmempool_transform_parse_args(&ctx, appname, argc, argv)))
return ret;
ret = pmempool_transform(ctx.poolset_file_src, ctx.poolset_file_dst,
ctx.flags);
if (ret) {
if (errno)
outv_err("%s\n", strerror(errno));
outv_err("failed to transform %s -> %s: %s\n",
ctx.poolset_file_src, ctx.poolset_file_dst,
pmempool_errormsg());
return -1;
} else {
outv(1, "%s -> %s: transformed\n", ctx.poolset_file_src,
ctx.poolset_file_dst);
return 0;
}
}
| 3,689 | 21.919255 | 77 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/info_blk.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* Copyright (c) 2016, Microsoft Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* info_blk.c -- pmempool info command source file for blk pool
*/
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
#include <sys/param.h>
#include <endian.h>
#include "os.h"
#include "common.h"
#include "output.h"
#include "info.h"
#include "btt.h"
/*
* pmempool_info_get_range -- get blocks/data chunk range
*
* Get range based on command line arguments and maximum value.
* Return value:
* 0 - range is empty
* 1 - range is not empty
*/
static int
pmempool_info_get_range(struct pmem_info *pip, struct range *rangep,
struct range *curp, uint32_t max, uint64_t offset)
{
/* not using range */
if (!pip->args.use_range) {
rangep->first = 0;
rangep->last = max;
return 1;
}
if (curp->first > offset + max)
return 0;
if (curp->first >= offset)
rangep->first = curp->first - offset;
else
rangep->first = 0;
if (curp->last < offset)
return 0;
if (curp->last <= offset + max)
rangep->last = curp->last - offset;
else
rangep->last = max;
return 1;
}
/*
* info_blk_skip_block -- get action type for block/data chunk
*
* Return value indicating whether processing block/data chunk
* should be skipped.
*
* Return values:
* 0 - continue processing
* 1 - skip current block
*/
static int
info_blk_skip_block(struct pmem_info *pip, int is_zero,
int is_error)
{
if (pip->args.blk.skip_no_flag && !is_zero && !is_error)
return 1;
if (is_zero && pip->args.blk.skip_zeros)
return 1;
if (is_error && pip->args.blk.skip_error)
return 1;
return 0;
}
/*
* info_btt_data -- print block data and corresponding flags from map
*/
static int
info_btt_data(struct pmem_info *pip, int v, struct btt_info *infop,
uint64_t arena_off, uint64_t offset, uint64_t *countp)
{
if (!outv_check(v))
return 0;
int ret = 0;
size_t mapsize = infop->external_nlba * BTT_MAP_ENTRY_SIZE;
uint32_t *map = malloc(mapsize);
if (!map)
err(1, "Cannot allocate memory for BTT map");
uint8_t *block_buff = malloc(infop->external_lbasize);
if (!block_buff)
err(1, "Cannot allocate memory for pmemblk block buffer");
/* read btt map area */
if (pmempool_info_read(pip, (uint8_t *)map, mapsize,
arena_off + infop->mapoff)) {
outv_err("wrong BTT Map size or offset\n");
ret = -1;
goto error;
}
uint64_t i;
struct range *curp = NULL;
struct range range;
FOREACH_RANGE(curp, &pip->args.ranges) {
if (pmempool_info_get_range(pip, &range, curp,
infop->external_nlba - 1, offset) == 0)
continue;
for (i = range.first; i <= range.last; i++) {
uint32_t map_entry = le32toh(map[i]);
int is_init = (map_entry & ~BTT_MAP_ENTRY_LBA_MASK)
== 0;
int is_zero = (map_entry & ~BTT_MAP_ENTRY_LBA_MASK)
== BTT_MAP_ENTRY_ZERO || is_init;
int is_error = (map_entry & ~BTT_MAP_ENTRY_LBA_MASK)
== BTT_MAP_ENTRY_ERROR;
uint64_t blockno = is_init ? i :
map_entry & BTT_MAP_ENTRY_LBA_MASK;
if (info_blk_skip_block(pip,
is_zero, is_error))
continue;
/* compute block's data address */
uint64_t block_off = arena_off + infop->dataoff +
blockno * infop->internal_lbasize;
if (pmempool_info_read(pip, block_buff,
infop->external_lbasize, block_off)) {
outv_err("cannot read %lu block\n", i);
ret = -1;
goto error;
}
if (*countp == 0)
outv_title(v, "PMEM BLK blocks data");
/*
* Print block number, offset and flags
* from map entry.
*/
outv(v, "Block %10lu: offset: %s\n",
offset + i,
out_get_btt_map_entry(map_entry));
/* dump block's data */
outv_hexdump(v, block_buff, infop->external_lbasize,
block_off, 1);
*countp = *countp + 1;
}
}
error:
free(map);
free(block_buff);
return ret;
}
/*
* info_btt_map -- print all map entries
*/
static int
info_btt_map(struct pmem_info *pip, int v,
struct btt_info *infop, uint64_t arena_off,
uint64_t offset, uint64_t *count)
{
if (!outv_check(v) && !outv_check(pip->args.vstats))
return 0;
int ret = 0;
size_t mapsize = infop->external_nlba * BTT_MAP_ENTRY_SIZE;
uint32_t *map = malloc(mapsize);
if (!map)
err(1, "Cannot allocate memory for BTT map");
/* read btt map area */
if (pmempool_info_read(pip, (uint8_t *)map, mapsize,
arena_off + infop->mapoff)) {
outv_err("wrong BTT Map size or offset\n");
ret = -1;
goto error;
}
uint32_t arena_count = 0;
uint64_t i;
struct range *curp = NULL;
struct range range;
FOREACH_RANGE(curp, &pip->args.ranges) {
if (pmempool_info_get_range(pip, &range, curp,
infop->external_nlba - 1, offset) == 0)
continue;
for (i = range.first; i <= range.last; i++) {
uint32_t entry = le32toh(map[i]);
int is_zero = (entry & ~BTT_MAP_ENTRY_LBA_MASK) ==
BTT_MAP_ENTRY_ZERO ||
(entry & ~BTT_MAP_ENTRY_LBA_MASK) == 0;
int is_error = (entry & ~BTT_MAP_ENTRY_LBA_MASK) ==
BTT_MAP_ENTRY_ERROR;
if (info_blk_skip_block(pip,
is_zero, is_error) == 0) {
if (arena_count == 0)
outv_title(v, "PMEM BLK BTT Map");
if (is_zero)
pip->blk.stats.zeros++;
if (is_error)
pip->blk.stats.errors++;
if (!is_zero && !is_error)
pip->blk.stats.noflag++;
pip->blk.stats.total++;
arena_count++;
(*count)++;
outv(v, "%010lu: %s\n", offset + i,
out_get_btt_map_entry(entry));
}
}
}
error:
free(map);
return ret;
}
/*
* info_btt_flog -- print all flog entries
*/
static int
info_btt_flog(struct pmem_info *pip, int v,
struct btt_info *infop, uint64_t arena_off)
{
if (!outv_check(v))
return 0;
int ret = 0;
struct btt_flog *flogp = NULL;
struct btt_flog *flogpp = NULL;
uint64_t flog_size = infop->nfree *
roundup(2 * sizeof(struct btt_flog), BTT_FLOG_PAIR_ALIGN);
flog_size = roundup(flog_size, BTT_ALIGNMENT);
uint8_t *buff = malloc(flog_size);
if (!buff)
err(1, "Cannot allocate memory for FLOG entries");
if (pmempool_info_read(pip, buff, flog_size,
arena_off + infop->flogoff)) {
outv_err("cannot read BTT FLOG");
ret = -1;
goto error;
}
outv_title(v, "PMEM BLK BTT FLOG");
uint8_t *ptr = buff;
uint32_t i;
for (i = 0; i < infop->nfree; i++) {
flogp = (struct btt_flog *)ptr;
flogpp = flogp + 1;
btt_flog_convert2h(flogp);
btt_flog_convert2h(flogpp);
outv(v, "%010d:\n", i);
outv_field(v, "LBA", "0x%08x", flogp->lba);
outv_field(v, "Old map", "0x%08x: %s", flogp->old_map,
out_get_btt_map_entry(flogp->old_map));
outv_field(v, "New map", "0x%08x: %s", flogp->new_map,
out_get_btt_map_entry(flogp->new_map));
outv_field(v, "Seq", "0x%x", flogp->seq);
outv_field(v, "LBA'", "0x%08x", flogpp->lba);
outv_field(v, "Old map'", "0x%08x: %s", flogpp->old_map,
out_get_btt_map_entry(flogpp->old_map));
outv_field(v, "New map'", "0x%08x: %s", flogpp->new_map,
out_get_btt_map_entry(flogpp->new_map));
outv_field(v, "Seq'", "0x%x", flogpp->seq);
ptr += BTT_FLOG_PAIR_ALIGN;
}
error:
free(buff);
return ret;
}
/*
* info_btt_stats -- print btt related statistics
*/
static void
info_btt_stats(struct pmem_info *pip, int v)
{
if (pip->blk.stats.total > 0) {
outv_title(v, "PMEM BLK Statistics");
double perc_zeros = (double)pip->blk.stats.zeros /
(double)pip->blk.stats.total * 100.0;
double perc_errors = (double)pip->blk.stats.errors /
(double)pip->blk.stats.total * 100.0;
double perc_noflag = (double)pip->blk.stats.noflag /
(double)pip->blk.stats.total * 100.0;
outv_field(v, "Total blocks", "%u", pip->blk.stats.total);
outv_field(v, "Zeroed blocks", "%u [%s]", pip->blk.stats.zeros,
out_get_percentage(perc_zeros));
outv_field(v, "Error blocks", "%u [%s]", pip->blk.stats.errors,
out_get_percentage(perc_errors));
outv_field(v, "Blocks without flag", "%u [%s]",
pip->blk.stats.noflag,
out_get_percentage(perc_noflag));
}
}
/*
* info_btt_info -- print btt_info structure fields
*/
static int
info_btt_info(struct pmem_info *pip, int v, struct btt_info *infop)
{
outv_field(v, "Signature", "%.*s", BTTINFO_SIG_LEN, infop->sig);
outv_field(v, "UUID of container", "%s",
out_get_uuid_str(infop->parent_uuid));
outv_field(v, "Flags", "0x%x", infop->flags);
outv_field(v, "Major", "%d", infop->major);
outv_field(v, "Minor", "%d", infop->minor);
outv_field(v, "External LBA size", "%s",
out_get_size_str(infop->external_lbasize,
pip->args.human));
outv_field(v, "External LBA count", "%u", infop->external_nlba);
outv_field(v, "Internal LBA size", "%s",
out_get_size_str(infop->internal_lbasize,
pip->args.human));
outv_field(v, "Internal LBA count", "%u", infop->internal_nlba);
outv_field(v, "Free blocks", "%u", infop->nfree);
outv_field(v, "Info block size", "%s",
out_get_size_str(infop->infosize, pip->args.human));
outv_field(v, "Next arena offset", "0x%lx", infop->nextoff);
outv_field(v, "Arena data offset", "0x%lx", infop->dataoff);
outv_field(v, "Area map offset", "0x%lx", infop->mapoff);
outv_field(v, "Area flog offset", "0x%lx", infop->flogoff);
outv_field(v, "Info block backup offset", "0x%lx", infop->infooff);
outv_field(v, "Checksum", "%s", out_get_checksum(infop,
sizeof(*infop), &infop->checksum, 0));
return 0;
}
/*
* info_btt_layout -- print information about BTT layout
*/
static int
info_btt_layout(struct pmem_info *pip, os_off_t btt_off)
{
int ret = 0;
if (btt_off <= 0) {
outv_err("wrong BTT layout offset\n");
return -1;
}
struct btt_info *infop = NULL;
infop = malloc(sizeof(struct btt_info));
if (!infop)
err(1, "Cannot allocate memory for BTT Info structure");
int narena = 0;
uint64_t cur_lba = 0;
uint64_t count_data = 0;
uint64_t count_map = 0;
uint64_t offset = (uint64_t)btt_off;
uint64_t nextoff = 0;
do {
/* read btt info area */
if (pmempool_info_read(pip, infop, sizeof(*infop), offset)) {
ret = -1;
outv_err("cannot read BTT Info header\n");
goto err;
}
if (util_check_memory((uint8_t *)infop,
sizeof(*infop), 0) == 0) {
outv(1, "\n<No BTT layout>\n");
break;
}
outv(1, "\n[ARENA %d]", narena);
outv_title(1, "PMEM BLK BTT Info Header");
outv_hexdump(pip->args.vhdrdump, infop,
sizeof(*infop), offset, 1);
btt_info_convert2h(infop);
nextoff = infop->nextoff;
/* print btt info fields */
if (info_btt_info(pip, 1, infop)) {
ret = -1;
goto err;
}
/* dump blocks data */
if (info_btt_data(pip, pip->args.vdata,
infop, offset, cur_lba, &count_data)) {
ret = -1;
goto err;
}
/* print btt map entries and get statistics */
if (info_btt_map(pip, pip->args.blk.vmap, infop,
offset, cur_lba, &count_map)) {
ret = -1;
goto err;
}
/* print flog entries */
if (info_btt_flog(pip, pip->args.blk.vflog, infop,
offset)) {
ret = -1;
goto err;
}
/* increment LBA's counter before reading info backup */
cur_lba += infop->external_nlba;
/* read btt info backup area */
if (pmempool_info_read(pip, infop, sizeof(*infop),
offset + infop->infooff)) {
outv_err("wrong BTT Info Backup size or offset\n");
ret = -1;
goto err;
}
outv_title(pip->args.blk.vbackup,
"PMEM BLK BTT Info Header Backup");
if (outv_check(pip->args.blk.vbackup))
outv_hexdump(pip->args.vhdrdump, infop,
sizeof(*infop),
offset + infop->infooff, 1);
btt_info_convert2h(infop);
info_btt_info(pip, pip->args.blk.vbackup, infop);
offset += nextoff;
narena++;
} while (nextoff > 0);
info_btt_stats(pip, pip->args.vstats);
err:
if (infop)
free(infop);
return ret;
}
/*
* info_blk_descriptor -- print pmemblk descriptor
*/
static void
info_blk_descriptor(struct pmem_info *pip, int v, struct pmemblk *pbp)
{
size_t pmemblk_size;
#ifdef DEBUG
pmemblk_size = offsetof(struct pmemblk, write_lock);
#else
pmemblk_size = sizeof(*pbp);
#endif
outv_title(v, "PMEM BLK Header");
/* dump pmemblk header without pool_hdr */
outv_hexdump(pip->args.vhdrdump, (uint8_t *)pbp + sizeof(pbp->hdr),
pmemblk_size - sizeof(pbp->hdr), sizeof(pbp->hdr), 1);
outv_field(v, "Block size", "%s",
out_get_size_str(pbp->bsize, pip->args.human));
outv_field(v, "Is zeroed", pbp->is_zeroed ? "true" : "false");
}
/*
* pmempool_info_blk -- print information about block type pool
*/
int
pmempool_info_blk(struct pmem_info *pip)
{
int ret;
struct pmemblk *pbp = malloc(sizeof(struct pmemblk));
if (!pbp)
err(1, "Cannot allocate memory for pmemblk structure");
if (pmempool_info_read(pip, pbp, sizeof(struct pmemblk), 0)) {
outv_err("cannot read pmemblk header\n");
free(pbp);
return -1;
}
info_blk_descriptor(pip, VERBOSE_DEFAULT, pbp);
ssize_t btt_off = (char *)pbp->data - (char *)pbp->addr;
ret = info_btt_layout(pip, btt_off);
free(pbp);
return ret;
}
/*
* pmempool_info_btt -- print information about btt device
*/
int
pmempool_info_btt(struct pmem_info *pip)
{
int ret;
outv(1, "\nBTT Device");
ret = info_btt_layout(pip, DEFAULT_HDR_SIZE);
return ret;
}
| 14,565 | 24.644366 | 74 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/common.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* common.c -- definitions of common functions
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <string.h>
#include <err.h>
#include <sys/param.h>
#include <sys/mman.h>
#include <ctype.h>
#include <assert.h>
#include <getopt.h>
#include <unistd.h>
#include <endian.h>
#include "common.h"
#include "output.h"
#include "libpmem.h"
#include "libpmemblk.h"
#include "libpmemlog.h"
#include "libpmemobj.h"
#include "btt.h"
#include "file.h"
#include "os.h"
#include "set.h"
#include "out.h"
#include "mmap.h"
#include "util_pmem.h"
#include "set_badblocks.h"
#include "util.h"
#define REQ_BUFF_SIZE 2048U
#define Q_BUFF_SIZE 8192
typedef const char *(*enum_to_str_fn)(int);
/*
* pmem_pool_type -- return pool type based on first two pages.
* If pool header's content suggests that pool may be BTT device
* (first page zeroed and no correct signature for pool header),
* signature from second page is checked to prove that it's BTT device layout.
*/
pmem_pool_type_t
pmem_pool_type(const void *base_pool_addr)
{
struct pool_hdr *hdrp = (struct pool_hdr *)base_pool_addr;
if (util_is_zeroed(hdrp, DEFAULT_HDR_SIZE)) {
return util_get_pool_type_second_page(base_pool_addr);
}
pmem_pool_type_t type = pmem_pool_type_parse_hdr(hdrp);
if (type != PMEM_POOL_TYPE_UNKNOWN)
return type;
else
return util_get_pool_type_second_page(base_pool_addr);
}
/*
* pmem_pool_checksum -- return true if checksum is correct
* based on first two pages
*/
int
pmem_pool_checksum(const void *base_pool_addr)
{
/* check whether it's btt device -> first page zeroed */
if (util_is_zeroed(base_pool_addr, DEFAULT_HDR_SIZE)) {
struct btt_info bttinfo;
void *sec_page_addr = (char *)base_pool_addr + DEFAULT_HDR_SIZE;
memcpy(&bttinfo, sec_page_addr, sizeof(bttinfo));
btt_info_convert2h(&bttinfo);
return util_checksum(&bttinfo, sizeof(bttinfo),
&bttinfo.checksum, 0, 0);
} else {
/* it's not btt device - first page contains header */
struct pool_hdr hdrp;
memcpy(&hdrp, base_pool_addr, sizeof(hdrp));
return util_checksum(&hdrp, sizeof(hdrp),
&hdrp.checksum, 0, POOL_HDR_CSUM_END_OFF(&hdrp));
}
}
/*
* pmem_pool_type_parse_hdr -- return pool type based only on signature
*/
pmem_pool_type_t
pmem_pool_type_parse_hdr(const struct pool_hdr *hdrp)
{
if (memcmp(hdrp->signature, LOG_HDR_SIG, POOL_HDR_SIG_LEN) == 0)
return PMEM_POOL_TYPE_LOG;
else if (memcmp(hdrp->signature, BLK_HDR_SIG, POOL_HDR_SIG_LEN) == 0)
return PMEM_POOL_TYPE_BLK;
else if (memcmp(hdrp->signature, OBJ_HDR_SIG, POOL_HDR_SIG_LEN) == 0)
return PMEM_POOL_TYPE_OBJ;
else
return PMEM_POOL_TYPE_UNKNOWN;
}
/*
* pmem_pool_type_parse_str -- returns pool type from command line arg
*/
pmem_pool_type_t
pmem_pool_type_parse_str(const char *str)
{
if (strcmp(str, "blk") == 0) {
return PMEM_POOL_TYPE_BLK;
} else if (strcmp(str, "log") == 0) {
return PMEM_POOL_TYPE_LOG;
} else if (strcmp(str, "obj") == 0) {
return PMEM_POOL_TYPE_OBJ;
} else if (strcmp(str, "btt") == 0) {
return PMEM_POOL_TYPE_BTT;
} else {
return PMEM_POOL_TYPE_UNKNOWN;
}
}
/*
* util_get_pool_type_second_page -- return type based on second page content
*/
pmem_pool_type_t
util_get_pool_type_second_page(const void *pool_base_addr)
{
struct btt_info bttinfo;
void *sec_page_addr = (char *)pool_base_addr + DEFAULT_HDR_SIZE;
memcpy(&bttinfo, sec_page_addr, sizeof(bttinfo));
btt_info_convert2h(&bttinfo);
if (util_is_zeroed(&bttinfo, sizeof(bttinfo)))
return PMEM_POOL_TYPE_UNKNOWN;
if (memcmp(bttinfo.sig, BTTINFO_SIG, BTTINFO_SIG_LEN) == 0)
return PMEM_POOL_TYPE_BTT;
return PMEM_POOL_TYPE_UNKNOWN;
}
/*
* util_parse_mode -- parse file mode from octal string
*/
int
util_parse_mode(const char *str, mode_t *mode)
{
mode_t m = 0;
int digits = 0;
/* skip leading zeros */
while (*str == '0')
str++;
/* parse at most 3 octal digits */
while (digits < 3 && *str != '\0') {
if (*str < '0' || *str > '7')
return -1;
m = (mode_t)(m << 3) | (mode_t)(*str - '0');
digits++;
str++;
}
/* more than 3 octal digits */
if (digits == 3 && *str != '\0')
return -1;
if (mode)
*mode = m;
return 0;
}
static void
util_range_limit(struct range *rangep, struct range limit)
{
if (rangep->first < limit.first)
rangep->first = limit.first;
if (rangep->last > limit.last)
rangep->last = limit.last;
}
/*
* util_parse_range_from -- parse range string as interval from specified number
*/
static int
util_parse_range_from(char *str, struct range *rangep, struct range entire)
{
size_t str_len = strlen(str);
if (str[str_len - 1] != '-')
return -1;
str[str_len - 1] = '\0';
if (util_parse_size(str, (size_t *)&rangep->first))
return -1;
rangep->last = entire.last;
util_range_limit(rangep, entire);
return 0;
}
/*
* util_parse_range_to -- parse range string as interval to specified number
*/
static int
util_parse_range_to(char *str, struct range *rangep, struct range entire)
{
if (str[0] != '-' || str[1] == '\0')
return -1;
if (util_parse_size(str + 1, (size_t *)&rangep->last))
return -1;
rangep->first = entire.first;
util_range_limit(rangep, entire);
return 0;
}
/*
* util_parse_range_number -- parse range string as a single number
*/
static int
util_parse_range_number(char *str, struct range *rangep, struct range entire)
{
if (util_parse_size(str, (size_t *)&rangep->first) != 0)
return -1;
rangep->last = rangep->first;
if (rangep->first > entire.last ||
rangep->last < entire.first)
return -1;
util_range_limit(rangep, entire);
return 0;
}
/*
* util_parse_range -- parse single range string
*/
static int
util_parse_range(char *str, struct range *rangep, struct range entire)
{
char *dash = strchr(str, '-');
if (!dash)
return util_parse_range_number(str, rangep, entire);
/* '-' at the beginning */
if (dash == str)
return util_parse_range_to(str, rangep, entire);
/* '-' at the end */
if (dash[1] == '\0')
return util_parse_range_from(str, rangep, entire);
*dash = '\0';
dash++;
if (util_parse_size(str, (size_t *)&rangep->first))
return -1;
if (util_parse_size(dash, (size_t *)&rangep->last))
return -1;
if (rangep->first > rangep->last) {
uint64_t tmp = rangep->first;
rangep->first = rangep->last;
rangep->last = tmp;
}
util_range_limit(rangep, entire);
return 0;
}
/*
* util_ranges_overlap -- return 1 if two ranges are overlapped
*/
static int
util_ranges_overlap(struct range *rangep1, struct range *rangep2)
{
if (rangep1->last + 1 < rangep2->first ||
rangep2->last + 1 < rangep1->first)
return 0;
else
return 1;
}
/*
* util_ranges_add -- create and add range
*/
int
util_ranges_add(struct ranges *rangesp, struct range range)
{
struct range *rangep = malloc(sizeof(struct range));
if (!rangep)
err(1, "Cannot allocate memory for range\n");
memcpy(rangep, &range, sizeof(*rangep));
struct range *curp, *next;
uint64_t first = rangep->first;
uint64_t last = rangep->last;
curp = PMDK_LIST_FIRST(&rangesp->head);
while (curp) {
next = PMDK_LIST_NEXT(curp, next);
if (util_ranges_overlap(curp, rangep)) {
PMDK_LIST_REMOVE(curp, next);
if (curp->first < first)
first = curp->first;
if (curp->last > last)
last = curp->last;
free(curp);
}
curp = next;
}
rangep->first = first;
rangep->last = last;
PMDK_LIST_FOREACH(curp, &rangesp->head, next) {
if (curp->first < rangep->first) {
PMDK_LIST_INSERT_AFTER(curp, rangep, next);
return 0;
}
}
PMDK_LIST_INSERT_HEAD(&rangesp->head, rangep, next);
return 0;
}
/*
* util_ranges_contain -- return 1 if ranges contain the number n
*/
int
util_ranges_contain(const struct ranges *rangesp, uint64_t n)
{
struct range *curp = NULL;
PMDK_LIST_FOREACH(curp, &rangesp->head, next) {
if (curp->first <= n && n <= curp->last)
return 1;
}
return 0;
}
/*
* util_ranges_empty -- return 1 if ranges are empty
*/
int
util_ranges_empty(const struct ranges *rangesp)
{
return PMDK_LIST_EMPTY(&rangesp->head);
}
/*
* util_ranges_clear -- clear list of ranges
*/
void
util_ranges_clear(struct ranges *rangesp)
{
while (!PMDK_LIST_EMPTY(&rangesp->head)) {
struct range *rangep = PMDK_LIST_FIRST(&rangesp->head);
PMDK_LIST_REMOVE(rangep, next);
free(rangep);
}
}
/*
* util_parse_ranges -- parser ranges from string
*
* The valid formats of range are:
* - 'n-m' -- from n to m
* - '-m' -- from minimum passed in entirep->first to m
* - 'n-' -- from n to maximum passed in entirep->last
* - 'n' -- n'th byte/block
* Multiple ranges may be separated by comma:
* 'n1-m1,n2-,-m3,n4'
*/
int
util_parse_ranges(const char *ptr, struct ranges *rangesp, struct range entire)
{
if (ptr == NULL)
return util_ranges_add(rangesp, entire);
char *dup = strdup(ptr);
if (!dup)
err(1, "Cannot allocate memory for ranges");
char *str = dup;
int ret = 0;
char *next = str;
do {
str = next;
next = strchr(str, ',');
if (next != NULL) {
*next = '\0';
next++;
}
struct range range;
if (util_parse_range(str, &range, entire)) {
ret = -1;
goto out;
} else if (util_ranges_add(rangesp, range)) {
ret = -1;
goto out;
}
} while (next != NULL);
out:
free(dup);
return ret;
}
/*
* pmem_pool_get_min_size -- return minimum size of pool for specified type
*/
uint64_t
pmem_pool_get_min_size(pmem_pool_type_t type)
{
switch (type) {
case PMEM_POOL_TYPE_LOG:
return PMEMLOG_MIN_POOL;
case PMEM_POOL_TYPE_BLK:
return PMEMBLK_MIN_POOL;
case PMEM_POOL_TYPE_OBJ:
return PMEMOBJ_MIN_POOL;
default:
break;
}
return 0;
}
/*
* util_poolset_map -- map poolset
*/
int
util_poolset_map(const char *fname, struct pool_set **poolset, int rdonly)
{
if (util_is_poolset_file(fname) != 1) {
int ret = util_poolset_create_set(poolset, fname, 0, 0, true);
if (ret < 0) {
outv_err("cannot open pool set -- '%s'", fname);
return -1;
}
unsigned flags = (rdonly ? POOL_OPEN_COW : 0) |
POOL_OPEN_IGNORE_BAD_BLOCKS;
return util_pool_open_nocheck(*poolset, flags);
}
/* open poolset file */
int fd = util_file_open(fname, NULL, 0, O_RDONLY);
if (fd < 0)
return -1;
struct pool_set *set;
/* parse poolset file */
if (util_poolset_parse(&set, fname, fd)) {
outv_err("parsing poolset file failed\n");
os_close(fd);
return -1;
}
set->ignore_sds = true;
os_close(fd);
/* read the pool header from first pool set file */
const char *part0_path = PART(REP(set, 0), 0)->path;
struct pool_hdr hdr;
if (util_file_pread(part0_path, &hdr, sizeof(hdr), 0) !=
sizeof(hdr)) {
outv_err("cannot read pool header from poolset\n");
goto err_pool_set;
}
util_poolset_free(set);
util_convert2h_hdr_nocheck(&hdr);
/* parse pool type from first pool set file */
pmem_pool_type_t type = pmem_pool_type_parse_hdr(&hdr);
if (type == PMEM_POOL_TYPE_UNKNOWN) {
outv_err("cannot determine pool type from poolset\n");
return -1;
}
/*
* Just use one thread - there is no need for multi-threaded access
* to remote pool.
*/
unsigned nlanes = 1;
/*
* Open the poolset, the values passed to util_pool_open are read
* from the first poolset file, these values are then compared with
* the values from all headers of poolset files.
*/
struct pool_attr attr;
util_pool_hdr2attr(&attr, &hdr);
unsigned flags = (rdonly ? POOL_OPEN_COW : 0) | POOL_OPEN_IGNORE_SDS |
POOL_OPEN_IGNORE_BAD_BLOCKS;
if (util_pool_open(poolset, fname, 0 /* minpartsize */,
&attr, &nlanes, NULL, flags)) {
outv_err("opening poolset failed\n");
return -1;
}
return 0;
err_pool_set:
util_poolset_free(set);
return -1;
}
/*
* pmem_pool_parse_params -- parse pool type, file size and block size
*/
int
pmem_pool_parse_params(const char *fname, struct pmem_pool_params *paramsp,
int check)
{
paramsp->type = PMEM_POOL_TYPE_UNKNOWN;
char pool_str_addr[POOL_HDR_DESC_SIZE];
enum file_type type = util_file_get_type(fname);
if (type < 0)
return -1;
int is_poolset = util_is_poolset_file(fname);
if (is_poolset < 0)
return -1;
paramsp->is_poolset = is_poolset;
int fd = util_file_open(fname, NULL, 0, O_RDONLY);
if (fd < 0)
return -1;
/* get file size and mode */
os_stat_t stat_buf;
if (os_fstat(fd, &stat_buf)) {
os_close(fd);
return -1;
}
int ret = 0;
assert(stat_buf.st_size >= 0);
paramsp->size = (uint64_t)stat_buf.st_size;
paramsp->mode = stat_buf.st_mode;
void *addr = NULL;
struct pool_set *set = NULL;
if (paramsp->is_poolset) {
/* close the file */
os_close(fd);
fd = -1;
if (check) {
if (util_poolset_map(fname, &set, 0)) {
ret = -1;
goto out_close;
}
} else {
ret = util_poolset_create_set(&set, fname, 0, 0, true);
if (ret < 0) {
outv_err("cannot open pool set -- '%s'", fname);
ret = -1;
goto out_close;
}
if (util_pool_open_nocheck(set,
POOL_OPEN_IGNORE_BAD_BLOCKS)) {
ret = -1;
goto out_close;
}
}
paramsp->size = set->poolsize;
addr = set->replica[0]->part[0].addr;
/*
* XXX mprotect for device dax with length not aligned to its
* page granularity causes SIGBUS on the next page fault.
* The length argument of this call should be changed to
* set->poolsize once the kernel issue is solved.
*/
if (mprotect(addr, set->replica[0]->repsize,
PROT_READ) < 0) {
outv_err("!mprotect");
goto out_close;
}
} else {
/* read first two pages */
if (type == TYPE_DEVDAX) {
addr = util_file_map_whole(fname);
if (addr == NULL) {
ret = -1;
goto out_close;
}
} else {
ssize_t num = read(fd, pool_str_addr,
POOL_HDR_DESC_SIZE);
if (num < (ssize_t)POOL_HDR_DESC_SIZE) {
outv_err("!read");
ret = -1;
goto out_close;
}
addr = pool_str_addr;
}
}
struct pool_hdr hdr;
memcpy(&hdr, addr, sizeof(hdr));
util_convert2h_hdr_nocheck(&hdr);
memcpy(paramsp->signature, hdr.signature, sizeof(paramsp->signature));
/*
* Check if file is a part of pool set by comparing
* the UUID with the next part UUID. If it is the same
* it means the pool consist of a single file.
*/
paramsp->is_part = !paramsp->is_poolset &&
(memcmp(hdr.uuid, hdr.next_part_uuid, POOL_HDR_UUID_LEN) ||
memcmp(hdr.uuid, hdr.prev_part_uuid, POOL_HDR_UUID_LEN) ||
memcmp(hdr.uuid, hdr.next_repl_uuid, POOL_HDR_UUID_LEN) ||
memcmp(hdr.uuid, hdr.prev_repl_uuid, POOL_HDR_UUID_LEN));
if (check)
paramsp->type = pmem_pool_type(addr);
else
paramsp->type = pmem_pool_type_parse_hdr(addr);
paramsp->is_checksum_ok = pmem_pool_checksum(addr);
if (paramsp->type == PMEM_POOL_TYPE_BLK) {
struct pmemblk *pbp = addr;
paramsp->blk.bsize = le32toh(pbp->bsize);
} else if (paramsp->type == PMEM_POOL_TYPE_OBJ) {
struct pmemobjpool *pop = addr;
memcpy(paramsp->obj.layout, pop->layout, PMEMOBJ_MAX_LAYOUT);
}
if (paramsp->is_poolset)
util_poolset_close(set, DO_NOT_DELETE_PARTS);
out_close:
if (fd >= 0)
(void) os_close(fd);
return ret;
}
/*
* util_check_memory -- check if memory contains single value
*/
int
util_check_memory(const uint8_t *buff, size_t len, uint8_t val)
{
size_t i;
for (i = 0; i < len; i++) {
if (buff[i] != val)
return -1;
}
return 0;
}
/*
* pmempool_ask_yes_no -- prints the question,
* takes user answer and returns validated value
*/
static char
pmempool_ask_yes_no(char def_ans, const char *answers, const char *qbuff)
{
char ret = INV_ANS;
printf("%s", qbuff);
size_t len = strlen(answers);
size_t i;
char def_anslo = (char)tolower(def_ans);
printf(" [");
for (i = 0; i < len; i++) {
char anslo = (char)tolower(answers[i]);
printf("%c", anslo == def_anslo ?
toupper(anslo) : anslo);
if (i != len - 1)
printf("/");
}
printf("] ");
char *line_of_answer = util_readline(stdin);
if (line_of_answer == NULL) {
outv_err("input is empty");
return '?';
}
char first_letter = line_of_answer[0];
line_of_answer[0] = (char)tolower(first_letter);
if (strcmp(line_of_answer, "yes\n") == 0) {
if (strchr(answers, 'y') != NULL)
ret = 'y';
}
if (strcmp(line_of_answer, "no\n") == 0) {
if (strchr(answers, 'n') != NULL)
ret = 'n';
}
if (strlen(line_of_answer) == 2 &&
line_of_answer[1] == '\n') {
if (strchr(answers, line_of_answer[0]) != NULL)
ret = line_of_answer[0];
}
if (strlen(line_of_answer) == 1 &&
line_of_answer[0] == '\n') {
ret = def_ans;
}
Free(line_of_answer);
return ret;
}
/*
* ask -- keep asking for answer until it gets valid input
*/
char
ask(char op, char *answers, char def_ans, const char *fmt, va_list ap)
{
char qbuff[Q_BUFF_SIZE];
char ret = INV_ANS;
int is_tty = 0;
if (op != '?')
return op;
int p = vsnprintf(qbuff, Q_BUFF_SIZE, fmt, ap);
if (p < 0) {
outv_err("vsnprintf");
exit(EXIT_FAILURE);
}
if (p >= Q_BUFF_SIZE) {
outv_err("vsnprintf: output was truncated");
exit(EXIT_FAILURE);
}
is_tty = isatty(fileno(stdin));
while ((ret = pmempool_ask_yes_no(def_ans, answers, qbuff)) == INV_ANS)
;
if (!is_tty)
printf("%c\n", ret);
return ret;
}
char
ask_Yn(char op, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char ret = ask(op, "yn", 'y', fmt, ap);
va_end(ap);
return ret;
}
char
ask_yN(char op, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char ret = ask(op, "yn", 'n', fmt, ap);
va_end(ap);
return ret;
}
/*
* util_parse_enum -- parse single enum and store to bitmap
*/
static int
util_parse_enum(const char *str, int first, int max, uint64_t *bitmap,
enum_to_str_fn enum_to_str)
{
for (int i = first; i < max; i++) {
if (strcmp(str, enum_to_str(i)) == 0) {
*bitmap |= (uint64_t)1<<i;
return 0;
}
}
return -1;
}
/*
* util_parse_enums -- parse enums and store to bitmap
*/
static int
util_parse_enums(const char *str, int first, int max, uint64_t *bitmap,
enum_to_str_fn enum_to_str)
{
char *dup = strdup(str);
if (!dup)
err(1, "Cannot allocate memory for enum str");
char *ptr = dup;
int ret = 0;
char *comma;
do {
comma = strchr(ptr, ',');
if (comma) {
*comma = '\0';
comma++;
}
if ((ret = util_parse_enum(ptr, first, max,
bitmap, enum_to_str))) {
goto out;
}
ptr = comma;
} while (ptr);
out:
free(dup);
return ret;
}
/*
* util_parse_chunk_types -- parse chunk types strings
*/
int
util_parse_chunk_types(const char *str, uint64_t *types)
{
assert(MAX_CHUNK_TYPE < 8 * sizeof(*types));
return util_parse_enums(str, 0, MAX_CHUNK_TYPE, types,
(enum_to_str_fn)out_get_chunk_type_str);
}
/*
* util_options_alloc -- allocate and initialize options structure
*/
struct options *
util_options_alloc(const struct option *options,
size_t nopts, const struct option_requirement *req)
{
struct options *opts = calloc(1, sizeof(*opts));
if (!opts)
err(1, "Cannot allocate memory for options structure");
opts->opts = options;
opts->noptions = nopts;
opts->req = req;
size_t bitmap_size = howmany(nopts, 8);
opts->bitmap = calloc(bitmap_size, 1);
if (!opts->bitmap)
err(1, "Cannot allocate memory for options bitmap");
return opts;
}
/*
* util_options_free -- free options structure
*/
void
util_options_free(struct options *opts)
{
free(opts->bitmap);
free(opts);
}
/*
* util_opt_get_index -- return index of specified option in global
* array of options
*/
static int
util_opt_get_index(const struct options *opts, int opt)
{
const struct option *lopt = &opts->opts[0];
int ret = 0;
while (lopt->name) {
if ((lopt->val & ~OPT_MASK) == opt)
return ret;
lopt++;
ret++;
}
return -1;
}
/*
* util_opt_get_req -- get required option for specified option
*/
static struct option_requirement *
util_opt_get_req(const struct options *opts, int opt, pmem_pool_type_t type)
{
size_t n = 0;
struct option_requirement *ret = NULL;
struct option_requirement *tmp = NULL;
const struct option_requirement *req = &opts->req[0];
while (req->opt) {
if (req->opt == opt && (req->type & type)) {
n++;
tmp = realloc(ret, n * sizeof(*ret));
if (!tmp)
err(1, "Cannot allocate memory for"
" option requirements");
ret = tmp;
ret[n - 1] = *req;
}
req++;
}
if (ret) {
tmp = realloc(ret, (n + 1) * sizeof(*ret));
if (!tmp)
err(1, "Cannot allocate memory for"
" option requirements");
ret = tmp;
memset(&ret[n], 0, sizeof(*ret));
}
return ret;
}
/*
* util_opt_check_requirements -- check if requirements has been fulfilled
*/
static int
util_opt_check_requirements(const struct options *opts,
const struct option_requirement *req)
{
int count = 0;
int set = 0;
uint64_t tmp;
while ((tmp = req->req) != 0) {
while (tmp) {
int req_idx =
util_opt_get_index(opts, tmp & OPT_REQ_MASK);
if (req_idx >= 0 && util_isset(opts->bitmap, req_idx)) {
set++;
break;
}
tmp >>= OPT_REQ_SHIFT;
}
req++;
count++;
}
return count != set;
}
/*
* util_opt_print_requirements -- print requirements for specified option
*/
static void
util_opt_print_requirements(const struct options *opts,
const struct option_requirement *req)
{
char buff[REQ_BUFF_SIZE];
unsigned n = 0;
uint64_t tmp;
const struct option *opt =
&opts->opts[util_opt_get_index(opts, req->opt)];
int sn;
sn = util_snprintf(&buff[n], REQ_BUFF_SIZE - n,
"option [-%c|--%s] requires: ", opt->val, opt->name);
assert(sn >= 0);
if (sn >= 0)
n += (unsigned)sn;
size_t rc = 0;
while ((tmp = req->req) != 0) {
if (rc != 0) {
sn = util_snprintf(&buff[n], REQ_BUFF_SIZE - n,
" and ");
assert(sn >= 0);
if (sn >= 0)
n += (unsigned)sn;
}
size_t c = 0;
while (tmp) {
sn = util_snprintf(&buff[n], REQ_BUFF_SIZE - n,
c == 0 ? "[" : "|");
assert(sn >= 0);
if (sn >= 0)
n += (unsigned)sn;
int req_opt_ind =
util_opt_get_index(opts, tmp & OPT_REQ_MASK);
const struct option *req_option =
&opts->opts[req_opt_ind];
sn = util_snprintf(&buff[n], REQ_BUFF_SIZE - n,
"-%c|--%s", req_option->val, req_option->name);
assert(sn >= 0);
if (sn >= 0)
n += (unsigned)sn;
tmp >>= OPT_REQ_SHIFT;
c++;
}
sn = util_snprintf(&buff[n], REQ_BUFF_SIZE - n, "]");
assert(sn >= 0);
if (sn >= 0)
n += (unsigned)sn;
req++;
rc++;
}
outv_err("%s\n", buff);
}
/*
* util_opt_verify_requirements -- verify specified requirements for options
*/
static int
util_opt_verify_requirements(const struct options *opts, size_t index,
pmem_pool_type_t type)
{
const struct option *opt = &opts->opts[index];
int val = opt->val & ~OPT_MASK;
struct option_requirement *req;
if ((req = util_opt_get_req(opts, val, type)) == NULL)
return 0;
int ret = 0;
if (util_opt_check_requirements(opts, req)) {
ret = -1;
util_opt_print_requirements(opts, req);
}
free(req);
return ret;
}
/*
* util_opt_verify_type -- check if used option matches pool type
*/
static int
util_opt_verify_type(const struct options *opts, pmem_pool_type_t type,
size_t index)
{
const struct option *opt = &opts->opts[index];
int val = opt->val & ~OPT_MASK;
int opt_type = opt->val;
opt_type >>= OPT_SHIFT;
if (!(opt_type & (1<<type))) {
outv_err("'--%s|-%c' -- invalid option specified"
" for pool type '%s'\n",
opt->name, val,
out_get_pool_type_str(type));
return -1;
}
return 0;
}
/*
* util_options_getopt -- wrapper for getopt_long which sets bitmap
*/
int
util_options_getopt(int argc, char *argv[], const char *optstr,
const struct options *opts)
{
int opt = getopt_long(argc, argv, optstr, opts->opts, NULL);
if (opt == -1 || opt == '?')
return opt;
opt &= ~OPT_MASK;
int option_index = util_opt_get_index(opts, opt);
assert(option_index >= 0);
util_setbit((uint8_t *)opts->bitmap, (unsigned)option_index);
return opt;
}
/*
* util_options_verify -- verify options
*/
int
util_options_verify(const struct options *opts, pmem_pool_type_t type)
{
for (size_t i = 0; i < opts->noptions; i++) {
if (util_isset(opts->bitmap, i)) {
if (util_opt_verify_type(opts, type, i))
return -1;
if (opts->req)
if (util_opt_verify_requirements(opts, i, type))
return -1;
}
}
return 0;
}
/*
* util_heap_max_zone -- get number of zones
*/
unsigned
util_heap_max_zone(size_t size)
{
unsigned max_zone = 0;
size -= sizeof(struct heap_header);
while (size >= ZONE_MIN_SIZE) {
max_zone++;
size -= size <= ZONE_MAX_SIZE ? size : ZONE_MAX_SIZE;
}
return max_zone;
}
/*
* pool_set_file_open -- opens pool set file or regular file
*/
struct pool_set_file *
pool_set_file_open(const char *fname,
int rdonly, int check)
{
struct pool_set_file *file = calloc(1, sizeof(*file));
if (!file)
return NULL;
file->replica = 0;
file->fname = strdup(fname);
if (!file->fname)
goto err;
os_stat_t buf;
if (os_stat(fname, &buf)) {
warn("%s", fname);
goto err_free_fname;
}
file->mtime = buf.st_mtime;
file->mode = buf.st_mode;
if (S_ISBLK(file->mode))
file->fileio = true;
if (file->fileio) {
/* Simple file open for BTT device */
int fd = util_file_open(fname, NULL, 0, O_RDONLY);
if (fd < 0) {
outv_err("util_file_open failed\n");
goto err_free_fname;
}
os_off_t seek_size = os_lseek(fd, 0, SEEK_END);
if (seek_size == -1) {
outv_err("lseek SEEK_END failed\n");
os_close(fd);
goto err_free_fname;
}
file->size = (size_t)seek_size;
file->fd = fd;
} else {
/*
* The check flag indicates whether the headers from each pool
* set file part should be checked for valid values.
*/
if (check) {
if (util_poolset_map(file->fname,
&file->poolset, rdonly))
goto err_free_fname;
} else {
int ret = util_poolset_create_set(&file->poolset,
file->fname, 0, 0, true);
if (ret < 0) {
outv_err("cannot open pool set -- '%s'",
file->fname);
goto err_free_fname;
}
unsigned flags = (rdonly ? POOL_OPEN_COW : 0) |
POOL_OPEN_IGNORE_BAD_BLOCKS;
if (util_pool_open_nocheck(file->poolset, flags))
goto err_free_fname;
}
/* get modification time from the first part of first replica */
const char *path = file->poolset->replica[0]->part[0].path;
if (os_stat(path, &buf)) {
warn("%s", path);
goto err_close_poolset;
}
file->size = file->poolset->poolsize;
file->addr = file->poolset->replica[0]->part[0].addr;
}
return file;
err_close_poolset:
util_poolset_close(file->poolset, DO_NOT_DELETE_PARTS);
err_free_fname:
free(file->fname);
err:
free(file);
return NULL;
}
/*
* pool_set_file_close -- closes pool set file or regular file
*/
void
pool_set_file_close(struct pool_set_file *file)
{
if (!file->fileio) {
if (file->poolset)
util_poolset_close(file->poolset, DO_NOT_DELETE_PARTS);
else if (file->addr) {
munmap(file->addr, file->size);
os_close(file->fd);
}
}
free(file->fname);
free(file);
}
/*
* pool_set_file_read -- read from pool set file or regular file
*
* 'buff' has to be a buffer at least 'nbytes' long
* 'off' is an offset from the beginning of the file
*/
int
pool_set_file_read(struct pool_set_file *file, void *buff,
size_t nbytes, uint64_t off)
{
if (off + nbytes > file->size)
return -1;
if (file->fileio) {
ssize_t num = pread(file->fd, buff, nbytes, (os_off_t)off);
if (num < (ssize_t)nbytes)
return -1;
} else {
memcpy(buff, (char *)file->addr + off, nbytes);
}
return 0;
}
/*
* pool_set_file_write -- write to pool set file or regular file
*
* 'buff' has to be a buffer at least 'nbytes' long
* 'off' is an offset from the beginning of the file
*/
int
pool_set_file_write(struct pool_set_file *file, void *buff,
size_t nbytes, uint64_t off)
{
enum file_type type = util_file_get_type(file->fname);
if (type < 0)
return -1;
if (off + nbytes > file->size)
return -1;
if (file->fileio) {
ssize_t num = pwrite(file->fd, buff, nbytes, (os_off_t)off);
if (num < (ssize_t)nbytes)
return -1;
} else {
memcpy((char *)file->addr + off, buff, nbytes);
util_persist_auto(type == TYPE_DEVDAX, (char *)file->addr + off,
nbytes);
}
return 0;
}
/*
* pool_set_file_set_replica -- change replica for pool set file
*/
int
pool_set_file_set_replica(struct pool_set_file *file, size_t replica)
{
if (!replica)
return 0;
if (!file->poolset)
return -1;
if (replica >= file->poolset->nreplicas)
return -1;
if (file->poolset->replica[replica]->remote) {
outv_err("reading from remote replica not supported");
return -1;
}
file->replica = replica;
file->addr = file->poolset->replica[replica]->part[0].addr;
return 0;
}
/*
* pool_set_file_nreplicas -- return number of replicas
*/
size_t
pool_set_file_nreplicas(struct pool_set_file *file)
{
return file->poolset->nreplicas;
}
/*
* pool_set_file_map -- return mapped address at given offset
*/
void *
pool_set_file_map(struct pool_set_file *file, uint64_t offset)
{
if (file->addr == MAP_FAILED)
return NULL;
return (char *)file->addr + offset;
}
/*
* pool_set_file_persist -- propagates and persists changes to a memory range
*
* 'addr' points to the beginning of data in the master replica that has to be
* propagated
* 'len' is the number of bytes to be propagated to other replicas
*/
void
pool_set_file_persist(struct pool_set_file *file, const void *addr, size_t len)
{
uintptr_t offset = (uintptr_t)((char *)addr -
(char *)file->poolset->replica[0]->part[0].addr);
for (unsigned r = 1; r < file->poolset->nreplicas; ++r) {
struct pool_replica *rep = file->poolset->replica[r];
void *dst = (char *)rep->part[0].addr + offset;
memcpy(dst, addr, len);
util_persist(rep->is_pmem, dst, len);
}
struct pool_replica *rep = file->poolset->replica[0];
util_persist(rep->is_pmem, (void *)addr, len);
}
/*
* util_pool_clear_badblocks -- clear badblocks in a pool (set or a single file)
*/
int
util_pool_clear_badblocks(const char *path, int create)
{
LOG(3, "path %s create %i", path, create);
struct pool_set *setp;
/* do not check minsize */
int ret = util_poolset_create_set(&setp, path, 0, 0,
POOL_OPEN_IGNORE_SDS);
if (ret < 0) {
LOG(2, "cannot open pool set -- '%s'", path);
return -1;
}
if (badblocks_clear_poolset(setp, create)) {
outv_err("clearing bad blocks in the pool set failed -- '%s'",
path);
errno = EIO;
return -1;
}
return 0;
}
| 30,274 | 20.890817 | 80 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/create.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* create.h -- pmempool create command header file
*/
int pmempool_create_func(const char *appname, int argc, char *argv[]);
void pmempool_create_help(const char *appname);
| 265 | 25.6 | 70 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/info_obj.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* info_obj.c -- pmempool info command source file for obj pool
*/
#include <stdlib.h>
#include <stdbool.h>
#include <err.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <assert.h>
#include <inttypes.h>
#include "alloc_class.h"
#include "set.h"
#include "common.h"
#include "output.h"
#include "info.h"
#include "util.h"
#define BITMAP_BUFF_SIZE 1024
#define OFF_TO_PTR(pop, off) ((void *)((uintptr_t)(pop) + (off)))
#define PTR_TO_OFF(pop, ptr) ((uintptr_t)(ptr) - (uintptr_t)(pop))
/*
* lane_need_recovery -- return 1 if lane section needs recovery
*/
static int
lane_need_recovery(struct pmem_info *pip, struct lane_layout *lane)
{
return ulog_recovery_needed((struct ulog *)&lane->external, 1) ||
ulog_recovery_needed((struct ulog *)&lane->internal, 1) ||
ulog_recovery_needed((struct ulog *)&lane->undo, 0);
}
#define RUN_BITMAP_SEPARATOR_DISTANCE 8
/*
* get_bitmap_str -- get bitmap single value string
*/
static const char *
get_bitmap_str(uint64_t val, unsigned values)
{
static char buff[BITMAP_BUFF_SIZE];
unsigned j = 0;
for (unsigned i = 0; i < values && j < BITMAP_BUFF_SIZE - 3; i++) {
buff[j++] = ((val & ((uint64_t)1 << i)) ? 'x' : '.');
if ((i + 1) % RUN_BITMAP_SEPARATOR_DISTANCE == 0)
buff[j++] = ' ';
}
buff[j] = '\0';
return buff;
}
/*
* pmem_obj_stats_get_type -- get stats for specified type number
*/
static struct pmem_obj_type_stats *
pmem_obj_stats_get_type(struct pmem_obj_stats *stats, uint64_t type_num)
{
struct pmem_obj_type_stats *type;
struct pmem_obj_type_stats *type_dest = NULL;
PMDK_TAILQ_FOREACH(type, &stats->type_stats, next) {
if (type->type_num == type_num)
return type;
if (!type_dest && type->type_num > type_num)
type_dest = type;
}
type = calloc(1, sizeof(*type));
if (!type) {
outv_err("cannot allocate memory for type stats\n");
exit(EXIT_FAILURE);
}
type->type_num = type_num;
if (type_dest)
PMDK_TAILQ_INSERT_BEFORE(type_dest, type, next);
else
PMDK_TAILQ_INSERT_TAIL(&stats->type_stats, type, next);
return type;
}
struct info_obj_redo_args {
int v;
size_t i;
struct pmem_info *pip;
};
/*
* info_obj_redo_entry - print redo log entry info
*/
static int
info_obj_redo_entry(struct ulog_entry_base *e, void *arg,
const struct pmem_ops *p_ops)
{
struct info_obj_redo_args *a = arg;
struct ulog_entry_val *ev;
struct ulog_entry_buf *eb;
switch (ulog_entry_type(e)) {
case ULOG_OPERATION_AND:
case ULOG_OPERATION_OR:
case ULOG_OPERATION_SET:
ev = (struct ulog_entry_val *)e;
outv(a->v, "%010zu: "
"Offset: 0x%016jx "
"Value: 0x%016jx ",
a->i++,
ulog_entry_offset(e),
ev->value);
break;
case ULOG_OPERATION_BUF_CPY:
case ULOG_OPERATION_BUF_SET:
eb = (struct ulog_entry_buf *)e;
outv(a->v, "%010zu: "
"Offset: 0x%016jx "
"Size: %s ",
a->i++,
ulog_entry_offset(e),
out_get_size_str(eb->size,
a->pip->args.human));
break;
default:
ASSERT(0); /* unreachable */
}
return 0;
}
/*
* info_obj_redo -- print ulog log entries
*/
static void
info_obj_ulog(struct pmem_info *pip, int v, struct ulog *ulog,
const struct pmem_ops *ops)
{
outv_title(v, "Log entries");
struct info_obj_redo_args args = {v, 0, pip};
ulog_foreach_entry(ulog, info_obj_redo_entry, &args, ops,NULL);
}
/*
* info_obj_alloc_hdr -- print allocation header
*/
static void
info_obj_alloc_hdr(struct pmem_info *pip, int v,
const struct memory_block *m)
{
outv_title(v, "Allocation Header");
outv_field(v, "Size", "%s", out_get_size_str(m->m_ops->get_user_size(m),
pip->args.human));
outv_field(v, "Extra", "%lu", m->m_ops->get_extra(m));
outv_field(v, "Flags", "0x%x", m->m_ops->get_flags(m));
}
/*
* info_obj_object_hdr -- print object headers and data
*/
static void
info_obj_object_hdr(struct pmem_info *pip, int v, int vid,
const struct memory_block *m, uint64_t id)
{
struct pmemobjpool *pop = pip->obj.pop;
void *data = m->m_ops->get_user_data(m);
outv_nl(vid);
outv_field(vid, "Object", "%lu", id);
outv_field(vid, "Offset", "0x%016lx", PTR_TO_OFF(pop, data));
int vahdr = v && pip->args.obj.valloc;
int voobh = v && pip->args.obj.voobhdr;
outv_indent(vahdr || voobh, 1);
info_obj_alloc_hdr(pip, vahdr, m);
outv_hexdump(v && pip->args.vdata, data,
m->m_ops->get_real_size(m),
PTR_TO_OFF(pip->obj.pop, data), 1);
outv_indent(vahdr || voobh, -1);
}
/*
* info_obj_lane_section -- print lane's section
*/
static void
info_obj_lane(struct pmem_info *pip, int v, struct lane_layout *lane)
{
struct pmem_ops p_ops;
p_ops.base = pip->obj.pop;
outv_title(v, "Undo Log");
outv_indent(v, 1);
info_obj_ulog(pip, v, (struct ulog *)&lane->undo, &p_ops);
outv_indent(v, -1);
outv_nl(v);
outv_title(v, "Internal Undo Log");
outv_indent(v, 1);
info_obj_ulog(pip, v, (struct ulog *)&lane->internal, &p_ops);
outv_indent(v, -1);
outv_title(v, "External Undo Log");
outv_indent(v, 1);
info_obj_ulog(pip, v, (struct ulog *)&lane->external, &p_ops);
outv_indent(v, -1);
}
/*
* info_obj_lanes -- print lanes structures
*/
static void
info_obj_lanes(struct pmem_info *pip)
{
int v = pip->args.obj.vlanes;
if (!outv_check(v))
return;
struct pmemobjpool *pop = pip->obj.pop;
/*
* Iterate through all lanes from specified range and print
* specified sections.
*/
struct lane_layout *lanes = (void *)((char *)pip->obj.pop +
pop->lanes_offset);
struct range *curp = NULL;
FOREACH_RANGE(curp, &pip->args.obj.lane_ranges) {
for (uint64_t i = curp->first;
i <= curp->last && i < pop->nlanes; i++) {
/* For -R check print lane only if needs recovery */
if (pip->args.obj.lanes_recovery &&
!lane_need_recovery(pip, &lanes[i]))
continue;
outv_title(v, "Lane %" PRIu64, i);
outv_indent(v, 1);
info_obj_lane(pip, v, &lanes[i]);
outv_indent(v, -1);
}
}
}
/*
* info_obj_heap -- print pmemobj heap headers
*/
static void
info_obj_heap(struct pmem_info *pip)
{
int v = pip->args.obj.vheap;
struct pmemobjpool *pop = pip->obj.pop;
struct heap_layout *layout = OFF_TO_PTR(pop, pop->heap_offset);
struct heap_header *heap = &layout->header;
outv(v, "\nPMEMOBJ Heap Header:\n");
outv_hexdump(v && pip->args.vhdrdump, heap, sizeof(*heap),
pop->heap_offset, 1);
outv_field(v, "Signature", "%s", heap->signature);
outv_field(v, "Major", "%ld", heap->major);
outv_field(v, "Minor", "%ld", heap->minor);
outv_field(v, "Chunk size", "%s",
out_get_size_str(heap->chunksize, pip->args.human));
outv_field(v, "Chunks per zone", "%ld", heap->chunks_per_zone);
outv_field(v, "Checksum", "%s", out_get_checksum(heap, sizeof(*heap),
&heap->checksum, 0));
}
/*
* info_obj_zone -- print information about zone
*/
static void
info_obj_zone_hdr(struct pmem_info *pip, int v, struct zone_header *zone)
{
outv_hexdump(v && pip->args.vhdrdump, zone, sizeof(*zone),
PTR_TO_OFF(pip->obj.pop, zone), 1);
outv_field(v, "Magic", "%s", out_get_zone_magic_str(zone->magic));
outv_field(v, "Size idx", "%u", zone->size_idx);
}
/*
* info_obj_object -- print information about object
*/
static void
info_obj_object(struct pmem_info *pip, const struct memory_block *m,
uint64_t objid)
{
if (!util_ranges_contain(&pip->args.ranges, objid))
return;
uint64_t type_num = m->m_ops->get_extra(m);
if (!util_ranges_contain(&pip->args.obj.type_ranges, type_num))
return;
uint64_t real_size = m->m_ops->get_real_size(m);
pip->obj.stats.n_total_objects++;
pip->obj.stats.n_total_bytes += real_size;
struct pmem_obj_type_stats *type_stats =
pmem_obj_stats_get_type(&pip->obj.stats, type_num);
type_stats->n_objects++;
type_stats->n_bytes += real_size;
int vid = pip->args.obj.vobjects;
int v = pip->args.obj.vobjects;
outv_indent(v, 1);
info_obj_object_hdr(pip, v, vid, m, objid);
outv_indent(v, -1);
}
/*
* info_obj_run_bitmap -- print chunk run's bitmap
*/
static void
info_obj_run_bitmap(int v, struct run_bitmap *b)
{
/* print only used values for lower verbosity */
uint32_t i;
for (i = 0; i < b->nbits / RUN_BITS_PER_VALUE; i++)
outv(v, "%s\n", get_bitmap_str(b->values[i],
RUN_BITS_PER_VALUE));
unsigned mod = b->nbits % RUN_BITS_PER_VALUE;
if (mod != 0) {
outv(v, "%s\n", get_bitmap_str(b->values[i], mod));
}
}
/*
* info_obj_memblock_is_root -- (internal) checks whether the object is root
*/
static int
info_obj_memblock_is_root(struct pmem_info *pip, const struct memory_block *m)
{
uint64_t roff = pip->obj.pop->root_offset;
if (roff == 0)
return 0;
struct memory_block rm = memblock_from_offset(pip->obj.heap, roff);
return MEMORY_BLOCK_EQUALS(*m, rm);
}
/*
* info_obj_run_cb -- (internal) run object callback
*/
static int
info_obj_run_cb(const struct memory_block *m, void *arg)
{
struct pmem_info *pip = arg;
if (info_obj_memblock_is_root(pip, m))
return 0;
info_obj_object(pip, m, pip->obj.objid++);
return 0;
}
static struct pmem_obj_class_stats *
info_obj_class_stats_get_or_insert(struct pmem_obj_zone_stats *stats,
uint64_t unit_size, uint64_t alignment,
uint32_t nallocs, uint16_t flags)
{
struct pmem_obj_class_stats *cstats;
VEC_FOREACH_BY_PTR(cstats, &stats->class_stats) {
if (cstats->alignment == alignment &&
cstats->flags == flags &&
cstats->nallocs == nallocs &&
cstats->unit_size == unit_size)
return cstats;
}
struct pmem_obj_class_stats s = {0, 0, unit_size,
alignment, nallocs, flags};
if (VEC_PUSH_BACK(&stats->class_stats, s) != 0)
return NULL;
return &VEC_BACK(&stats->class_stats);
}
/*
* info_obj_chunk -- print chunk info
*/
static void
info_obj_chunk(struct pmem_info *pip, uint64_t c, uint64_t z,
struct chunk_header *chunk_hdr, struct chunk *chunk,
struct pmem_obj_zone_stats *stats)
{
int v = pip->args.obj.vchunkhdr;
outv(v, "\n");
outv_field(v, "Chunk", "%lu", c);
struct pmemobjpool *pop = pip->obj.pop;
outv_hexdump(v && pip->args.vhdrdump, chunk_hdr, sizeof(*chunk_hdr),
PTR_TO_OFF(pop, chunk_hdr), 1);
outv_field(v, "Type", "%s", out_get_chunk_type_str(chunk_hdr->type));
outv_field(v, "Flags", "0x%x %s", chunk_hdr->flags,
out_get_chunk_flags(chunk_hdr->flags));
outv_field(v, "Size idx", "%u", chunk_hdr->size_idx);
struct memory_block m = MEMORY_BLOCK_NONE;
m.zone_id = (uint32_t)z;
m.chunk_id = (uint32_t)c;
m.size_idx = (uint32_t)chunk_hdr->size_idx;
memblock_rebuild_state(pip->obj.heap, &m);
if (chunk_hdr->type == CHUNK_TYPE_USED ||
chunk_hdr->type == CHUNK_TYPE_FREE) {
VEC_FRONT(&stats->class_stats).n_units +=
chunk_hdr->size_idx;
if (chunk_hdr->type == CHUNK_TYPE_USED) {
VEC_FRONT(&stats->class_stats).n_used +=
chunk_hdr->size_idx;
/* skip root object */
if (!info_obj_memblock_is_root(pip, &m)) {
info_obj_object(pip, &m, pip->obj.objid++);
}
}
} else if (chunk_hdr->type == CHUNK_TYPE_RUN) {
struct chunk_run *run = (struct chunk_run *)chunk;
outv_hexdump(v && pip->args.vhdrdump, run,
sizeof(run->hdr.block_size) +
sizeof(run->hdr.alignment),
PTR_TO_OFF(pop, run), 1);
struct run_bitmap bitmap;
m.m_ops->get_bitmap(&m, &bitmap);
struct pmem_obj_class_stats *cstats =
info_obj_class_stats_get_or_insert(stats,
run->hdr.block_size, run->hdr.alignment, bitmap.nbits,
chunk_hdr->flags);
if (cstats == NULL) {
outv_err("out of memory, can't allocate statistics");
return;
}
outv_field(v, "Block size", "%s",
out_get_size_str(run->hdr.block_size,
pip->args.human));
uint32_t units = bitmap.nbits;
uint32_t free_space = 0;
uint32_t max_free_block = 0;
m.m_ops->calc_free(&m, &free_space, &max_free_block);
uint32_t used = units - free_space;
cstats->n_units += units;
cstats->n_used += used;
outv_field(v, "Bitmap", "%u / %u", used, units);
info_obj_run_bitmap(v && pip->args.obj.vbitmap, &bitmap);
m.m_ops->iterate_used(&m, info_obj_run_cb, pip);
}
}
/*
* info_obj_zone_chunks -- print chunk headers from specified zone
*/
static void
info_obj_zone_chunks(struct pmem_info *pip, struct zone *zone, uint64_t z,
struct pmem_obj_zone_stats *stats)
{
VEC_INIT(&stats->class_stats);
struct pmem_obj_class_stats default_class_stats = {0, 0,
CHUNKSIZE, 0, 0, 0};
VEC_PUSH_BACK(&stats->class_stats, default_class_stats);
uint64_t c = 0;
while (c < zone->header.size_idx) {
enum chunk_type type = zone->chunk_headers[c].type;
uint64_t size_idx = zone->chunk_headers[c].size_idx;
if (util_ranges_contain(&pip->args.obj.chunk_ranges, c)) {
if (pip->args.obj.chunk_types & (1ULL << type)) {
stats->n_chunks++;
stats->n_chunks_type[type]++;
stats->size_chunks += size_idx;
stats->size_chunks_type[type] += size_idx;
info_obj_chunk(pip, c, z,
&zone->chunk_headers[c],
&zone->chunks[c], stats);
}
if (size_idx > 1 && type != CHUNK_TYPE_RUN &&
pip->args.obj.chunk_types &
(1 << CHUNK_TYPE_FOOTER)) {
size_t f = c + size_idx - 1;
info_obj_chunk(pip, f, z,
&zone->chunk_headers[f],
&zone->chunks[f], stats);
}
}
c += size_idx;
}
}
/*
* info_obj_root_obj -- print root object
*/
static void
info_obj_root_obj(struct pmem_info *pip)
{
int v = pip->args.obj.vroot;
struct pmemobjpool *pop = pip->obj.pop;
if (!pop->root_offset) {
outv(v, "\nNo root object...\n");
return;
}
outv_title(v, "Root object");
outv_field(v, "Offset", "0x%016zx", pop->root_offset);
uint64_t root_size = pop->root_size;
outv_field(v, "Size", "%s",
out_get_size_str(root_size, pip->args.human));
struct memory_block m = memblock_from_offset(
pip->obj.heap, pop->root_offset);
/* do not print object id and offset for root object */
info_obj_object_hdr(pip, v, VERBOSE_SILENT, &m, 0);
}
/*
* info_obj_zones -- print zones and chunks
*/
static void
info_obj_zones_chunks(struct pmem_info *pip)
{
if (!outv_check(pip->args.obj.vheap) &&
!outv_check(pip->args.vstats) &&
!outv_check(pip->args.obj.vobjects))
return;
struct pmemobjpool *pop = pip->obj.pop;
struct heap_layout *layout = OFF_TO_PTR(pop, pop->heap_offset);
size_t maxzone = util_heap_max_zone(pop->heap_size);
pip->obj.stats.n_zones = maxzone;
pip->obj.stats.zone_stats = calloc(maxzone,
sizeof(struct pmem_obj_zone_stats));
if (!pip->obj.stats.zone_stats)
err(1, "Cannot allocate memory for zone stats");
for (size_t i = 0; i < maxzone; i++) {
struct zone *zone = ZID_TO_ZONE(layout, i);
if (util_ranges_contain(&pip->args.obj.zone_ranges, i)) {
int vvv = pip->args.obj.vheap &&
(pip->args.obj.vzonehdr ||
pip->args.obj.vchunkhdr);
outv_title(vvv, "Zone %zu", i);
if (zone->header.magic == ZONE_HEADER_MAGIC)
pip->obj.stats.n_zones_used++;
info_obj_zone_hdr(pip, pip->args.obj.vheap &&
pip->args.obj.vzonehdr,
&zone->header);
outv_indent(vvv, 1);
info_obj_zone_chunks(pip, zone, i,
&pip->obj.stats.zone_stats[i]);
outv_indent(vvv, -1);
}
}
}
/*
* info_obj_descriptor -- print pmemobj descriptor
*/
static void
info_obj_descriptor(struct pmem_info *pip)
{
int v = VERBOSE_DEFAULT;
if (!outv_check(v))
return;
outv(v, "\nPMEM OBJ Header:\n");
struct pmemobjpool *pop = pip->obj.pop;
uint8_t *hdrptr = (uint8_t *)pop + sizeof(pop->hdr);
size_t hdrsize = sizeof(*pop) - sizeof(pop->hdr);
size_t hdroff = sizeof(pop->hdr);
outv_hexdump(pip->args.vhdrdump, hdrptr, hdrsize, hdroff, 1);
/* check if layout is zeroed */
char *layout = util_check_memory((uint8_t *)pop->layout,
sizeof(pop->layout), 0) ?
pop->layout : "(null)";
/* address for checksum */
void *dscp = (void *)((uintptr_t)(pop) + sizeof(struct pool_hdr));
outv_field(v, "Layout", "%s", layout);
outv_field(v, "Lanes offset", "0x%lx", pop->lanes_offset);
outv_field(v, "Number of lanes", "%lu", pop->nlanes);
outv_field(v, "Heap offset", "0x%lx", pop->heap_offset);
outv_field(v, "Heap size", "%lu", pop->heap_size);
outv_field(v, "Checksum", "%s", out_get_checksum(dscp, OBJ_DSC_P_SIZE,
&pop->checksum, 0));
outv_field(v, "Root offset", "0x%lx", pop->root_offset);
/* run id with -v option */
outv_field(v + 1, "Run id", "%lu", pop->run_id);
}
/*
* info_obj_stats_objjects -- print objects' statistics
*/
static void
info_obj_stats_objects(struct pmem_info *pip, int v,
struct pmem_obj_stats *stats)
{
outv_field(v, "Number of objects", "%lu",
stats->n_total_objects);
outv_field(v, "Number of bytes", "%s", out_get_size_str(
stats->n_total_bytes, pip->args.human));
outv_title(v, "Objects by type");
outv_indent(v, 1);
struct pmem_obj_type_stats *type_stats;
PMDK_TAILQ_FOREACH(type_stats, &pip->obj.stats.type_stats, next) {
if (!type_stats->n_objects)
continue;
double n_objects_perc = 100.0 *
(double)type_stats->n_objects /
(double)stats->n_total_objects;
double n_bytes_perc = 100.0 *
(double)type_stats->n_bytes /
(double)stats->n_total_bytes;
outv_nl(v);
outv_field(v, "Type number", "%lu", type_stats->type_num);
outv_field(v, "Number of objects", "%lu [%s]",
type_stats->n_objects,
out_get_percentage(n_objects_perc));
outv_field(v, "Number of bytes", "%s [%s]",
out_get_size_str(
type_stats->n_bytes,
pip->args.human),
out_get_percentage(n_bytes_perc));
}
outv_indent(v, -1);
}
/*
* info_boj_stats_alloc_classes -- print allocation classes' statistics
*/
static void
info_obj_stats_alloc_classes(struct pmem_info *pip, int v,
struct pmem_obj_zone_stats *stats)
{
uint64_t total_bytes = 0;
uint64_t total_used = 0;
outv_indent(v, 1);
struct pmem_obj_class_stats *cstats;
VEC_FOREACH_BY_PTR(cstats, &stats->class_stats) {
if (cstats->n_units == 0)
continue;
double used_perc = 100.0 *
(double)cstats->n_used / (double)cstats->n_units;
outv_nl(v);
outv_field(v, "Unit size", "%s", out_get_size_str(
cstats->unit_size, pip->args.human));
outv_field(v, "Units", "%lu", cstats->n_units);
outv_field(v, "Used units", "%lu [%s]",
cstats->n_used,
out_get_percentage(used_perc));
uint64_t bytes = cstats->unit_size *
cstats->n_units;
uint64_t used = cstats->unit_size *
cstats->n_used;
total_bytes += bytes;
total_used += used;
double used_bytes_perc = 100.0 * (double)used / (double)bytes;
outv_field(v, "Bytes", "%s",
out_get_size_str(bytes, pip->args.human));
outv_field(v, "Used bytes", "%s [%s]",
out_get_size_str(used, pip->args.human),
out_get_percentage(used_bytes_perc));
}
outv_indent(v, -1);
double used_bytes_perc = total_bytes ? 100.0 *
(double)total_used / (double)total_bytes : 0.0;
outv_nl(v);
outv_field(v, "Total bytes", "%s",
out_get_size_str(total_bytes, pip->args.human));
outv_field(v, "Total used bytes", "%s [%s]",
out_get_size_str(total_used, pip->args.human),
out_get_percentage(used_bytes_perc));
}
/*
* info_obj_stats_chunks -- print chunks' statistics
*/
static void
info_obj_stats_chunks(struct pmem_info *pip, int v,
struct pmem_obj_zone_stats *stats)
{
outv_field(v, "Number of chunks", "%lu", stats->n_chunks);
outv_indent(v, 1);
for (unsigned type = 0; type < MAX_CHUNK_TYPE; type++) {
double type_perc = 100.0 *
(double)stats->n_chunks_type[type] /
(double)stats->n_chunks;
if (stats->n_chunks_type[type]) {
outv_field(v, out_get_chunk_type_str(type),
"%lu [%s]",
stats->n_chunks_type[type],
out_get_percentage(type_perc));
}
}
outv_indent(v, -1);
outv_nl(v);
outv_field(v, "Total chunks size", "%s", out_get_size_str(
stats->size_chunks, pip->args.human));
outv_indent(v, 1);
for (unsigned type = 0; type < MAX_CHUNK_TYPE; type++) {
double type_perc = 100.0 *
(double)stats->size_chunks_type[type] /
(double)stats->size_chunks;
if (stats->size_chunks_type[type]) {
outv_field(v, out_get_chunk_type_str(type),
"%lu [%s]",
stats->size_chunks_type[type],
out_get_percentage(type_perc));
}
}
outv_indent(v, -1);
}
/*
* info_obj_add_zone_stats -- add stats to total
*/
static void
info_obj_add_zone_stats(struct pmem_obj_zone_stats *total,
struct pmem_obj_zone_stats *stats)
{
total->n_chunks += stats->n_chunks;
total->size_chunks += stats->size_chunks;
for (int type = 0; type < MAX_CHUNK_TYPE; type++) {
total->n_chunks_type[type] +=
stats->n_chunks_type[type];
total->size_chunks_type[type] +=
stats->size_chunks_type[type];
}
struct pmem_obj_class_stats *cstats;
VEC_FOREACH_BY_PTR(cstats, &stats->class_stats) {
struct pmem_obj_class_stats *ctotal =
info_obj_class_stats_get_or_insert(total, cstats->unit_size,
cstats->alignment, cstats->nallocs, cstats->flags);
if (ctotal == NULL) {
outv_err("out of memory, can't allocate statistics");
return;
}
ctotal->n_units += cstats->n_units;
ctotal->n_used += cstats->n_used;
}
}
/*
* info_obj_stats_zones -- print zones' statistics
*/
static void
info_obj_stats_zones(struct pmem_info *pip, int v, struct pmem_obj_stats *stats,
struct pmem_obj_zone_stats *total)
{
double used_zones_perc = 100.0 * (double)stats->n_zones_used /
(double)stats->n_zones;
outv_field(v, "Number of zones", "%lu", stats->n_zones);
outv_field(v, "Number of used zones", "%lu [%s]", stats->n_zones_used,
out_get_percentage(used_zones_perc));
outv_indent(v, 1);
for (uint64_t i = 0; i < stats->n_zones_used; i++) {
outv_title(v, "Zone %" PRIu64, i);
struct pmem_obj_zone_stats *zstats = &stats->zone_stats[i];
info_obj_stats_chunks(pip, v, zstats);
outv_title(v, "Zone's allocation classes");
info_obj_stats_alloc_classes(pip, v, zstats);
info_obj_add_zone_stats(total, zstats);
}
outv_indent(v, -1);
}
/*
* info_obj_stats -- print statistics
*/
static void
info_obj_stats(struct pmem_info *pip)
{
int v = pip->args.vstats;
if (!outv_check(v))
return;
struct pmem_obj_stats *stats = &pip->obj.stats;
struct pmem_obj_zone_stats total;
memset(&total, 0, sizeof(total));
outv_title(v, "Statistics");
outv_title(v, "Objects");
info_obj_stats_objects(pip, v, stats);
outv_title(v, "Heap");
info_obj_stats_zones(pip, v, stats, &total);
if (stats->n_zones_used > 1) {
outv_title(v, "Total zone's statistics");
outv_title(v, "Chunks statistics");
info_obj_stats_chunks(pip, v, &total);
outv_title(v, "Allocation classes");
info_obj_stats_alloc_classes(pip, v, &total);
}
VEC_DELETE(&total.class_stats);
}
static struct pmem_info *Pip;
#ifndef _WIN32
static void
info_obj_sa_sigaction(int signum, siginfo_t *info, void *context)
{
uintptr_t offset = (uintptr_t)info->si_addr - (uintptr_t)Pip->obj.pop;
outv_err("Invalid offset 0x%lx\n", offset);
exit(EXIT_FAILURE);
}
static struct sigaction info_obj_sigaction = {
.sa_sigaction = info_obj_sa_sigaction,
.sa_flags = SA_SIGINFO
};
#else
#define CALL_FIRST 1
static LONG CALLBACK
exception_handler(_In_ PEXCEPTION_POINTERS ExceptionInfo)
{
PEXCEPTION_RECORD record = ExceptionInfo->ExceptionRecord;
if (record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) {
return EXCEPTION_CONTINUE_SEARCH;
}
uintptr_t offset = (uintptr_t)record->ExceptionInformation[1] -
(uintptr_t)Pip->obj.pop;
outv_err("Invalid offset 0x%lx\n", offset);
exit(EXIT_FAILURE);
}
#endif
/*
* info_obj -- print information about obj pool type
*/
int
pmempool_info_obj(struct pmem_info *pip)
{
pip->obj.pop = pool_set_file_map(pip->pfile, 0);
if (pip->obj.pop == NULL)
return -1;
pip->obj.size = pip->pfile->size;
struct palloc_heap *heap = calloc(1, sizeof(*heap));
if (heap == NULL)
err(1, "Cannot allocate memory for heap data");
heap->layout = OFF_TO_PTR(pip->obj.pop, pip->obj.pop->heap_offset);
heap->base = pip->obj.pop;
pip->obj.alloc_classes = alloc_class_collection_new();
pip->obj.heap = heap;
Pip = pip;
#ifndef _WIN32
if (sigaction(SIGSEGV, &info_obj_sigaction, NULL)) {
#else
if (AddVectoredExceptionHandler(CALL_FIRST, exception_handler) ==
NULL) {
#endif
perror("sigaction");
return -1;
}
pip->obj.uuid_lo = pmemobj_get_uuid_lo(pip->obj.pop);
info_obj_descriptor(pip);
info_obj_lanes(pip);
info_obj_root_obj(pip);
info_obj_heap(pip);
info_obj_zones_chunks(pip);
info_obj_stats(pip);
free(heap);
alloc_class_collection_delete(pip->obj.alloc_classes);
return 0;
}
| 24,182 | 24.11215 | 80 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/pmempool.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* pmempool.c -- pmempool main source file
*/
#include <stdio.h>
#include <libgen.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdbool.h>
#include "common.h"
#include "output.h"
#include "info.h"
#include "create.h"
#include "dump.h"
#include "check.h"
#include "rm.h"
#include "convert.h"
#include "synchronize.h"
#include "transform.h"
#include "feature.h"
#include "set.h"
#include "pmemcommon.h"
#ifndef _WIN32
#include "rpmem_common.h"
#include "rpmem_util.h"
#endif
#define APPNAME "pmempool"
#define PMEMPOOL_TOOL_LOG_PREFIX "pmempool"
#define PMEMPOOL_TOOL_LOG_LEVEL_VAR "PMEMPOOL_TOOL_LOG_LEVEL"
#define PMEMPOOL_TOOL_LOG_FILE_VAR "PMEMPOOL_TOOL_LOG_FILE"
#ifdef USE_NDP_REDO
int use_ndp_redo = 0;
#endif
/*
* command -- struct for pmempool commands definition
*/
struct command {
const char *name;
const char *brief;
int (*func)(const char *, int, char *[]);
void (*help)(const char *);
};
static const struct command *get_command(const char *cmd_str);
static void print_help(const char *appname);
/*
* long_options -- pmempool command line arguments
*/
static const struct option long_options[] = {
{"version", no_argument, NULL, 'V'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 },
};
/*
* help_help -- prints help message for help command
*/
static void
help_help(const char *appname)
{
printf("Usage: %s help <command>\n", appname);
}
/*
* help_func -- prints help message for specified command
*/
static int
help_func(const char *appname, int argc, char *argv[])
{
if (argc > 1) {
char *cmd_str = argv[1];
const struct command *cmdp = get_command(cmd_str);
if (cmdp && cmdp->help) {
cmdp->help(appname);
return 0;
} else {
outv_err("No help text for '%s' command\n", cmd_str);
return -1;
}
} else {
print_help(appname);
return -1;
}
}
/*
* commands -- definition of all pmempool commands
*/
static const struct command commands[] = {
{
.name = "info",
.brief = "print information and statistics about a pool",
.func = pmempool_info_func,
.help = pmempool_info_help,
},
{
.name = "create",
.brief = "create a pool",
.func = pmempool_create_func,
.help = pmempool_create_help,
},
{
.name = "dump",
.brief = "dump user data from a pool",
.func = pmempool_dump_func,
.help = pmempool_dump_help,
},
{
.name = "check",
.brief = "check consistency of a pool",
.func = pmempool_check_func,
.help = pmempool_check_help,
},
{
.name = "rm",
.brief = "remove pool or poolset",
.func = pmempool_rm_func,
.help = pmempool_rm_help,
},
{
.name = "convert",
.brief = "perform pool layout conversion",
.func = pmempool_convert_func,
.help = pmempool_convert_help,
},
{
.name = "sync",
.brief = "synchronize data between replicas",
.func = pmempool_sync_func,
.help = pmempool_sync_help,
},
{
.name = "transform",
.brief = "modify internal structure of a poolset",
.func = pmempool_transform_func,
.help = pmempool_transform_help,
},
{
.name = "feature",
.brief = "toggle / query pool features",
.func = pmempool_feature_func,
.help = pmempool_feature_help,
},
{
.name = "help",
.brief = "print help text about a command",
.func = help_func,
.help = help_help,
},
};
/*
* number of pmempool commands
*/
#define COMMANDS_NUMBER (sizeof(commands) / sizeof(commands[0]))
/*
* print_version -- prints pmempool version message
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* print_usage -- prints pmempool usage message
*/
static void
print_usage(const char *appname)
{
printf("usage: %s [--version] [--help] <command> [<args>]\n", appname);
}
/*
* print_help -- prints pmempool help message
*/
static void
print_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf("\n");
printf("Options:\n");
printf(" -V, --version display version\n");
printf(" -h, --help display this help and exit\n");
printf("\n");
printf("The available commands are:\n");
unsigned i;
for (i = 0; i < COMMANDS_NUMBER; i++) {
const char *format = (strlen(commands[i].name) / 8)
? "%s\t- %s\n" : "%s\t\t- %s\n";
printf(format, commands[i].name, commands[i].brief);
}
printf("\n");
printf("For complete documentation see %s(1) manual page.\n", appname);
}
/*
* get_command -- returns command for specified command name
*/
static const struct command *
get_command(const char *cmd_str)
{
unsigned i;
for (i = 0; i < COMMANDS_NUMBER; i++) {
if (strcmp(cmd_str, commands[i].name) == 0)
return &commands[i];
}
return NULL;
}
int
main(int argc, char *argv[])
{
int opt;
int option_index;
int ret = 0;
#ifdef _WIN32
util_suppress_errmsg();
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
outv_err("Error during arguments conversion\n");
return 1;
}
}
#endif
common_init(PMEMPOOL_TOOL_LOG_PREFIX,
PMEMPOOL_TOOL_LOG_LEVEL_VAR,
PMEMPOOL_TOOL_LOG_FILE_VAR,
0 /* major version */,
0 /* minor version */);
#ifndef _WIN32
util_remote_init();
rpmem_util_cmds_init();
#endif
if (argc < 2) {
print_usage(APPNAME);
goto end;
}
while ((opt = getopt_long(2, argv, "Vh",
long_options, &option_index)) != -1) {
switch (opt) {
case 'V':
print_version(APPNAME);
goto end;
case 'h':
print_help(APPNAME);
goto end;
default:
print_usage(APPNAME);
ret = 1;
goto end;
}
}
char *cmd_str = argv[optind];
const struct command *cmdp = get_command(cmd_str);
if (cmdp) {
ret = cmdp->func(APPNAME, argc - 1, argv + 1);
} else {
outv_err("'%s' -- unknown command\n", cmd_str);
ret = 1;
}
end:
#ifndef _WIN32
util_remote_fini();
rpmem_util_cmds_fini();
#endif
common_fini();
#ifdef _WIN32
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
#endif
if (ret)
return 1;
return 0;
}
| 6,114 | 19.04918 | 72 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/output.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* output.c -- definitions of output printing related functions
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <err.h>
#include <endian.h>
#include <inttypes.h>
#include <float.h>
#include "feature.h"
#include "common.h"
#include "output.h"
#define _STR(s) #s
#define STR(s) _STR(s)
#define TIME_STR_FMT "%a %b %d %Y %H:%M:%S"
#define UUID_STR_MAX 37
#define HEXDUMP_ROW_WIDTH 16
/*
* 2 chars + space per byte +
* space after 8 bytes and terminating NULL
*/
#define HEXDUMP_ROW_HEX_LEN (HEXDUMP_ROW_WIDTH * 3 + 1 + 1)
/* 1 printable char per byte + terminating NULL */
#define HEXDUMP_ROW_ASCII_LEN (HEXDUMP_ROW_WIDTH + 1)
#define SEPARATOR_CHAR '-'
#define MAX_INDENT 32
#define INDENT_CHAR ' '
static char out_indent_str[MAX_INDENT + 1];
static int out_indent_level;
static int out_vlevel;
static unsigned out_column_width = 20;
static FILE *out_fh;
static const char *out_prefix;
#define STR_MAX 256
/*
* outv_check -- verify verbosity level
*/
int
outv_check(int vlevel)
{
return vlevel && (out_vlevel >= vlevel);
}
/*
* out_set_col_width -- set column width
*
* See: outv_field() function
*/
void
out_set_col_width(unsigned col_width)
{
out_column_width = col_width;
}
/*
* out_set_vlevel -- set verbosity level
*/
void
out_set_vlevel(int vlevel)
{
out_vlevel = vlevel;
if (out_fh == NULL)
out_fh = stdout;
}
/*
* out_set_prefix -- set prefix to output format
*/
void
out_set_prefix(const char *prefix)
{
out_prefix = prefix;
}
/*
* out_set_stream -- set output stream
*/
void
out_set_stream(FILE *stream)
{
out_fh = stream;
memset(out_indent_str, INDENT_CHAR, MAX_INDENT);
}
/*
* outv_err -- print error message
*/
void
outv_err(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
outv_err_vargs(fmt, ap);
va_end(ap);
}
/*
* outv_err_vargs -- print error message
*/
void
outv_err_vargs(const char *fmt, va_list ap)
{
char *_str = strdup(fmt);
if (!_str)
err(1, "strdup");
char *str = _str;
fprintf(stderr, "error: ");
int errstr = str[0] == '!';
if (errstr)
str++;
char *nl = strchr(str, '\n');
if (nl)
*nl = '\0';
vfprintf(stderr, str, ap);
if (errstr)
fprintf(stderr, ": %s", strerror(errno));
fprintf(stderr, "\n");
free(_str);
}
/*
* outv_indent -- change indentation level by factor
*/
void
outv_indent(int vlevel, int i)
{
if (!outv_check(vlevel))
return;
out_indent_str[out_indent_level] = INDENT_CHAR;
out_indent_level += i;
if (out_indent_level < 0)
out_indent_level = 0;
if (out_indent_level > MAX_INDENT)
out_indent_level = MAX_INDENT;
out_indent_str[out_indent_level] = '\0';
}
/*
* _out_prefix -- print prefix if defined
*/
static void
_out_prefix(void)
{
if (out_prefix)
fprintf(out_fh, "%s: ", out_prefix);
}
/*
* _out_indent -- print indent
*/
static void
_out_indent(void)
{
fprintf(out_fh, "%s", out_indent_str);
}
/*
* outv -- print message taking into account verbosity level
*/
void
outv(int vlevel, const char *fmt, ...)
{
va_list ap;
if (!outv_check(vlevel))
return;
_out_prefix();
_out_indent();
va_start(ap, fmt);
vfprintf(out_fh, fmt, ap);
va_end(ap);
}
/*
* outv_nl -- print new line without indentation
*/
void
outv_nl(int vlevel)
{
if (!outv_check(vlevel))
return;
_out_prefix();
fprintf(out_fh, "\n");
}
void
outv_title(int vlevel, const char *fmt, ...)
{
va_list ap;
if (!outv_check(vlevel))
return;
fprintf(out_fh, "\n");
_out_prefix();
_out_indent();
va_start(ap, fmt);
vfprintf(out_fh, fmt, ap);
va_end(ap);
fprintf(out_fh, ":\n");
}
/*
* outv_field -- print field name and value in specified format
*
* Field name will have fixed width which can be changed by
* out_set_column_width() function.
* vlevel - verbosity level
* field - field name
* fmt - format form value
*/
void
outv_field(int vlevel, const char *field, const char *fmt, ...)
{
va_list ap;
if (!outv_check(vlevel))
return;
_out_prefix();
_out_indent();
va_start(ap, fmt);
fprintf(out_fh, "%-*s : ", out_column_width, field);
vfprintf(out_fh, fmt, ap);
fprintf(out_fh, "\n");
va_end(ap);
}
/*
* out_get_percentage -- return percentage string
*/
const char *
out_get_percentage(double perc)
{
static char str_buff[STR_MAX] = {0, };
int ret = 0;
if (perc > 0.0 && perc < 0.0001) {
ret = util_snprintf(str_buff, STR_MAX, "%e %%", perc);
if (ret < 0)
return "";
} else {
int decimal = 0;
if (perc >= 100.0 || perc < DBL_EPSILON)
decimal = 0;
else
decimal = 6;
ret = util_snprintf(str_buff, STR_MAX, "%.*f %%", decimal,
perc);
if (ret < 0)
return "";
}
return str_buff;
}
/*
* out_get_size_str -- return size string
*
* human - if 1 return size in human-readable format
* if 2 return size in bytes and human-readable format
* otherwise return size in bytes.
*/
const char *
out_get_size_str(uint64_t size, int human)
{
static char str_buff[STR_MAX] = {0, };
char units[] = {
'K', 'M', 'G', 'T', '\0'
};
const int nunits = sizeof(units) / sizeof(units[0]);
int ret = 0;
if (!human) {
ret = util_snprintf(str_buff, STR_MAX, "%"PRIu64, size);
} else {
int i = -1;
double dsize = (double)size;
uint64_t csize = size;
while (csize >= 1024 && i < nunits) {
csize /= 1024;
dsize /= 1024.0;
i++;
}
if (i >= 0 && i < nunits)
if (human == 1)
ret = util_snprintf(str_buff, STR_MAX,
"%.1f%c", dsize, units[i]);
else
ret = util_snprintf(str_buff, STR_MAX,
"%.1f%c [%" PRIu64"]", dsize,
units[i], size);
else
ret = util_snprintf(str_buff, STR_MAX, "%"PRIu64,
size);
}
if (ret < 0)
return "";
return str_buff;
}
/*
* out_get_uuid_str -- returns uuid in human readable format
*/
const char *
out_get_uuid_str(uuid_t uuid)
{
static char uuid_str[UUID_STR_MAX] = {0, };
int ret = util_uuid_to_string(uuid, uuid_str);
if (ret != 0) {
outv(2, "failed to covert uuid to string");
return NULL;
}
return uuid_str;
}
/*
* out_get_time_str -- returns time in human readable format
*/
const char *
out_get_time_str(time_t time)
{
static char str_buff[STR_MAX] = {0, };
struct tm *tm = util_localtime(&time);
if (tm) {
strftime(str_buff, STR_MAX, TIME_STR_FMT, tm);
} else {
int ret = util_snprintf(str_buff, STR_MAX, "unknown");
if (ret < 0)
return "";
}
return str_buff;
}
/*
* out_get_ascii_str -- get string with printable ASCII dump buffer
*
* Convert non-printable ASCII characters to dot '.'
* See: util_get_printable_ascii() function.
*/
static int
out_get_ascii_str(char *str, size_t str_len, const uint8_t *datap, size_t len)
{
int c = 0;
size_t i;
char pch;
if (str_len < len)
return -1;
for (i = 0; i < len; i++) {
pch = util_get_printable_ascii((char)datap[i]);
int t = util_snprintf(str + c, str_len - (size_t)c, "%c", pch);
if (t < 0)
return -1;
c += t;
}
return c;
}
/*
* out_get_hex_str -- get string with hexadecimal dump of buffer
*
* Hexadecimal bytes in format %02x, each one followed by space,
* additional space after every 8th byte.
*/
static int
out_get_hex_str(char *str, size_t str_len, const uint8_t *datap, size_t len)
{
int c = 0;
size_t i;
int t;
if (str_len < (3 * len + 1))
return -1;
for (i = 0; i < len; i++) {
/* add space after n*8 byte */
if (i && (i % 8) == 0) {
t = util_snprintf(str + c, str_len - (size_t)c, " ");
if (t < 0)
return -1;
c += t;
}
t = util_snprintf(str + c, str_len - (size_t)c, "%02x ",
datap[i]);
if (t < 0)
return -1;
c += t;
}
return c;
}
/*
* outv_hexdump -- print buffer in canonical hex+ASCII format
*
* Print offset in hexadecimal,
* sixteen space-separated, two column, hexadecimal bytes,
* followed by the same sixteen bytes converted to printable ASCII characters
* enclosed in '|' characters.
*/
void
outv_hexdump(int vlevel, const void *addr, size_t len, size_t offset, int sep)
{
if (!outv_check(vlevel) || len <= 0)
return;
const uint8_t *datap = (uint8_t *)addr;
uint8_t row_hex_str[HEXDUMP_ROW_HEX_LEN] = {0, };
uint8_t row_ascii_str[HEXDUMP_ROW_ASCII_LEN] = {0, };
size_t curr = 0;
size_t prev = 0;
int repeated = 0;
int n = 0;
while (len) {
size_t curr_len = min(len, HEXDUMP_ROW_WIDTH);
/*
* Check if current row is the same as the previous one
* don't check it for first and last rows.
*/
if (len != curr_len && curr &&
!memcmp(datap + prev, datap + curr, curr_len)) {
if (!repeated) {
/* print star only for the first repeated */
fprintf(out_fh, "*\n");
repeated = 1;
}
} else {
repeated = 0;
/* row with hexadecimal bytes */
int rh = out_get_hex_str((char *)row_hex_str,
HEXDUMP_ROW_HEX_LEN, datap + curr, curr_len);
/* row with printable ascii chars */
int ra = out_get_ascii_str((char *)row_ascii_str,
HEXDUMP_ROW_ASCII_LEN, datap + curr, curr_len);
if (ra && rh)
n = fprintf(out_fh, "%08zx %-*s|%-*s|\n",
curr + offset,
HEXDUMP_ROW_HEX_LEN, row_hex_str,
HEXDUMP_ROW_WIDTH, row_ascii_str);
prev = curr;
}
len -= curr_len;
curr += curr_len;
}
if (sep && n) {
while (--n)
fprintf(out_fh, "%c", SEPARATOR_CHAR);
fprintf(out_fh, "\n");
}
}
/*
* out_get_checksum -- return checksum string with result
*/
const char *
out_get_checksum(void *addr, size_t len, uint64_t *csump, size_t skip_off)
{
static char str_buff[STR_MAX] = {0, };
int ret = 0;
uint64_t csum = util_checksum_compute(addr, len, csump, skip_off);
if (*csump == htole64(csum))
ret = util_snprintf(str_buff, STR_MAX, "0x%" PRIx64" [OK]",
le64toh(csum));
else
ret = util_snprintf(str_buff, STR_MAX,
"0x%" PRIx64 " [wrong! should be: 0x%" PRIx64 "]",
le64toh(*csump), le64toh(csum));
if (ret < 0)
return "";
return str_buff;
}
/*
* out_get_btt_map_entry -- return BTT map entry with flags strings
*/
const char *
out_get_btt_map_entry(uint32_t map)
{
static char str_buff[STR_MAX] = {0, };
int is_init = (map & ~BTT_MAP_ENTRY_LBA_MASK) == 0;
int is_zero = (map & ~BTT_MAP_ENTRY_LBA_MASK) ==
BTT_MAP_ENTRY_ZERO;
int is_error = (map & ~BTT_MAP_ENTRY_LBA_MASK) ==
BTT_MAP_ENTRY_ERROR;
int is_normal = (map & ~BTT_MAP_ENTRY_LBA_MASK) ==
BTT_MAP_ENTRY_NORMAL;
uint32_t lba = map & BTT_MAP_ENTRY_LBA_MASK;
int ret = util_snprintf(str_buff, STR_MAX, "0x%08x state: %s", lba,
is_init ? "init" :
is_zero ? "zero" :
is_error ? "error" :
is_normal ? "normal" : "unknown");
if (ret < 0)
return "";
return str_buff;
}
/*
* out_get_pool_type_str -- get pool type string
*/
const char *
out_get_pool_type_str(pmem_pool_type_t type)
{
switch (type) {
case PMEM_POOL_TYPE_LOG:
return "log";
case PMEM_POOL_TYPE_BLK:
return "blk";
case PMEM_POOL_TYPE_OBJ:
return "obj";
case PMEM_POOL_TYPE_BTT:
return "btt";
default:
return "unknown";
}
}
/*
* out_get_pool_signature -- return signature of specified pool type
*/
const char *
out_get_pool_signature(pmem_pool_type_t type)
{
switch (type) {
case PMEM_POOL_TYPE_LOG:
return LOG_HDR_SIG;
case PMEM_POOL_TYPE_BLK:
return BLK_HDR_SIG;
case PMEM_POOL_TYPE_OBJ:
return OBJ_HDR_SIG;
default:
return NULL;
}
}
/*
* out_get_chunk_type_str -- get chunk type string
*/
const char *
out_get_chunk_type_str(enum chunk_type type)
{
switch (type) {
case CHUNK_TYPE_FOOTER:
return "footer";
case CHUNK_TYPE_FREE:
return "free";
case CHUNK_TYPE_USED:
return "used";
case CHUNK_TYPE_RUN:
return "run";
case CHUNK_TYPE_UNKNOWN:
default:
return "unknown";
}
}
/*
* out_get_chunk_flags -- get names of set flags for chunk header
*/
const char *
out_get_chunk_flags(uint16_t flags)
{
if (flags & CHUNK_FLAG_COMPACT_HEADER)
return "compact header";
else if (flags & CHUNK_FLAG_HEADER_NONE)
return "header none";
return "";
}
/*
* out_get_zone_magic_str -- get zone magic string with additional
* information about correctness of the magic value
*/
const char *
out_get_zone_magic_str(uint32_t magic)
{
static char str_buff[STR_MAX] = {0, };
const char *correct = NULL;
switch (magic) {
case 0:
correct = "uninitialized";
break;
case ZONE_HEADER_MAGIC:
correct = "OK";
break;
default:
correct = "wrong! should be " STR(ZONE_HEADER_MAGIC);
break;
}
int ret = util_snprintf(str_buff, STR_MAX, "0x%08x [%s]", magic,
correct);
if (ret < 0)
return "";
return str_buff;
}
/*
* out_get_pmemoid_str -- get PMEMoid string
*/
const char *
out_get_pmemoid_str(PMEMoid oid, uint64_t uuid_lo)
{
static char str_buff[STR_MAX] = {0, };
int free_cor = 0;
int ret = 0;
char *correct = "OK";
if (oid.pool_uuid_lo && oid.pool_uuid_lo != uuid_lo) {
ret = util_snprintf(str_buff, STR_MAX,
"wrong! should be 0x%016"PRIx64, uuid_lo);
if (ret < 0)
err(1, "snprintf: %d", ret);
correct = strdup(str_buff);
if (!correct)
err(1, "Cannot allocate memory for PMEMoid string\n");
free_cor = 1;
}
ret = util_snprintf(str_buff, STR_MAX,
"off: 0x%016"PRIx64" pool_uuid_lo: 0x%016"
PRIx64" [%s]", oid.off, oid.pool_uuid_lo, correct);
if (free_cor)
free(correct);
if (ret < 0)
err(1, "snprintf: %d", ret);
return str_buff;
}
/*
* out_get_arch_machine_class_str -- get a string representation of the machine
* class
*/
const char *
out_get_arch_machine_class_str(uint8_t machine_class)
{
switch (machine_class) {
case PMDK_MACHINE_CLASS_64:
return "64";
default:
return "unknown";
}
}
/*
* out_get_arch_data_str -- get a string representation of the data endianness
*/
const char *
out_get_arch_data_str(uint8_t data)
{
switch (data) {
case PMDK_DATA_LE:
return "2's complement, little endian";
case PMDK_DATA_BE:
return "2's complement, big endian";
default:
return "unknown";
}
}
/*
* out_get_arch_machine_str -- get a string representation of the machine type
*/
const char *
out_get_arch_machine_str(uint16_t machine)
{
static char str_buff[STR_MAX] = {0, };
switch (machine) {
case PMDK_MACHINE_X86_64:
return "AMD X86-64";
case PMDK_MACHINE_AARCH64:
return "Aarch64";
case PMDK_MACHINE_PPC64:
return "PPC64";
default:
break;
}
int ret = util_snprintf(str_buff, STR_MAX, "unknown %u", machine);
if (ret < 0)
return "unknown";
return str_buff;
}
/*
* out_get_last_shutdown_str -- get a string representation of the finish state
*/
const char *
out_get_last_shutdown_str(uint8_t dirty)
{
if (dirty)
return "dirty";
else
return "clean";
}
/*
* out_get_alignment_descr_str -- get alignment descriptor string
*/
const char *
out_get_alignment_desc_str(uint64_t ad, uint64_t valid_ad)
{
static char str_buff[STR_MAX] = {0, };
int ret = 0;
if (ad == valid_ad)
ret = util_snprintf(str_buff, STR_MAX, "0x%016"PRIx64"[OK]",
ad);
else
ret = util_snprintf(str_buff, STR_MAX, "0x%016"PRIx64" "
"[wrong! should be 0x%016"PRIx64"]", ad, valid_ad);
if (ret < 0)
return "";
return str_buff;
}
/*
* out_concat -- concatenate the new element to the list of strings
*
* If concatenation is successful it increments current position in the output
* string and number of elements in the list. Elements are separated with ", ".
*/
static int
out_concat(char *str_buff, int *curr, int *count, const char *str)
{
ASSERTne(str_buff, NULL);
ASSERTne(curr, NULL);
ASSERTne(str, NULL);
const char *separator = (count != NULL && *count > 0) ? ", " : "";
int ret = util_snprintf(str_buff + *curr,
(size_t)(STR_MAX - *curr), "%s%s", separator, str);
if (ret < 0)
return -1;
*curr += ret;
if (count)
++(*count);
return 0;
}
/*
* out_get_incompat_features_str -- (internal) get a string with names of
* incompatibility flags
*/
const char *
out_get_incompat_features_str(uint32_t incompat)
{
static char str_buff[STR_MAX] = {0};
features_t features = {POOL_FEAT_ZERO, incompat, POOL_FEAT_ZERO};
int ret = 0;
if (incompat == 0) {
/* print the value only */
return "0x0";
} else {
/* print the value and the left square bracket */
ret = util_snprintf(str_buff, STR_MAX, "0x%x [", incompat);
if (ret < 0) {
ERR("snprintf for incompat features: %d", ret);
return "<error>";
}
/* print names of known options */
int count = 0;
int curr = ret;
features_t found;
const char *feat;
while (((feat = util_feature2str(features, &found))) != NULL) {
util_feature_disable(&features, found);
ret = out_concat(str_buff, &curr, &count, feat);
if (ret < 0)
return "";
}
/* check if any unknown flags are set */
if (!util_feature_is_zero(features)) {
if (out_concat(str_buff, &curr, &count,
"?UNKNOWN_FLAG?"))
return "";
}
/* print the right square bracket */
if (out_concat(str_buff, &curr, NULL, "]"))
return "";
}
return str_buff;
}
| 16,852 | 18.944379 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/dump.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* dump.h -- pmempool dump command header file
*/
int pmempool_dump_func(const char *appname, int argc, char *argv[]);
void pmempool_dump_help(const char *appname);
| 257 | 24.8 | 68 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/rm.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* rm.h -- pmempool rm command header file
*/
void pmempool_rm_help(const char *appname);
int pmempool_rm_func(const char *appname, int argc, char *argv[]);
| 249 | 24 | 66 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/feature.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018, Intel Corporation */
/*
* feature.h -- pmempool feature command header file
*/
int pmempool_feature_func(const char *appname, int argc, char *argv[]);
void pmempool_feature_help(const char *appname);
| 264 | 25.5 | 71 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/feature.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2019, Intel Corporation */
/*
* feature.c -- pmempool feature command source file
*/
#include <getopt.h>
#include <stdlib.h>
#include "common.h"
#include "feature.h"
#include "output.h"
#include "libpmempool.h"
/* operations over features */
enum feature_op {
undefined,
enable,
disable,
query
};
/*
* feature_ctx -- context and arguments for feature command
*/
struct feature_ctx {
int verbose;
const char *fname;
enum feature_op op;
enum pmempool_feature feature;
unsigned flags;
};
/*
* pmempool_feature_default -- default arguments for feature command
*/
static const struct feature_ctx pmempool_feature_default = {
.verbose = 0,
.fname = NULL,
.op = undefined,
.feature = UINT32_MAX,
.flags = 0
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Toggle or query a pool feature\n"
"\n"
"For complete documentation see %s-feature(1) manual page.\n"
;
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"enable", required_argument, NULL, 'e'},
{"disable", required_argument, NULL, 'd'},
{"query", required_argument, NULL, 'q'},
{"verbose", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 },
};
/*
* print_usage -- print short description of application's usage
*/
static void
print_usage(const char *appname)
{
printf("Usage: %s feature [<args>] <file>\n", appname);
printf(
"feature: SINGLEHDR, CKSUM_2K, SHUTDOWN_STATE, CHECK_BAD_BLOCKS\n");
}
/*
* print_version -- print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_feature_help -- print help message for feature command
*/
void
pmempool_feature_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* feature_perform -- perform operation over function
*/
static int
feature_perform(struct feature_ctx *pfp)
{
int ret;
switch (pfp->op) {
case enable:
return pmempool_feature_enable(pfp->fname, pfp->feature,
pfp->flags);
case disable:
return pmempool_feature_disable(pfp->fname, pfp->feature,
pfp->flags);
case query:
ret = pmempool_feature_query(pfp->fname, pfp->feature,
pfp->flags);
if (ret < 0)
return 1;
printf("%d", ret);
return 0;
default:
outv_err("Invalid option.");
return -1;
}
}
/*
* set_op -- set operation
*/
static void
set_op(const char *appname, struct feature_ctx *pfp, enum feature_op op,
const char *feature)
{
/* only one operation allowed */
if (pfp->op != undefined)
goto misuse;
pfp->op = op;
/* parse feature name */
uint32_t fval = util_str2pmempool_feature(feature);
if (fval == UINT32_MAX)
goto misuse;
pfp->feature = (enum pmempool_feature)fval;
return;
misuse:
print_usage(appname);
exit(EXIT_FAILURE);
}
/*
* parse_args -- parse command line arguments
*/
static int
parse_args(struct feature_ctx *pfp, const char *appname,
int argc, char *argv[])
{
int opt;
while ((opt = getopt_long(argc, argv, "vhe:d:q:h",
long_options, NULL)) != -1) {
switch (opt) {
case 'e':
set_op(appname, pfp, enable, optarg);
break;
case 'd':
set_op(appname, pfp, disable, optarg);
break;
case 'q':
set_op(appname, pfp, query, optarg);
break;
case 'v':
pfp->verbose = 2;
break;
case 'h':
pmempool_feature_help(appname);
exit(EXIT_SUCCESS);
default:
print_usage(appname);
exit(EXIT_FAILURE);
}
}
if (optind >= argc) {
print_usage(appname);
exit(EXIT_FAILURE);
}
pfp->fname = argv[optind];
return 0;
}
/*
* pmempool_feature_func -- main function for feature command
*/
int
pmempool_feature_func(const char *appname, int argc, char *argv[])
{
struct feature_ctx pf = pmempool_feature_default;
int ret = 0;
/* parse command line arguments */
ret = parse_args(&pf, appname, argc, argv);
if (ret)
return ret;
/* set verbosity level */
out_set_vlevel(pf.verbose);
return feature_perform(&pf);
}
| 4,057 | 18.509615 | 72 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/check.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* check.c -- pmempool check command source file
*/
#include <getopt.h>
#include <stdlib.h>
#include "common.h"
#include "check.h"
#include "output.h"
#include "set.h"
#include "file.h"
#include "libpmempool.h"
typedef enum
{
CHECK_RESULT_CONSISTENT,
CHECK_RESULT_NOT_CONSISTENT,
CHECK_RESULT_REPAIRED,
CHECK_RESULT_CANNOT_REPAIR,
CHECK_RESULT_SYNC_REQ,
CHECK_RESULT_ERROR
} check_result_t;
/*
* pmempool_check_context -- context and arguments for check command
*/
struct pmempool_check_context {
int verbose; /* verbosity level */
char *fname; /* file name */
struct pool_set_file *pfile;
bool repair; /* do repair */
bool backup; /* do backup */
bool advanced; /* do advanced repairs */
char *backup_fname; /* backup file name */
bool exec; /* do execute */
char ans; /* default answer on all questions or '?' */
};
/*
* pmempool_check_default -- default arguments for check command
*/
static const struct pmempool_check_context pmempool_check_default = {
.verbose = 1,
.fname = NULL,
.repair = false,
.backup = false,
.backup_fname = NULL,
.advanced = false,
.exec = true,
.ans = '?',
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Check consistency of a pool\n"
"\n"
"Common options:\n"
" -r, --repair try to repair a pool file if possible\n"
" -y, --yes answer yes to all questions\n"
" -d, --dry-run don't execute, just show what would be done\n"
" -b, --backup <file> create backup of a pool file before executing\n"
" -a, --advanced perform advanced repairs\n"
" -q, --quiet be quiet and don't print any messages\n"
" -v, --verbose increase verbosity level\n"
" -h, --help display this help and exit\n"
"\n"
"For complete documentation see %s-check(1) manual page.\n"
;
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"repair", no_argument, NULL, 'r'},
{"yes", no_argument, NULL, 'y'},
{"dry-run", no_argument, NULL, 'd'},
{"no-exec", no_argument, NULL, 'N'}, /* deprecated */
{"backup", required_argument, NULL, 'b'},
{"advanced", no_argument, NULL, 'a'},
{"quiet", no_argument, NULL, 'q'},
{"verbose", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 },
};
/*
* print_usage -- print short description of application's usage
*/
static void
print_usage(const char *appname)
{
printf("Usage: %s check [<args>] <file>\n", appname);
}
/*
* print_version -- print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_check_help -- print help message for check command
*/
void
pmempool_check_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* pmempool_check_parse_args -- parse command line arguments
*/
static int
pmempool_check_parse_args(struct pmempool_check_context *pcp,
const char *appname, int argc, char *argv[])
{
int opt;
while ((opt = getopt_long(argc, argv, "ahvrdNb:qy",
long_options, NULL)) != -1) {
switch (opt) {
case 'r':
pcp->repair = true;
break;
case 'y':
pcp->ans = 'y';
break;
case 'd':
case 'N':
pcp->exec = false;
break;
case 'b':
pcp->backup = true;
pcp->backup_fname = optarg;
break;
case 'a':
pcp->advanced = true;
break;
case 'q':
pcp->verbose = 0;
break;
case 'v':
pcp->verbose = 2;
break;
case 'h':
pmempool_check_help(appname);
exit(EXIT_SUCCESS);
default:
print_usage(appname);
exit(EXIT_FAILURE);
}
}
if (optind < argc) {
pcp->fname = argv[optind];
} else {
print_usage(appname);
exit(EXIT_FAILURE);
}
if (!pcp->repair && !pcp->exec) {
outv_err("'-N' option requires '-r'\n");
exit(EXIT_FAILURE);
}
if (!pcp->repair && pcp->backup) {
outv_err("'-b' option requires '-r'\n");
exit(EXIT_FAILURE);
}
return 0;
}
static check_result_t pmempool_check_2_check_res_t[] =
{
[PMEMPOOL_CHECK_RESULT_CONSISTENT] = CHECK_RESULT_CONSISTENT,
[PMEMPOOL_CHECK_RESULT_NOT_CONSISTENT] = CHECK_RESULT_NOT_CONSISTENT,
[PMEMPOOL_CHECK_RESULT_REPAIRED] = CHECK_RESULT_REPAIRED,
[PMEMPOOL_CHECK_RESULT_CANNOT_REPAIR] = CHECK_RESULT_CANNOT_REPAIR,
[PMEMPOOL_CHECK_RESULT_SYNC_REQ] = CHECK_RESULT_SYNC_REQ,
[PMEMPOOL_CHECK_RESULT_ERROR] = CHECK_RESULT_ERROR,
};
static const char *
check_ask(const char *msg)
{
char answer = ask_Yn('?', "%s", msg);
switch (answer) {
case 'y':
return "yes";
case 'n':
return "no";
default:
return "?";
}
}
static check_result_t
pmempool_check_perform(struct pmempool_check_context *pc)
{
struct pmempool_check_args args = {
.path = pc->fname,
.backup_path = pc->backup_fname,
.pool_type = PMEMPOOL_POOL_TYPE_DETECT,
.flags = PMEMPOOL_CHECK_FORMAT_STR
};
if (pc->repair)
args.flags |= PMEMPOOL_CHECK_REPAIR;
if (!pc->exec)
args.flags |= PMEMPOOL_CHECK_DRY_RUN;
if (pc->advanced)
args.flags |= PMEMPOOL_CHECK_ADVANCED;
if (pc->ans == 'y')
args.flags |= PMEMPOOL_CHECK_ALWAYS_YES;
if (pc->verbose == 2)
args.flags |= PMEMPOOL_CHECK_VERBOSE;
PMEMpoolcheck *ppc = pmempool_check_init(&args, sizeof(args));
if (ppc == NULL)
return CHECK_RESULT_ERROR;
struct pmempool_check_status *status = NULL;
while ((status = pmempool_check(ppc)) != NULL) {
switch (status->type) {
case PMEMPOOL_CHECK_MSG_TYPE_ERROR:
outv(1, "%s\n", status->str.msg);
break;
case PMEMPOOL_CHECK_MSG_TYPE_INFO:
outv(2, "%s\n", status->str.msg);
break;
case PMEMPOOL_CHECK_MSG_TYPE_QUESTION:
status->str.answer = check_ask(status->str.msg);
break;
default:
pmempool_check_end(ppc);
exit(EXIT_FAILURE);
}
}
enum pmempool_check_result ret = pmempool_check_end(ppc);
return pmempool_check_2_check_res_t[ret];
}
/*
* pmempool_check_func -- main function for check command
*/
int
pmempool_check_func(const char *appname, int argc, char *argv[])
{
int ret = 0;
check_result_t res = CHECK_RESULT_CONSISTENT;
struct pmempool_check_context pc = pmempool_check_default;
/* parse command line arguments */
ret = pmempool_check_parse_args(&pc, appname, argc, argv);
if (ret)
return ret;
/* set verbosity level */
out_set_vlevel(pc.verbose);
res = pmempool_check_perform(&pc);
switch (res) {
case CHECK_RESULT_CONSISTENT:
outv(2, "%s: consistent\n", pc.fname);
ret = 0;
break;
case CHECK_RESULT_NOT_CONSISTENT:
outv(1, "%s: not consistent\n", pc.fname);
ret = -1;
break;
case CHECK_RESULT_REPAIRED:
outv(1, "%s: repaired\n", pc.fname);
ret = 0;
break;
case CHECK_RESULT_CANNOT_REPAIR:
outv(1, "%s: cannot repair\n", pc.fname);
ret = -1;
break;
case CHECK_RESULT_SYNC_REQ:
outv(1, "%s: sync required\n", pc.fname);
ret = 0;
break;
case CHECK_RESULT_ERROR:
if (errno)
outv_err("%s\n", strerror(errno));
if (pc.repair)
outv_err("repairing failed\n");
else
outv_err("checking consistency failed\n");
ret = -1;
break;
default:
outv_err("status unknown\n");
ret = -1;
break;
}
return ret;
}
| 7,163 | 21.670886 | 72 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/convert.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* convert.h -- pmempool convert command header file
*/
#include <sys/types.h>
int pmempool_convert_func(const char *appname, int argc, char *argv[]);
void pmempool_convert_help(const char *appname);
| 293 | 23.5 | 71 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/info.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* info.c -- pmempool info command main source file
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdbool.h>
#include <err.h>
#include <errno.h>
#include <inttypes.h>
#include <assert.h>
#include <sys/param.h>
#include <unistd.h>
#include <sys/mman.h>
#include "common.h"
#include "output.h"
#include "out.h"
#include "info.h"
#include "set.h"
#include "file.h"
#include "badblocks.h"
#include "set_badblocks.h"
#define DEFAULT_CHUNK_TYPES\
((1<<CHUNK_TYPE_FREE)|\
(1<<CHUNK_TYPE_USED)|\
(1<<CHUNK_TYPE_RUN))
#define GET_ALIGNMENT(ad, x)\
(1 + (((ad) >> (ALIGNMENT_DESC_BITS * (x))) & ((1 << ALIGNMENT_DESC_BITS) - 1)))
#define UNDEF_REPLICA UINT_MAX
#define UNDEF_PART UINT_MAX
/*
* Default arguments
*/
static const struct pmempool_info_args pmempool_info_args_default = {
/*
* Picked experimentally based on used fields names.
* This should be at least the number of characters of
* the longest field name.
*/
.col_width = 24,
.human = false,
.force = false,
.badblocks = PRINT_BAD_BLOCKS_NOT_SET,
.type = PMEM_POOL_TYPE_UNKNOWN,
.vlevel = VERBOSE_DEFAULT,
.vdata = VERBOSE_SILENT,
.vhdrdump = VERBOSE_SILENT,
.vstats = VERBOSE_SILENT,
.log = {
.walk = 0,
},
.blk = {
.vmap = VERBOSE_SILENT,
.vflog = VERBOSE_SILENT,
.vbackup = VERBOSE_SILENT,
.skip_zeros = false,
.skip_error = false,
.skip_no_flag = false,
},
.obj = {
.vlanes = VERBOSE_SILENT,
.vroot = VERBOSE_SILENT,
.vobjects = VERBOSE_SILENT,
.valloc = VERBOSE_SILENT,
.voobhdr = VERBOSE_SILENT,
.vheap = VERBOSE_SILENT,
.vzonehdr = VERBOSE_SILENT,
.vchunkhdr = VERBOSE_SILENT,
.vbitmap = VERBOSE_SILENT,
.lanes_recovery = false,
.ignore_empty_obj = false,
.chunk_types = DEFAULT_CHUNK_TYPES,
.replica = 0,
},
};
/*
* long-options -- structure holding long options.
*/
static const struct option long_options[] = {
{"version", no_argument, NULL, 'V' | OPT_ALL},
{"verbose", no_argument, NULL, 'v' | OPT_ALL},
{"help", no_argument, NULL, 'h' | OPT_ALL},
{"human", no_argument, NULL, 'n' | OPT_ALL},
{"force", required_argument, NULL, 'f' | OPT_ALL},
{"data", no_argument, NULL, 'd' | OPT_ALL},
{"headers-hex", no_argument, NULL, 'x' | OPT_ALL},
{"stats", no_argument, NULL, 's' | OPT_ALL},
{"range", required_argument, NULL, 'r' | OPT_ALL},
{"bad-blocks", required_argument, NULL, 'k' | OPT_ALL},
{"walk", required_argument, NULL, 'w' | OPT_LOG},
{"skip-zeros", no_argument, NULL, 'z' | OPT_BLK | OPT_BTT},
{"skip-error", no_argument, NULL, 'e' | OPT_BLK | OPT_BTT},
{"skip-no-flag", no_argument, NULL, 'u' | OPT_BLK | OPT_BTT},
{"map", no_argument, NULL, 'm' | OPT_BLK | OPT_BTT},
{"flog", no_argument, NULL, 'g' | OPT_BLK | OPT_BTT},
{"backup", no_argument, NULL, 'B' | OPT_BLK | OPT_BTT},
{"lanes", no_argument, NULL, 'l' | OPT_OBJ},
{"recovery", no_argument, NULL, 'R' | OPT_OBJ},
{"section", required_argument, NULL, 'S' | OPT_OBJ},
{"object-store", no_argument, NULL, 'O' | OPT_OBJ},
{"types", required_argument, NULL, 't' | OPT_OBJ},
{"no-empty", no_argument, NULL, 'E' | OPT_OBJ},
{"alloc-header", no_argument, NULL, 'A' | OPT_OBJ},
{"oob-header", no_argument, NULL, 'a' | OPT_OBJ},
{"root", no_argument, NULL, 'o' | OPT_OBJ},
{"heap", no_argument, NULL, 'H' | OPT_OBJ},
{"zones", no_argument, NULL, 'Z' | OPT_OBJ},
{"chunks", no_argument, NULL, 'C' | OPT_OBJ},
{"chunk-type", required_argument, NULL, 'T' | OPT_OBJ},
{"bitmap", no_argument, NULL, 'b' | OPT_OBJ},
{"replica", required_argument, NULL, 'p' | OPT_OBJ},
{NULL, 0, NULL, 0 },
};
static const struct option_requirement option_requirements[] = {
{
.opt = 'r',
.type = PMEM_POOL_TYPE_LOG,
.req = OPT_REQ0('d')
},
{
.opt = 'r',
.type = PMEM_POOL_TYPE_BLK | PMEM_POOL_TYPE_BTT,
.req = OPT_REQ0('d') | OPT_REQ1('m')
},
{
.opt = 'z',
.type = PMEM_POOL_TYPE_BLK | PMEM_POOL_TYPE_BTT,
.req = OPT_REQ0('d') | OPT_REQ1('m')
},
{
.opt = 'e',
.type = PMEM_POOL_TYPE_BLK | PMEM_POOL_TYPE_BTT,
.req = OPT_REQ0('d') | OPT_REQ1('m')
},
{
.opt = 'u',
.type = PMEM_POOL_TYPE_BLK | PMEM_POOL_TYPE_BTT,
.req = OPT_REQ0('d') | OPT_REQ1('m')
},
{
.opt = 'r',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('O') | OPT_REQ1('Z') |
OPT_REQ2('C') | OPT_REQ3('l'),
},
{
.opt = 'R',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('l')
},
{
.opt = 'S',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('l')
},
{
.opt = 'E',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('O')
},
{
.opt = 'T',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('C')
},
{
.opt = 'b',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('H')
},
{
.opt = 'b',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('C')
},
{
.opt = 'A',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('O') | OPT_REQ1('l') | OPT_REQ2('o')
},
{
.opt = 'a',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('O') | OPT_REQ1('l') | OPT_REQ2('o')
},
{
.opt = 't',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('O') | OPT_REQ1('s'),
},
{
.opt = 'C',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('O') | OPT_REQ1('H') | OPT_REQ2('s'),
},
{
.opt = 'Z',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('O') | OPT_REQ1('H') | OPT_REQ2('s'),
},
{
.opt = 'd',
.type = PMEM_POOL_TYPE_OBJ,
.req = OPT_REQ0('O') | OPT_REQ1('o'),
},
{ 0, 0, 0}
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Show information about pmem pool from specified file.\n"
"\n"
"Common options:\n"
" -h, --help Print this help and exit.\n"
" -V, --version Print version and exit.\n"
" -v, --verbose Increase verbisity level.\n"
" -f, --force blk|log|obj|btt Force parsing a pool of specified type.\n"
" -n, --human Print sizes in human readable format.\n"
" -x, --headers-hex Hexdump all headers.\n"
" -d, --data Dump log data and blocks.\n"
" -s, --stats Print statistics.\n"
" -r, --range <range> Range of blocks/chunks/objects.\n"
" -k, --bad-blocks=<yes|no> Print bad blocks.\n"
"\n"
"Options for PMEMLOG:\n"
" -w, --walk <size> Chunk size.\n"
"\n"
"Options for PMEMBLK:\n"
" -m, --map Print BTT Map entries.\n"
" -g, --flog Print BTT FLOG entries.\n"
" -B, --backup Print BTT Info header backup.\n"
" -z, --skip-zeros Skip blocks marked with zero flag.\n"
" -e, --skip-error Skip blocks marked with error flag.\n"
" -u, --skip-no-flag Skip blocks not marked with any flag.\n"
"\n"
"Options for PMEMOBJ:\n"
" -l, --lanes [<range>] Print lanes from specified range.\n"
" -R, --recovery Print only lanes which need recovery.\n"
" -S, --section tx,allocator,list Print only specified sections.\n"
" -O, --object-store Print object store.\n"
" -t, --types <range> Specify objects' type numbers range.\n"
" -E, --no-empty Print only non-empty object store lists.\n"
" -o, --root Print root object information\n"
" -A, --alloc-header Print allocation header for objects in\n"
" object store.\n"
" -a, --oob-header Print OOB header\n"
" -H, --heap Print heap header.\n"
" -Z, --zones [<range>] Print zones header. If range is specified\n"
" and --object|-O option is specified prints\n"
" objects from specified zones only.\n"
" -C, --chunks [<range>] Print zones header. If range is specified\n"
" and --object|-O option is specified prints\n"
" objects from specified zones only.\n"
" -T, --chunk-type used,free,run,footer\n"
" Print only specified type(s) of chunk.\n"
" [requires --chunks|-C]\n"
" -b, --bitmap Print chunk run's bitmap in graphical\n"
" format. [requires --chunks|-C]\n"
" -p, --replica <num> Print info from specified replica\n"
"For complete documentation see %s-info(1) manual page.\n"
;
/*
* print_usage -- print application usage short description
*/
static void
print_usage(const char *appname)
{
printf("Usage: %s info [<args>] <file>\n", appname);
}
/*
* print_version -- print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_info_help -- print application usage detailed description
*/
void
pmempool_info_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* parse_args -- parse command line arguments
*
* Parse command line arguments and store them in pmempool_info_args
* structure.
* Terminates process if invalid arguments passed.
*/
static int
parse_args(const char *appname, int argc, char *argv[],
struct pmempool_info_args *argsp,
struct options *opts)
{
int opt;
if (argc == 1) {
print_usage(appname);
return -1;
}
struct ranges *rangesp = &argsp->ranges;
while ((opt = util_options_getopt(argc, argv,
"vhnf:ezuF:L:c:dmxVw:gBsr:lRS:OECZHT:bot:aAp:k:",
opts)) != -1) {
switch (opt) {
case 'v':
argsp->vlevel = VERBOSE_MAX;
break;
case 'V':
print_version(appname);
exit(EXIT_SUCCESS);
case 'h':
pmempool_info_help(appname);
exit(EXIT_SUCCESS);
case 'n':
argsp->human = true;
break;
case 'f':
argsp->type = pmem_pool_type_parse_str(optarg);
if (argsp->type == PMEM_POOL_TYPE_UNKNOWN) {
outv_err("'%s' -- unknown pool type\n", optarg);
return -1;
}
argsp->force = true;
break;
case 'k':
if (strcmp(optarg, "no") == 0) {
argsp->badblocks = PRINT_BAD_BLOCKS_NO;
} else if (strcmp(optarg, "yes") == 0) {
argsp->badblocks = PRINT_BAD_BLOCKS_YES;
} else {
outv_err(
"'%s' -- invalid argument of the '-k/--bad-blocks' option\n",
optarg);
return -1;
}
break;
case 'e':
argsp->blk.skip_error = true;
break;
case 'z':
argsp->blk.skip_zeros = true;
break;
case 'u':
argsp->blk.skip_no_flag = true;
break;
case 'r':
if (util_parse_ranges(optarg, rangesp,
ENTIRE_UINT64)) {
outv_err("'%s' -- cannot parse range(s)\n",
optarg);
return -1;
}
if (rangesp == &argsp->ranges)
argsp->use_range = 1;
break;
case 'd':
argsp->vdata = VERBOSE_DEFAULT;
break;
case 'm':
argsp->blk.vmap = VERBOSE_DEFAULT;
break;
case 'g':
argsp->blk.vflog = VERBOSE_DEFAULT;
break;
case 'B':
argsp->blk.vbackup = VERBOSE_DEFAULT;
break;
case 'x':
argsp->vhdrdump = VERBOSE_DEFAULT;
break;
case 's':
argsp->vstats = VERBOSE_DEFAULT;
break;
case 'w':
argsp->log.walk = (size_t)atoll(optarg);
if (argsp->log.walk == 0) {
outv_err("'%s' -- invalid chunk size\n",
optarg);
return -1;
}
break;
case 'l':
argsp->obj.vlanes = VERBOSE_DEFAULT;
rangesp = &argsp->obj.lane_ranges;
break;
case 'R':
argsp->obj.lanes_recovery = true;
break;
case 'O':
argsp->obj.vobjects = VERBOSE_DEFAULT;
rangesp = &argsp->ranges;
break;
case 'a':
argsp->obj.voobhdr = VERBOSE_DEFAULT;
break;
case 'A':
argsp->obj.valloc = VERBOSE_DEFAULT;
break;
case 'E':
argsp->obj.ignore_empty_obj = true;
break;
case 'Z':
argsp->obj.vzonehdr = VERBOSE_DEFAULT;
rangesp = &argsp->obj.zone_ranges;
break;
case 'C':
argsp->obj.vchunkhdr = VERBOSE_DEFAULT;
rangesp = &argsp->obj.chunk_ranges;
break;
case 'H':
argsp->obj.vheap = VERBOSE_DEFAULT;
break;
case 'T':
argsp->obj.chunk_types = 0;
if (util_parse_chunk_types(optarg,
&argsp->obj.chunk_types) ||
(argsp->obj.chunk_types &
(1 << CHUNK_TYPE_UNKNOWN))) {
outv_err("'%s' -- cannot parse chunk type(s)\n",
optarg);
return -1;
}
break;
case 'o':
argsp->obj.vroot = VERBOSE_DEFAULT;
break;
case 't':
if (util_parse_ranges(optarg,
&argsp->obj.type_ranges, ENTIRE_UINT64)) {
outv_err("'%s' -- cannot parse range(s)\n",
optarg);
return -1;
}
break;
case 'b':
argsp->obj.vbitmap = VERBOSE_DEFAULT;
break;
case 'p':
{
char *endptr;
int olderrno = errno;
errno = 0;
long long ll = strtoll(optarg, &endptr, 10);
if ((endptr && *endptr != '\0') || errno) {
outv_err("'%s' -- invalid replica number",
optarg);
return -1;
}
errno = olderrno;
argsp->obj.replica = (size_t)ll;
break;
}
default:
print_usage(appname);
return -1;
}
}
if (optind < argc) {
argsp->file = argv[optind];
} else {
print_usage(appname);
return -1;
}
if (!argsp->use_range)
util_ranges_add(&argsp->ranges, ENTIRE_UINT64);
if (util_ranges_empty(&argsp->obj.type_ranges))
util_ranges_add(&argsp->obj.type_ranges, ENTIRE_UINT64);
if (util_ranges_empty(&argsp->obj.lane_ranges))
util_ranges_add(&argsp->obj.lane_ranges, ENTIRE_UINT64);
if (util_ranges_empty(&argsp->obj.zone_ranges))
util_ranges_add(&argsp->obj.zone_ranges, ENTIRE_UINT64);
if (util_ranges_empty(&argsp->obj.chunk_ranges))
util_ranges_add(&argsp->obj.chunk_ranges, ENTIRE_UINT64);
return 0;
}
/*
* pmempool_info_read -- read data from file
*/
int
pmempool_info_read(struct pmem_info *pip, void *buff, size_t nbytes,
uint64_t off)
{
return pool_set_file_read(pip->pfile, buff, nbytes, off);
}
/*
* pmempool_info_badblocks -- (internal) prints info about file badblocks
*/
static int
pmempool_info_badblocks(struct pmem_info *pip, const char *file_name, int v)
{
int ret;
if (pip->args.badblocks != PRINT_BAD_BLOCKS_YES)
return 0;
struct badblocks *bbs = badblocks_new();
if (bbs == NULL)
return -1;
ret = badblocks_get(file_name, bbs);
if (ret) {
if (errno == ENOTSUP) {
outv(v, BB_NOT_SUPP "\n");
ret = -1;
goto exit_free;
}
outv_err("checking bad blocks failed -- '%s'", file_name);
goto exit_free;
}
if (bbs->bb_cnt == 0 || bbs->bbv == NULL)
goto exit_free;
outv(v, "bad blocks:\n");
outv(v, "\toffset\t\tlength\n");
unsigned b;
for (b = 0; b < bbs->bb_cnt; b++) {
outv(v, "\t%zu\t\t%zu\n",
B2SEC(bbs->bbv[b].offset),
B2SEC(bbs->bbv[b].length));
}
exit_free:
badblocks_delete(bbs);
return ret;
}
/*
* pmempool_info_part -- (internal) print info about poolset part
*/
static int
pmempool_info_part(struct pmem_info *pip, unsigned repn, unsigned partn, int v)
{
/* get path of the part file */
const char *path = NULL;
if (repn != UNDEF_REPLICA && partn != UNDEF_PART) {
outv(v, "part %u:\n", partn);
struct pool_set_part *part =
&pip->pfile->poolset->replica[repn]->part[partn];
path = part->path;
} else {
outv(v, "Part file:\n");
path = pip->file_name;
}
outv_field(v, "path", "%s", path);
enum file_type type = util_file_get_type(path);
if (type < 0)
return -1;
const char *type_str = type == TYPE_DEVDAX ? "device dax" :
"regular file";
outv_field(v, "type", "%s", type_str);
/* get size of the part file */
ssize_t size = util_file_get_size(path);
if (size < 0) {
outv_err("couldn't get size of %s", path);
return -1;
}
outv_field(v, "size", "%s", out_get_size_str((size_t)size,
pip->args.human));
/* get alignment of device dax */
if (type == TYPE_DEVDAX) {
size_t alignment = util_file_device_dax_alignment(path);
outv_field(v, "alignment", "%s", out_get_size_str(alignment,
pip->args.human));
}
/* look for bad blocks */
if (pmempool_info_badblocks(pip, path, VERBOSE_DEFAULT)) {
outv_err("Unable to retrieve badblock info");
return -1;
}
return 0;
}
/*
* pmempool_info_directory -- (internal) print information about directory
*/
static void
pmempool_info_directory(struct pool_set_directory *d,
int v)
{
outv(v, "Directory %s:\n", d->path);
outv_field(v, "reservation size", "%lu", d->resvsize);
}
/*
* pmempool_info_replica -- (internal) print info about replica
*/
static int
pmempool_info_replica(struct pmem_info *pip, unsigned repn, int v)
{
struct pool_replica *rep = pip->pfile->poolset->replica[repn];
outv(v, "Replica %u%s - %s", repn,
repn == 0 ? " (master)" : "",
rep->remote == NULL ? "local" : "remote");
if (rep->remote) {
outv(v, ":\n");
outv_field(v, "node", "%s", rep->remote->node_addr);
outv_field(v, "pool set", "%s", rep->remote->pool_desc);
return 0;
}
outv(v, ", %u part(s):\n", rep->nparts);
for (unsigned p = 0; p < rep->nparts; ++p) {
if (pmempool_info_part(pip, repn, p, v))
return -1;
}
if (pip->pfile->poolset->directory_based) {
size_t nd = VEC_SIZE(&rep->directory);
outv(v, "%lu %s:\n", nd, nd == 1 ? "Directory" : "Directories");
struct pool_set_directory *d;
VEC_FOREACH_BY_PTR(d, &rep->directory) {
pmempool_info_directory(d, v);
}
}
return 0;
}
/*
* pmempool_info_poolset -- (internal) print info about poolset structure
*/
static int
pmempool_info_poolset(struct pmem_info *pip, int v)
{
ASSERTeq(pip->params.is_poolset, 1);
if (pip->pfile->poolset->directory_based)
outv(v, "Directory-based Poolset structure:\n");
else
outv(v, "Poolset structure:\n");
outv_field(v, "Number of replicas", "%u",
pip->pfile->poolset->nreplicas);
for (unsigned r = 0; r < pip->pfile->poolset->nreplicas; ++r) {
if (pmempool_info_replica(pip, r, v))
return -1;
}
if (pip->pfile->poolset->options > 0) {
outv_title(v, "Poolset options");
if (pip->pfile->poolset->options & OPTION_SINGLEHDR)
outv(v, "%s", "SINGLEHDR\n");
}
return 0;
}
/*
* pmempool_info_pool_hdr -- (internal) print pool header information
*/
static int
pmempool_info_pool_hdr(struct pmem_info *pip, int v)
{
static const char *alignment_desc_str[] = {
" char",
" short",
" int",
" long",
" long long",
" size_t",
" os_off_t",
" float",
" double",
" long double",
" void *",
};
static const size_t alignment_desc_n =
sizeof(alignment_desc_str) / sizeof(alignment_desc_str[0]);
int ret = 0;
struct pool_hdr *hdr = malloc(sizeof(struct pool_hdr));
if (!hdr)
err(1, "Cannot allocate memory for pool_hdr");
if (pmempool_info_read(pip, hdr, sizeof(*hdr), 0)) {
outv_err("cannot read pool header\n");
free(hdr);
return -1;
}
struct arch_flags arch_flags;
util_get_arch_flags(&arch_flags);
outv_title(v, "POOL Header");
outv_hexdump(pip->args.vhdrdump, hdr, sizeof(*hdr), 0, 1);
util_convert2h_hdr_nocheck(hdr);
outv_field(v, "Signature", "%.*s%s", POOL_HDR_SIG_LEN,
hdr->signature,
pip->params.is_part ?
" [part file]" : "");
outv_field(v, "Major", "%d", hdr->major);
outv_field(v, "Mandatory features", "%s",
out_get_incompat_features_str(hdr->features.incompat));
outv_field(v, "Not mandatory features", "0x%x", hdr->features.compat);
outv_field(v, "Forced RO", "0x%x", hdr->features.ro_compat);
outv_field(v, "Pool set UUID", "%s",
out_get_uuid_str(hdr->poolset_uuid));
outv_field(v, "UUID", "%s", out_get_uuid_str(hdr->uuid));
outv_field(v, "Previous part UUID", "%s",
out_get_uuid_str(hdr->prev_part_uuid));
outv_field(v, "Next part UUID", "%s",
out_get_uuid_str(hdr->next_part_uuid));
outv_field(v, "Previous replica UUID", "%s",
out_get_uuid_str(hdr->prev_repl_uuid));
outv_field(v, "Next replica UUID", "%s",
out_get_uuid_str(hdr->next_repl_uuid));
outv_field(v, "Creation Time", "%s",
out_get_time_str((time_t)hdr->crtime));
uint64_t ad = hdr->arch_flags.alignment_desc;
uint64_t cur_ad = arch_flags.alignment_desc;
outv_field(v, "Alignment Descriptor", "%s",
out_get_alignment_desc_str(ad, cur_ad));
for (size_t i = 0; i < alignment_desc_n; i++) {
uint64_t a = GET_ALIGNMENT(ad, i);
if (ad == cur_ad) {
outv_field(v + 1, alignment_desc_str[i],
"%2lu", a);
} else {
uint64_t av = GET_ALIGNMENT(cur_ad, i);
if (a == av) {
outv_field(v + 1, alignment_desc_str[i],
"%2lu [OK]", a);
} else {
outv_field(v + 1, alignment_desc_str[i],
"%2lu [wrong! should be %2lu]", a, av);
}
}
}
outv_field(v, "Class", "%s",
out_get_arch_machine_class_str(
hdr->arch_flags.machine_class));
outv_field(v, "Data", "%s",
out_get_arch_data_str(hdr->arch_flags.data));
outv_field(v, "Machine", "%s",
out_get_arch_machine_str(hdr->arch_flags.machine));
outv_field(v, "Last shutdown", "%s",
out_get_last_shutdown_str(hdr->sds.dirty));
outv_field(v, "Checksum", "%s", out_get_checksum(hdr, sizeof(*hdr),
&hdr->checksum, POOL_HDR_CSUM_END_OFF(hdr)));
free(hdr);
return ret;
}
/*
* pmempool_info_file -- print info about single file
*/
static int
pmempool_info_file(struct pmem_info *pip, const char *file_name)
{
int ret = 0;
pip->file_name = file_name;
/*
* If force flag is set 'types' fields _must_ hold
* single pool type - this is validated when processing
* command line arguments.
*/
if (pip->args.force) {
pip->type = pip->args.type;
} else {
if (pmem_pool_parse_params(file_name, &pip->params, 1)) {
if (errno)
perror(file_name);
else
outv_err("%s: cannot determine type of pool\n",
file_name);
return -1;
}
pip->type = pip->params.type;
}
if (PMEM_POOL_TYPE_UNKNOWN == pip->type) {
outv_err("%s: unknown pool type -- '%s'\n", file_name,
pip->params.signature);
return -1;
} else if (!pip->args.force && !pip->params.is_checksum_ok) {
outv_err("%s: invalid checksum\n", file_name);
return -1;
} else {
if (util_options_verify(pip->opts, pip->type))
return -1;
pip->pfile = pool_set_file_open(file_name, 0, !pip->args.force);
if (!pip->pfile) {
perror(file_name);
return -1;
}
/* check if we should check and print bad blocks */
if (pip->args.badblocks == PRINT_BAD_BLOCKS_NOT_SET) {
struct pool_hdr hdr;
if (pmempool_info_read(pip, &hdr, sizeof(hdr), 0)) {
outv_err("cannot read pool header\n");
goto out_close;
}
util_convert2h_hdr_nocheck(&hdr);
if (hdr.features.compat & POOL_FEAT_CHECK_BAD_BLOCKS)
pip->args.badblocks = PRINT_BAD_BLOCKS_YES;
else
pip->args.badblocks = PRINT_BAD_BLOCKS_NO;
}
if (pip->type != PMEM_POOL_TYPE_BTT) {
struct pool_set *ps = pip->pfile->poolset;
for (unsigned r = 0; r < ps->nreplicas; ++r) {
if (ps->replica[r]->remote == NULL &&
mprotect(ps->replica[r]->part[0].addr,
ps->replica[r]->repsize,
PROT_READ) < 0) {
outv_err(
"%s: failed to change pool protection",
pip->pfile->fname);
ret = -1;
goto out_close;
}
}
}
if (pip->args.obj.replica) {
size_t nreplicas = pool_set_file_nreplicas(pip->pfile);
if (nreplicas == 1) {
outv_err("only master replica available");
ret = -1;
goto out_close;
}
if (pip->args.obj.replica >= nreplicas) {
outv_err("replica number out of range"
" (valid range is: 0-%" PRIu64 ")",
nreplicas - 1);
ret = -1;
goto out_close;
}
if (pool_set_file_set_replica(pip->pfile,
pip->args.obj.replica)) {
outv_err("setting replica number failed");
ret = -1;
goto out_close;
}
}
/* hdr info is not present in btt device */
if (pip->type != PMEM_POOL_TYPE_BTT) {
if (pip->params.is_poolset &&
pmempool_info_poolset(pip,
VERBOSE_DEFAULT)) {
ret = -1;
goto out_close;
}
if (!pip->params.is_poolset &&
pmempool_info_part(pip, UNDEF_REPLICA,
UNDEF_PART, VERBOSE_DEFAULT)) {
ret = -1;
goto out_close;
}
if (pmempool_info_pool_hdr(pip, VERBOSE_DEFAULT)) {
ret = -1;
goto out_close;
}
}
if (pip->params.is_part) {
ret = 0;
goto out_close;
}
switch (pip->type) {
case PMEM_POOL_TYPE_LOG:
ret = pmempool_info_log(pip);
break;
case PMEM_POOL_TYPE_BLK:
ret = pmempool_info_blk(pip);
break;
case PMEM_POOL_TYPE_OBJ:
ret = pmempool_info_obj(pip);
break;
case PMEM_POOL_TYPE_BTT:
ret = pmempool_info_btt(pip);
break;
case PMEM_POOL_TYPE_UNKNOWN:
default:
ret = -1;
break;
}
out_close:
pool_set_file_close(pip->pfile);
}
return ret;
}
/*
* pmempool_info_alloc -- allocate pmem info context
*/
static struct pmem_info *
pmempool_info_alloc(void)
{
struct pmem_info *pip = malloc(sizeof(struct pmem_info));
if (!pip)
err(1, "Cannot allocate memory for pmempool info context");
if (pip) {
memset(pip, 0, sizeof(*pip));
/* set default command line parameters */
memcpy(&pip->args, &pmempool_info_args_default,
sizeof(pip->args));
pip->opts = util_options_alloc(long_options,
sizeof(long_options) /
sizeof(long_options[0]),
option_requirements);
PMDK_LIST_INIT(&pip->args.ranges.head);
PMDK_LIST_INIT(&pip->args.obj.type_ranges.head);
PMDK_LIST_INIT(&pip->args.obj.lane_ranges.head);
PMDK_LIST_INIT(&pip->args.obj.zone_ranges.head);
PMDK_LIST_INIT(&pip->args.obj.chunk_ranges.head);
PMDK_TAILQ_INIT(&pip->obj.stats.type_stats);
}
return pip;
}
/*
* pmempool_info_free -- free pmem info context
*/
static void
pmempool_info_free(struct pmem_info *pip)
{
if (pip->obj.stats.zone_stats) {
for (uint64_t i = 0; i < pip->obj.stats.n_zones; ++i)
VEC_DELETE(&pip->obj.stats.zone_stats[i].class_stats);
free(pip->obj.stats.zone_stats);
}
util_options_free(pip->opts);
util_ranges_clear(&pip->args.ranges);
util_ranges_clear(&pip->args.obj.type_ranges);
util_ranges_clear(&pip->args.obj.zone_ranges);
util_ranges_clear(&pip->args.obj.chunk_ranges);
util_ranges_clear(&pip->args.obj.lane_ranges);
while (!PMDK_TAILQ_EMPTY(&pip->obj.stats.type_stats)) {
struct pmem_obj_type_stats *type =
PMDK_TAILQ_FIRST(&pip->obj.stats.type_stats);
PMDK_TAILQ_REMOVE(&pip->obj.stats.type_stats, type, next);
free(type);
}
free(pip);
}
int
pmempool_info_func(const char *appname, int argc, char *argv[])
{
int ret = 0;
struct pmem_info *pip = pmempool_info_alloc();
/* read command line arguments */
if ((ret = parse_args(appname, argc, argv, &pip->args,
pip->opts)) == 0) {
/* set some output format values */
out_set_vlevel(pip->args.vlevel);
out_set_col_width(pip->args.col_width);
ret = pmempool_info_file(pip, pip->args.file);
}
pmempool_info_free(pip);
return ret;
}
| 26,501 | 24.605797 | 80 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/rm.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* rm.c -- pmempool rm command main source file
*/
#include <stdlib.h>
#include <getopt.h>
#include <unistd.h>
#include <err.h>
#include <stdio.h>
#include <fcntl.h>
#include "os.h"
#include "out.h"
#include "common.h"
#include "output.h"
#include "file.h"
#include "rm.h"
#include "set.h"
#ifdef USE_RPMEM
#include "librpmem.h"
#endif
enum ask_type {
ASK_SOMETIMES, /* ask before removing write-protected files */
ASK_ALWAYS, /* always ask */
ASK_NEVER, /* never ask */
};
/* verbosity level */
static int vlevel;
/* force remove and ignore errors */
static int force;
/* poolset files options */
#define RM_POOLSET_NONE (0)
#define RM_POOLSET_LOCAL (1 << 0)
#define RM_POOLSET_REMOTE (1 << 1)
#define RM_POOLSET_ALL (RM_POOLSET_LOCAL | RM_POOLSET_REMOTE)
static int rm_poolset_mode;
/* mode of interaction */
static enum ask_type ask_mode;
/* indicates whether librpmem is available */
static int rpmem_avail;
/* help message */
static const char * const help_str =
"Remove pool file or all files from poolset\n"
"\n"
"Available options:\n"
" -h, --help Print this help message.\n"
" -v, --verbose Be verbose.\n"
" -s, --only-pools Remove only pool files (default).\n"
" -a, --all Remove all poolset files - local and remote.\n"
" -l, --local Remove local poolset files\n"
" -r, --remote Remove remote poolset files\n"
" -f, --force Ignore nonexisting files.\n"
" -i, --interactive Prompt before every single removal.\n"
"\n"
"For complete documentation see %s-rm(1) manual page.\n";
/* short options string */
static const char *optstr = "hvsfialr";
/* long options */
static const struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"verbose", no_argument, NULL, 'v'},
{"only-pools", no_argument, NULL, 's'},
{"all", no_argument, NULL, 'a'},
{"local", no_argument, NULL, 'l'},
{"remote", no_argument, NULL, 'r'},
{"force", no_argument, NULL, 'f'},
{"interactive", no_argument, NULL, 'i'},
{NULL, 0, NULL, 0 },
};
/*
* print_usage -- print usage message
*/
static void
print_usage(const char *appname)
{
printf("Usage: %s rm [<args>] <files>\n", appname);
}
/*
* pmempool_rm_help -- print help message
*/
void
pmempool_rm_help(const char *appname)
{
print_usage(appname);
printf(help_str, appname);
}
/*
* rm_file -- remove single file
*/
static int
rm_file(const char *file)
{
int write_protected = os_access(file, W_OK) != 0;
char cask = 'y';
switch (ask_mode) {
case ASK_ALWAYS:
cask = '?';
break;
case ASK_NEVER:
cask = 'y';
break;
case ASK_SOMETIMES:
cask = write_protected ? '?' : 'y';
break;
default:
outv_err("unknown state");
return 1;
}
const char *pre_msg = write_protected ? "write-protected " : "";
char ans = ask_Yn(cask, "remove %sfile '%s' ?", pre_msg, file);
if (ans == 'y') {
if (util_unlink(file)) {
outv_err("cannot remove file '%s'", file);
return 1;
}
outv(1, "removed '%s'\n", file);
}
return 0;
}
/*
* remove_remote -- (internal) remove remote pool
*/
static int
remove_remote(const char *target, const char *pool_set)
{
#ifdef USE_RPMEM
char cask = 'y';
switch (ask_mode) {
case ASK_ALWAYS:
cask = '?';
break;
case ASK_NEVER:
case ASK_SOMETIMES:
cask = 'y';
break;
default:
outv_err("unknown state");
return 1;
}
char ans = ask_Yn(cask, "remove remote pool '%s' on '%s'?",
pool_set, target);
if (ans == INV_ANS)
outv(1, "invalid answer\n");
if (ans != 'y')
return 0;
if (!rpmem_avail) {
if (force) {
outv(1, "cannot remove '%s' on '%s' -- "
"librpmem not available", pool_set, target);
return 0;
}
outv_err("!cannot remove '%s' on '%s' -- "
"librpmem not available", pool_set, target);
return 1;
}
int flags = 0;
if (rm_poolset_mode & RM_POOLSET_REMOTE)
flags |= RPMEM_REMOVE_POOL_SET;
if (force)
flags |= RPMEM_REMOVE_FORCE;
int ret = Rpmem_remove(target, pool_set, flags);
if (ret) {
if (force) {
ret = 0;
outv(1, "cannot remove '%s' on '%s'",
pool_set, target);
} else {
/*
* Callback cannot return < 0 value because it
* is interpretted as error in parsing poolset file.
*/
ret = 1;
outv_err("!cannot remove '%s' on '%s'",
pool_set, target);
}
} else {
outv(1, "removed '%s' on '%s'\n",
pool_set, target);
}
return ret;
#else
outv_err("remote replication not supported");
return 1;
#endif
}
/*
* rm_poolset_cb -- (internal) callback for removing replicas
*/
static int
rm_poolset_cb(struct part_file *pf, void *arg)
{
int *error = (int *)arg;
int ret;
if (pf->is_remote) {
ret = remove_remote(pf->remote->node_addr,
pf->remote->pool_desc);
} else {
const char *part_file = pf->part->path;
outv(2, "part file : %s\n", part_file);
int exists = util_file_exists(part_file);
if (exists < 0)
ret = 1;
else if (!exists) {
/*
* Ignore not accessible file if force
* flag is set.
*/
if (force)
return 0;
ret = 1;
outv_err("!cannot remove file '%s'", part_file);
} else {
ret = rm_file(part_file);
}
}
if (ret)
*error = ret;
return 0;
}
/*
* rm_poolset -- remove files parsed from poolset file
*/
static int
rm_poolset(const char *file)
{
int error = 0;
int ret = util_poolset_foreach_part(file, rm_poolset_cb, &error);
if (ret == -1) {
outv_err("parsing poolset failed: %s\n",
out_get_errormsg());
return ret;
}
if (error && !force) {
outv_err("!removing '%s' failed\n", file);
return error;
}
return 0;
}
/*
* pmempool_rm_func -- main function for rm command
*/
int
pmempool_rm_func(const char *appname, int argc, char *argv[])
{
/* by default do not remove any poolset files */
rm_poolset_mode = RM_POOLSET_NONE;
int opt;
while ((opt = getopt_long(argc, argv, optstr,
long_options, NULL)) != -1) {
switch (opt) {
case 'h':
pmempool_rm_help(appname);
return 0;
case 'v':
vlevel++;
break;
case 's':
rm_poolset_mode = RM_POOLSET_NONE;
break;
case 'a':
rm_poolset_mode |= RM_POOLSET_ALL;
break;
case 'l':
rm_poolset_mode |= RM_POOLSET_LOCAL;
break;
case 'r':
rm_poolset_mode |= RM_POOLSET_REMOTE;
break;
case 'f':
force = 1;
ask_mode = ASK_NEVER;
break;
case 'i':
ask_mode = ASK_ALWAYS;
break;
default:
print_usage(appname);
return 1;
}
}
out_set_vlevel(vlevel);
if (optind == argc) {
print_usage(appname);
return 1;
}
#ifdef USE_RPMEM
/*
* Try to load librpmem, if loading failed -
* assume it is not available.
*/
util_remote_init();
rpmem_avail = !util_remote_load();
#endif
int lret = 0;
for (int i = optind; i < argc; i++) {
char *file = argv[i];
/* check if file exists and we can read it */
int exists = os_access(file, F_OK | R_OK) == 0;
if (!exists) {
/* ignore not accessible file if force flag is set */
if (force)
continue;
outv_err("!cannot remove '%s'", file);
lret = 1;
continue;
}
int is_poolset = util_is_poolset_file(file);
if (is_poolset < 0) {
outv(1, "%s: cannot determine type of file", file);
if (force)
continue;
}
if (is_poolset)
outv(2, "poolset file: %s\n", file);
else
outv(2, "pool file : %s\n", file);
int ret;
if (is_poolset) {
ret = rm_poolset(file);
if (!ret && (rm_poolset_mode & RM_POOLSET_LOCAL))
ret = rm_file(file);
} else {
ret = rm_file(file);
}
if (ret)
lret = ret;
}
return lret;
}
| 7,538 | 19.211796 | 71 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/synchronize.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* synchronize.h -- pmempool sync command header file
*/
int pmempool_sync_func(const char *appname, int argc, char *argv[]);
void pmempool_sync_help(const char *appname);
| 264 | 25.5 | 68 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/common.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* common.h -- declarations of common functions
*/
#include <stdint.h>
#include <stddef.h>
#include <stdarg.h>
#include <stdbool.h>
#include "queue.h"
#include "log.h"
#include "blk.h"
#include "libpmemobj.h"
#include "lane.h"
#include "ulog.h"
#include "memops.h"
#include "pmalloc.h"
#include "list.h"
#include "obj.h"
#include "memblock.h"
#include "heap_layout.h"
#include "tx.h"
#include "heap.h"
#include "btt_layout.h"
#include "page_size.h"
/* XXX - modify Linux makefiles to generate srcversion.h and remove #ifdef */
#ifdef _WIN32
#include "srcversion.h"
#endif
#define COUNT_OF(x) (sizeof(x) / sizeof(0[x]))
#define OPT_SHIFT 12
#define OPT_MASK (~((1 << OPT_SHIFT) - 1))
#define OPT_LOG (1 << (PMEM_POOL_TYPE_LOG + OPT_SHIFT))
#define OPT_BLK (1 << (PMEM_POOL_TYPE_BLK + OPT_SHIFT))
#define OPT_OBJ (1 << (PMEM_POOL_TYPE_OBJ + OPT_SHIFT))
#define OPT_BTT (1 << (PMEM_POOL_TYPE_BTT + OPT_SHIFT))
#define OPT_ALL (OPT_LOG | OPT_BLK | OPT_OBJ | OPT_BTT)
#define OPT_REQ_SHIFT 8
#define OPT_REQ_MASK ((1 << OPT_REQ_SHIFT) - 1)
#define _OPT_REQ(c, n) ((c) << (OPT_REQ_SHIFT * (n)))
#define OPT_REQ0(c) _OPT_REQ(c, 0)
#define OPT_REQ1(c) _OPT_REQ(c, 1)
#define OPT_REQ2(c) _OPT_REQ(c, 2)
#define OPT_REQ3(c) _OPT_REQ(c, 3)
#define OPT_REQ4(c) _OPT_REQ(c, 4)
#define OPT_REQ5(c) _OPT_REQ(c, 5)
#define OPT_REQ6(c) _OPT_REQ(c, 6)
#define OPT_REQ7(c) _OPT_REQ(c, 7)
#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif
#define FOREACH_RANGE(range, ranges)\
PMDK_LIST_FOREACH(range, &(ranges)->head, next)
#define PLIST_OFF_TO_PTR(pop, off)\
((off) == 0 ? NULL : (void *)((uintptr_t)(pop) + (off) - OBJ_OOB_SIZE))
#define ENTRY_TO_ALLOC_HDR(entry)\
((void *)((uintptr_t)(entry) - sizeof(struct allocation_header)))
#define OBJH_FROM_PTR(ptr)\
((void *)((uintptr_t)(ptr) - sizeof(struct legacy_object_header)))
#define DEFAULT_HDR_SIZE PMEM_PAGESIZE
#define DEFAULT_DESC_SIZE PMEM_PAGESIZE
#define POOL_HDR_DESC_SIZE (DEFAULT_HDR_SIZE + DEFAULT_DESC_SIZE)
#define PTR_TO_ALLOC_HDR(ptr)\
((void *)((uintptr_t)(ptr) -\
sizeof(struct legacy_object_header)))
#define OBJH_TO_PTR(objh)\
((void *)((uintptr_t)(objh) + sizeof(struct legacy_object_header)))
/* invalid answer for ask_* functions */
#define INV_ANS '\0'
#define FORMAT_PRINTF(a, b) __attribute__((__format__(__printf__, (a), (b))))
/*
* pmem_pool_type_t -- pool types
*/
typedef enum {
PMEM_POOL_TYPE_LOG = 0x01,
PMEM_POOL_TYPE_BLK = 0x02,
PMEM_POOL_TYPE_OBJ = 0x04,
PMEM_POOL_TYPE_BTT = 0x08,
PMEM_POOL_TYPE_ALL = 0x0f,
PMEM_POOL_TYPE_UNKNOWN = 0x80,
} pmem_pool_type_t;
struct option_requirement {
int opt;
pmem_pool_type_t type;
uint64_t req;
};
struct options {
const struct option *opts;
size_t noptions;
char *bitmap;
const struct option_requirement *req;
};
struct pmem_pool_params {
pmem_pool_type_t type;
char signature[POOL_HDR_SIG_LEN];
uint64_t size;
mode_t mode;
int is_poolset;
int is_part;
int is_checksum_ok;
union {
struct {
uint64_t bsize;
} blk;
struct {
char layout[PMEMOBJ_MAX_LAYOUT];
} obj;
};
};
struct pool_set_file {
int fd;
char *fname;
void *addr;
size_t size;
struct pool_set *poolset;
size_t replica;
time_t mtime;
mode_t mode;
bool fileio;
};
struct pool_set_file *pool_set_file_open(const char *fname,
int rdonly, int check);
void pool_set_file_close(struct pool_set_file *file);
int pool_set_file_read(struct pool_set_file *file, void *buff,
size_t nbytes, uint64_t off);
int pool_set_file_write(struct pool_set_file *file, void *buff,
size_t nbytes, uint64_t off);
int pool_set_file_set_replica(struct pool_set_file *file, size_t replica);
size_t pool_set_file_nreplicas(struct pool_set_file *file);
void *pool_set_file_map(struct pool_set_file *file, uint64_t offset);
void pool_set_file_persist(struct pool_set_file *file,
const void *addr, size_t len);
struct range {
PMDK_LIST_ENTRY(range) next;
uint64_t first;
uint64_t last;
};
struct ranges {
PMDK_LIST_HEAD(rangeshead, range) head;
};
pmem_pool_type_t pmem_pool_type_parse_hdr(const struct pool_hdr *hdrp);
pmem_pool_type_t pmem_pool_type(const void *base_pool_addr);
int pmem_pool_checksum(const void *base_pool_addr);
pmem_pool_type_t pmem_pool_type_parse_str(const char *str);
uint64_t pmem_pool_get_min_size(pmem_pool_type_t type);
int pmem_pool_parse_params(const char *fname, struct pmem_pool_params *paramsp,
int check);
int util_poolset_map(const char *fname, struct pool_set **poolset, int rdonly);
struct options *util_options_alloc(const struct option *options,
size_t nopts, const struct option_requirement *req);
void util_options_free(struct options *opts);
int util_options_verify(const struct options *opts, pmem_pool_type_t type);
int util_options_getopt(int argc, char *argv[], const char *optstr,
const struct options *opts);
pmem_pool_type_t util_get_pool_type_second_page(const void *pool_base_addr);
int util_parse_mode(const char *str, mode_t *mode);
int util_parse_ranges(const char *str, struct ranges *rangesp,
struct range entire);
int util_ranges_add(struct ranges *rangesp, struct range range);
void util_ranges_clear(struct ranges *rangesp);
int util_ranges_contain(const struct ranges *rangesp, uint64_t n);
int util_ranges_empty(const struct ranges *rangesp);
int util_check_memory(const uint8_t *buff, size_t len, uint8_t val);
int util_parse_chunk_types(const char *str, uint64_t *types);
int util_parse_lane_sections(const char *str, uint64_t *types);
char ask(char op, char *answers, char def_ans, const char *fmt, va_list ap);
char ask_Yn(char op, const char *fmt, ...) FORMAT_PRINTF(2, 3);
char ask_yN(char op, const char *fmt, ...) FORMAT_PRINTF(2, 3);
unsigned util_heap_max_zone(size_t size);
int util_pool_clear_badblocks(const char *path, int create);
static const struct range ENTIRE_UINT64 = {
{ NULL, NULL }, /* range */
0, /* first */
UINT64_MAX /* last */
};
| 5,957 | 28.205882 | 79 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/info_log.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* info_log.c -- pmempool info command source file for log pool
*/
#include <stdbool.h>
#include <stdlib.h>
#include <err.h>
#include <sys/mman.h>
#include "common.h"
#include "output.h"
#include "info.h"
/*
* info_log_data -- print used data from log pool
*/
static int
info_log_data(struct pmem_info *pip, int v, struct pmemlog *plp)
{
if (!outv_check(v))
return 0;
uint64_t size_used = plp->write_offset - plp->start_offset;
if (size_used == 0)
return 0;
uint8_t *addr = pool_set_file_map(pip->pfile, plp->start_offset);
if (addr == MAP_FAILED) {
warn("%s", pip->file_name);
outv_err("cannot read pmem log data\n");
return -1;
}
if (pip->args.log.walk == 0) {
outv_title(v, "PMEMLOG data");
struct range *curp = NULL;
PMDK_LIST_FOREACH(curp, &pip->args.ranges.head, next) {
uint8_t *ptr = addr + curp->first;
if (curp->last >= size_used)
curp->last = size_used - 1;
uint64_t count = curp->last - curp->first + 1;
outv_hexdump(v, ptr, count, curp->first +
plp->start_offset, 1);
size_used -= count;
if (!size_used)
break;
}
} else {
/*
* Walk through used data with fixed chunk size
* passed by user.
*/
uint64_t nchunks = size_used / pip->args.log.walk;
outv_title(v, "PMEMLOG data [chunks: total = %lu size = %ld]",
nchunks, pip->args.log.walk);
struct range *curp = NULL;
PMDK_LIST_FOREACH(curp, &pip->args.ranges.head, next) {
uint64_t i;
for (i = curp->first; i <= curp->last &&
i < nchunks; i++) {
outv(v, "Chunk %10lu:\n", i);
outv_hexdump(v, addr + i * pip->args.log.walk,
pip->args.log.walk,
plp->start_offset +
i * pip->args.log.walk,
1);
}
}
}
return 0;
}
/*
* info_logs_stats -- print log type pool statistics
*/
static void
info_log_stats(struct pmem_info *pip, int v, struct pmemlog *plp)
{
uint64_t size_total = plp->end_offset - plp->start_offset;
uint64_t size_used = plp->write_offset - plp->start_offset;
uint64_t size_avail = size_total - size_used;
if (size_total == 0)
return;
double perc_used = (double)size_used / (double)size_total * 100.0;
double perc_avail = 100.0 - perc_used;
outv_title(v, "PMEM LOG Statistics");
outv_field(v, "Total", "%s",
out_get_size_str(size_total, pip->args.human));
outv_field(v, "Available", "%s [%s]",
out_get_size_str(size_avail, pip->args.human),
out_get_percentage(perc_avail));
outv_field(v, "Used", "%s [%s]",
out_get_size_str(size_used, pip->args.human),
out_get_percentage(perc_used));
}
/*
* info_log_descriptor -- print pmemlog descriptor and return 1 if
* write offset is valid
*/
static int
info_log_descriptor(struct pmem_info *pip, int v, struct pmemlog *plp)
{
outv_title(v, "PMEM LOG Header");
/* dump pmemlog header without pool_hdr */
outv_hexdump(pip->args.vhdrdump, (uint8_t *)plp + sizeof(plp->hdr),
sizeof(*plp) - sizeof(plp->hdr),
sizeof(plp->hdr), 1);
log_convert2h(plp);
int write_offset_valid = plp->write_offset >= plp->start_offset &&
plp->write_offset <= plp->end_offset;
outv_field(v, "Start offset", "0x%lx", plp->start_offset);
outv_field(v, "Write offset", "0x%lx [%s]", plp->write_offset,
write_offset_valid ? "OK":"ERROR");
outv_field(v, "End offset", "0x%lx", plp->end_offset);
return write_offset_valid;
}
/*
* pmempool_info_log -- print information about log type pool
*/
int
pmempool_info_log(struct pmem_info *pip)
{
int ret = 0;
struct pmemlog *plp = malloc(sizeof(struct pmemlog));
if (!plp)
err(1, "Cannot allocate memory for pmemlog structure");
if (pmempool_info_read(pip, plp, sizeof(struct pmemlog), 0)) {
outv_err("cannot read pmemlog header\n");
free(plp);
return -1;
}
if (info_log_descriptor(pip, VERBOSE_DEFAULT, plp)) {
info_log_stats(pip, pip->args.vstats, plp);
ret = info_log_data(pip, pip->args.vdata, plp);
}
free(plp);
return ret;
}
| 3,972 | 23.677019 | 70 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/transform.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* transform.h -- pmempool transform command header file
*/
int pmempool_transform_func(const char *appname, int argc, char *argv[]);
void pmempool_transform_help(const char *appname);
| 277 | 26.8 | 73 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/info.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* info.h -- pmempool info command header file
*/
#include "vec.h"
/*
* Verbose levels used in application:
*
* VERBOSE_DEFAULT:
* Default value for application's verbosity level.
* This is also set for data structures which should be
* printed without any command line argument.
*
* VERBOSE_MAX:
* Maximum value for application's verbosity level.
* This value is used when -v command line argument passed.
*
* VERBOSE_SILENT:
* This value is higher than VERBOSE_MAX and it is used only
* for verbosity levels of data structures which should _not_ be
* printed without specified command line arguments.
*/
#define VERBOSE_SILENT 0
#define VERBOSE_DEFAULT 1
#define VERBOSE_MAX 2
/*
* print_bb_e -- printing bad blocks options
*/
enum print_bb_e {
PRINT_BAD_BLOCKS_NOT_SET,
PRINT_BAD_BLOCKS_NO,
PRINT_BAD_BLOCKS_YES,
PRINT_BAD_BLOCKS_MAX
};
/*
* pmempool_info_args -- structure for storing command line arguments
*/
struct pmempool_info_args {
char *file; /* input file */
unsigned col_width; /* column width for printing fields */
bool human; /* sizes in human-readable formats */
bool force; /* force parsing pool */
enum print_bb_e badblocks; /* print bad blocks */
pmem_pool_type_t type; /* forced pool type */
bool use_range; /* use range for blocks */
struct ranges ranges; /* range of block/chunks to dump */
int vlevel; /* verbosity level */
int vdata; /* verbosity level for data dump */
int vhdrdump; /* verbosity level for headers hexdump */
int vstats; /* verbosity level for statistics */
struct {
size_t walk; /* data chunk size */
} log;
struct {
int vmap; /* verbosity level for BTT Map */
int vflog; /* verbosity level for BTT FLOG */
int vbackup; /* verbosity level for BTT Info backup */
bool skip_zeros; /* skip blocks marked with zero flag */
bool skip_error; /* skip blocks marked with error flag */
bool skip_no_flag; /* skip blocks not marked with any flag */
} blk;
struct {
int vlanes; /* verbosity level for lanes */
int vroot;
int vobjects;
int valloc;
int voobhdr;
int vheap;
int vzonehdr;
int vchunkhdr;
int vbitmap;
bool lanes_recovery;
bool ignore_empty_obj;
uint64_t chunk_types;
size_t replica;
struct ranges lane_ranges;
struct ranges type_ranges;
struct ranges zone_ranges;
struct ranges chunk_ranges;
} obj;
};
/*
* pmem_blk_stats -- structure with statistics for pmemblk
*/
struct pmem_blk_stats {
uint32_t total; /* number of processed blocks */
uint32_t zeros; /* number of blocks marked by zero flag */
uint32_t errors; /* number of blocks marked by error flag */
uint32_t noflag; /* number of blocks not marked with any flag */
};
struct pmem_obj_class_stats {
uint64_t n_units;
uint64_t n_used;
uint64_t unit_size;
uint64_t alignment;
uint32_t nallocs;
uint16_t flags;
};
struct pmem_obj_zone_stats {
uint64_t n_chunks;
uint64_t n_chunks_type[MAX_CHUNK_TYPE];
uint64_t size_chunks;
uint64_t size_chunks_type[MAX_CHUNK_TYPE];
VEC(, struct pmem_obj_class_stats) class_stats;
};
struct pmem_obj_type_stats {
PMDK_TAILQ_ENTRY(pmem_obj_type_stats) next;
uint64_t type_num;
uint64_t n_objects;
uint64_t n_bytes;
};
struct pmem_obj_stats {
uint64_t n_total_objects;
uint64_t n_total_bytes;
uint64_t n_zones;
uint64_t n_zones_used;
struct pmem_obj_zone_stats *zone_stats;
PMDK_TAILQ_HEAD(obj_type_stats_head, pmem_obj_type_stats) type_stats;
};
/*
* pmem_info -- context for pmeminfo application
*/
struct pmem_info {
const char *file_name; /* current file name */
struct pool_set_file *pfile;
struct pmempool_info_args args; /* arguments parsed from command line */
struct options *opts;
struct pool_set *poolset;
pmem_pool_type_t type;
struct pmem_pool_params params;
struct {
struct pmem_blk_stats stats;
} blk;
struct {
struct pmemobjpool *pop;
struct palloc_heap *heap;
struct alloc_class_collection *alloc_classes;
size_t size;
struct pmem_obj_stats stats;
uint64_t uuid_lo;
uint64_t objid;
} obj;
};
int pmempool_info_func(const char *appname, int argc, char *argv[]);
void pmempool_info_help(const char *appname);
int pmempool_info_read(struct pmem_info *pip, void *buff,
size_t nbytes, uint64_t off);
int pmempool_info_blk(struct pmem_info *pip);
int pmempool_info_log(struct pmem_info *pip);
int pmempool_info_obj(struct pmem_info *pip);
int pmempool_info_btt(struct pmem_info *pip);
| 4,492 | 25.904192 | 73 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/output.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* output.h -- declarations of output printing related functions
*/
#include <time.h>
#include <stdint.h>
#include <stdio.h>
void out_set_vlevel(int vlevel);
void out_set_stream(FILE *stream);
void out_set_prefix(const char *prefix);
void out_set_col_width(unsigned col_width);
void outv_err(const char *fmt, ...) FORMAT_PRINTF(1, 2);
void out_err(const char *file, int line, const char *func,
const char *fmt, ...) FORMAT_PRINTF(4, 5);
void outv_err_vargs(const char *fmt, va_list ap);
void outv_indent(int vlevel, int i);
void outv(int vlevel, const char *fmt, ...) FORMAT_PRINTF(2, 3);
void outv_nl(int vlevel);
int outv_check(int vlevel);
void outv_title(int vlevel, const char *fmt, ...) FORMAT_PRINTF(2, 3);
void outv_field(int vlevel, const char *field, const char *fmt,
...) FORMAT_PRINTF(3, 4);
void outv_hexdump(int vlevel, const void *addr, size_t len, size_t offset,
int sep);
const char *out_get_uuid_str(uuid_t uuid);
const char *out_get_time_str(time_t time);
const char *out_get_size_str(uint64_t size, int human);
const char *out_get_percentage(double percentage);
const char *out_get_checksum(void *addr, size_t len, uint64_t *csump,
uint64_t skip_off);
const char *out_get_btt_map_entry(uint32_t map);
const char *out_get_pool_type_str(pmem_pool_type_t type);
const char *out_get_pool_signature(pmem_pool_type_t type);
const char *out_get_tx_state_str(uint64_t state);
const char *out_get_chunk_type_str(enum chunk_type type);
const char *out_get_chunk_flags(uint16_t flags);
const char *out_get_zone_magic_str(uint32_t magic);
const char *out_get_pmemoid_str(PMEMoid oid, uint64_t uuid_lo);
const char *out_get_arch_machine_class_str(uint8_t machine_class);
const char *out_get_arch_data_str(uint8_t data);
const char *out_get_arch_machine_str(uint16_t machine);
const char *out_get_last_shutdown_str(uint8_t dirty);
const char *out_get_alignment_desc_str(uint64_t ad, uint64_t cur_ad);
const char *out_get_incompat_features_str(uint32_t incompat);
| 2,070 | 41.265306 | 74 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/synchronize.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* synchronize.c -- pmempool sync command source file
*/
#include "synchronize.h"
#include <stdio.h>
#include <libgen.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdbool.h>
#include <sys/mman.h>
#include <endian.h>
#include "common.h"
#include "output.h"
#include "libpmempool.h"
/*
* pmempool_sync_context -- context and arguments for sync command
*/
struct pmempool_sync_context {
unsigned flags; /* flags which modify the command execution */
char *poolset_file; /* a path to a poolset file */
};
/*
* pmempool_sync_default -- default arguments for sync command
*/
static const struct pmempool_sync_context pmempool_sync_default = {
.flags = 0,
.poolset_file = NULL,
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Check consistency of a pool\n"
"\n"
"Common options:\n"
" -b, --bad-blocks fix bad blocks - it requires creating or reading special recovery files\n"
" -d, --dry-run do not apply changes, only check for viability of synchronization\n"
" -v, --verbose increase verbosity level\n"
" -h, --help display this help and exit\n"
"\n"
"For complete documentation see %s-sync(1) manual page.\n"
;
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"bad-blocks", no_argument, NULL, 'b'},
{"dry-run", no_argument, NULL, 'd'},
{"help", no_argument, NULL, 'h'},
{"verbose", no_argument, NULL, 'v'},
{NULL, 0, NULL, 0 },
};
/*
* print_usage -- (internal) print application usage short description
*/
static void
print_usage(const char *appname)
{
printf("usage: %s sync [<options>] <poolset_file>\n", appname);
}
/*
* print_version -- (internal) print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_sync_help -- print help message for the sync command
*/
void
pmempool_sync_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* pmempool_sync_parse_args -- (internal) parse command line arguments
*/
static int
pmempool_sync_parse_args(struct pmempool_sync_context *ctx, const char *appname,
int argc, char *argv[])
{
int opt;
while ((opt = getopt_long(argc, argv, "bdhv",
long_options, NULL)) != -1) {
switch (opt) {
case 'd':
ctx->flags |= PMEMPOOL_SYNC_DRY_RUN;
break;
case 'b':
ctx->flags |= PMEMPOOL_SYNC_FIX_BAD_BLOCKS;
break;
case 'h':
pmempool_sync_help(appname);
exit(EXIT_SUCCESS);
case 'v':
out_set_vlevel(1);
break;
default:
print_usage(appname);
exit(EXIT_FAILURE);
}
}
if (optind < argc) {
ctx->poolset_file = argv[optind];
} else {
print_usage(appname);
exit(EXIT_FAILURE);
}
return 0;
}
/*
* pmempool_sync_func -- main function for the sync command
*/
int
pmempool_sync_func(const char *appname, int argc, char *argv[])
{
int ret = 0;
struct pmempool_sync_context ctx = pmempool_sync_default;
/* parse command line arguments */
if ((ret = pmempool_sync_parse_args(&ctx, appname, argc, argv)))
return ret;
ret = pmempool_sync(ctx.poolset_file, ctx.flags);
if (ret) {
outv_err("failed to synchronize: %s\n", pmempool_errormsg());
if (errno)
outv_err("%s\n", strerror(errno));
return -1;
} else {
outv(1, "%s: synchronized\n", ctx.poolset_file);
return 0;
}
}
| 3,499 | 21.151899 | 98 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/pmempool/convert.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* convert.c -- pmempool convert command source file
*/
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "convert.h"
#include "os.h"
#ifdef _WIN32
static const char *delimiter = ";";
static const char *convert_bin = "\\pmdk-convert.exe";
#else
static const char *delimiter = ":";
static const char *convert_bin = "/pmdk-convert";
#endif // _WIN32
static int
pmempool_convert_get_path(char *p, size_t max_len)
{
char *path = strdup(os_getenv("PATH"));
if (!path) {
perror("strdup");
return -1;
}
char *dir = strtok(path, delimiter);
while (dir) {
size_t length = strlen(dir) + strlen(convert_bin) + 1;
if (length > max_len) {
fprintf(stderr, "very long dir in PATH, ignoring\n");
continue;
}
strcpy(p, dir);
strcat(p, convert_bin);
if (os_access(p, F_OK) == 0) {
free(path);
return 0;
}
dir = strtok(NULL, delimiter);
}
free(path);
return -1;
}
/*
* pmempool_convert_help -- print help message for convert command. This is
* help message from pmdk-convert tool.
*/
void
pmempool_convert_help(const char *appname)
{
char path[4096];
if (pmempool_convert_get_path(path, sizeof(path))) {
fprintf(stderr,
"pmdk-convert is not installed. Please install it.\n");
exit(1);
}
char *args[] = { path, "-h", NULL };
os_execv(path, args);
perror("execv");
exit(1);
}
/*
* pmempool_convert_func -- main function for convert command.
* It invokes pmdk-convert tool.
*/
int
pmempool_convert_func(const char *appname, int argc, char *argv[])
{
char path[4096];
if (pmempool_convert_get_path(path, sizeof(path))) {
fprintf(stderr,
"pmdk-convert is not installed. Please install it.\n");
exit(1);
}
char **args = malloc(((size_t)argc + 1) * sizeof(*args));
if (!args) {
perror("malloc");
exit(1);
}
args[0] = path;
for (int i = 1; i < argc; ++i)
args[i] = argv[i];
args[argc] = NULL;
os_execv(args[0], args);
perror("execv");
free(args);
exit(1);
}
| 2,104 | 17.794643 | 75 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/tools/daxio/daxio.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2020, Intel Corporation */
/*
* daxio.c -- simple app for reading and writing data from/to
* Device DAX device using mmap instead of file I/O API
*/
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <limits.h>
#include <string.h>
#include <ndctl/libndctl.h>
#include <ndctl/libdaxctl.h>
#include <libpmem.h>
#include "util.h"
#include "os.h"
#include "badblocks.h"
#define ALIGN_UP(size, align) (((size) + (align) - 1) & ~((align) - 1))
#define ALIGN_DOWN(size, align) ((size) & ~((align) - 1))
#define ERR(fmt, ...)\
do {\
fprintf(stderr, "daxio: " fmt, ##__VA_ARGS__);\
} while (0)
#define FAIL(func)\
do {\
fprintf(stderr, "daxio: %s:%d: %s: %s\n",\
__func__, __LINE__, func, strerror(errno));\
} while (0)
#define USAGE_MESSAGE \
"Usage: daxio [option] ...\n"\
"Valid options:\n"\
" -i, --input=FILE - input device/file (default stdin)\n"\
" -o, --output=FILE - output device/file (default stdout)\n"\
" -k, --skip=BYTES - skip offset for input (default 0)\n"\
" -s, --seek=BYTES - seek offset for output (default 0)\n"\
" -l, --len=BYTES - total length to perform the I/O\n"\
" -b, --clear-bad-blocks=<yes|no> - clear bad blocks (default: yes)\n"\
" -z, --zero - zeroing the device\n"\
" -h. --help - print this help\n"\
" -V, --version - display version of daxio\n"
struct daxio_device {
char *path;
int fd;
size_t size; /* actual file/device size */
int is_devdax;
/* Device DAX only */
size_t align; /* internal device alignment */
char *addr; /* mapping base address */
size_t maplen; /* mapping length */
size_t offset; /* seek or skip */
unsigned major;
unsigned minor;
struct ndctl_ctx *ndctl_ctx;
struct ndctl_region *region; /* parent region */
};
/*
* daxio_context -- context and arguments
*/
struct daxio_context {
size_t len; /* total length of I/O */
int zero;
int clear_bad_blocks;
struct daxio_device src;
struct daxio_device dst;
};
/*
* default context
*/
static struct daxio_context Ctx = {
SIZE_MAX, /* len */
0, /* zero */
1, /* clear_bad_blocks */
{ NULL, -1, SIZE_MAX, 0, 0, NULL, 0, 0, 0, 0, NULL, NULL },
{ NULL, -1, SIZE_MAX, 0, 0, NULL, 0, 0, 0, 0, NULL, NULL },
};
/*
* print_version -- print daxio version
*/
static void
print_version(void)
{
printf("%s\n", SRCVERSION);
}
/*
* print_usage -- print short description of usage
*/
static void
print_usage(void)
{
fprintf(stderr, USAGE_MESSAGE);
}
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"input", required_argument, NULL, 'i'},
{"output", required_argument, NULL, 'o'},
{"skip", required_argument, NULL, 'k'},
{"seek", required_argument, NULL, 's'},
{"len", required_argument, NULL, 'l'},
{"clear-bad-blocks", required_argument, NULL, 'b'},
{"zero", no_argument, NULL, 'z'},
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'V'},
{NULL, 0, NULL, 0 },
};
/*
* parse_args -- (internal) parse command line arguments
*/
static int
parse_args(struct daxio_context *ctx, int argc, char * const argv[])
{
int opt;
size_t offset;
size_t len;
while ((opt = getopt_long(argc, argv, "i:o:k:s:l:b:zhV",
long_options, NULL)) != -1) {
switch (opt) {
case 'i':
ctx->src.path = optarg;
break;
case 'o':
ctx->dst.path = optarg;
break;
case 'k':
if (util_parse_size(optarg, &offset)) {
ERR("'%s' -- invalid input offset\n", optarg);
return -1;
}
ctx->src.offset = offset;
break;
case 's':
if (util_parse_size(optarg, &offset)) {
ERR("'%s' -- invalid output offset\n", optarg);
return -1;
}
ctx->dst.offset = offset;
break;
case 'l':
if (util_parse_size(optarg, &len)) {
ERR("'%s' -- invalid length\n", optarg);
return -1;
}
ctx->len = len;
break;
case 'z':
ctx->zero = 1;
break;
case 'b':
if (strcmp(optarg, "no") == 0) {
ctx->clear_bad_blocks = 0;
} else if (strcmp(optarg, "yes") == 0) {
ctx->clear_bad_blocks = 1;
} else {
ERR(
"'%s' -- invalid argument of the '--clear-bad-blocks' option\n",
optarg);
return -1;
}
break;
case 'h':
print_usage();
exit(EXIT_SUCCESS);
case 'V':
print_version();
exit(EXIT_SUCCESS);
default:
print_usage();
exit(EXIT_FAILURE);
}
}
return 0;
}
/*
* validate_args -- (internal) validate command line arguments
*/
static int
validate_args(struct daxio_context *ctx)
{
if (ctx->zero && ctx->dst.path == NULL) {
ERR("zeroing flag specified but no output file provided\n");
return -1;
}
if (!ctx->zero && ctx->src.path == NULL && ctx->dst.path == NULL) {
ERR("an input file and/or an output file must be provided\n");
return -1;
}
/* if no input file provided, use stdin */
if (ctx->src.path == NULL) {
if (ctx->src.offset != 0) {
ERR(
"skip offset specified but no input file provided\n");
return -1;
}
ctx->src.fd = STDIN_FILENO;
ctx->src.path = "STDIN";
}
/* if no output file provided, use stdout */
if (ctx->dst.path == NULL) {
if (ctx->dst.offset != 0) {
ERR(
"seek offset specified but no output file provided\n");
return -1;
}
ctx->dst.fd = STDOUT_FILENO;
ctx->dst.path = "STDOUT";
}
return 0;
}
/*
* match_dev_dax -- (internal) find Device DAX by major/minor device number
*/
static int
match_dev_dax(struct daxio_device *dev, struct daxctl_region *dax_region)
{
struct daxctl_dev *d;
daxctl_dev_foreach(dax_region, d) {
if (dev->major == (unsigned)daxctl_dev_get_major(d) &&
dev->minor == (unsigned)daxctl_dev_get_minor(d)) {
dev->size = daxctl_dev_get_size(d);
return 1;
}
}
return 0;
}
/*
* find_dev_dax -- (internal) check if device is Device DAX
*
* If there is matching Device DAX, find its region, size and alignment.
*/
static int
find_dev_dax(struct ndctl_ctx *ndctl_ctx, struct daxio_device *dev)
{
struct ndctl_bus *bus = NULL;
struct ndctl_region *region = NULL;
struct ndctl_dax *dax = NULL;
struct daxctl_region *dax_region = NULL;
ndctl_bus_foreach(ndctl_ctx, bus) {
ndctl_region_foreach(bus, region) {
ndctl_dax_foreach(region, dax) {
dax_region = ndctl_dax_get_daxctl_region(dax);
if (match_dev_dax(dev, dax_region)) {
dev->is_devdax = 1;
dev->align = ndctl_dax_get_align(dax);
dev->region = region;
return 1;
}
}
}
}
/* try with dax regions */
struct daxctl_ctx *daxctl_ctx;
if (daxctl_new(&daxctl_ctx))
return 0;
int ret = 0;
daxctl_region_foreach(daxctl_ctx, dax_region) {
if (match_dev_dax(dev, dax_region)) {
dev->is_devdax = 1;
dev->align = daxctl_region_get_align(dax_region);
dev->region = region;
ret = 1;
goto end;
}
}
end:
daxctl_unref(daxctl_ctx);
return ret;
}
/*
* setup_device -- (internal) open/mmap file/device
*/
static int
setup_device(struct ndctl_ctx *ndctl_ctx, struct daxio_device *dev, int is_dst,
int clear_bad_blocks)
{
int ret;
int flags = O_RDWR;
int prot = is_dst ? PROT_WRITE : PROT_READ;
if (dev->fd != -1) {
dev->size = SIZE_MAX;
return 0; /* stdin/stdout */
}
/* try to open file/device (if exists) */
dev->fd = os_open(dev->path, flags, S_IRUSR|S_IWUSR);
if (dev->fd == -1) {
ret = errno;
if (ret == ENOENT && is_dst) {
/* file does not exist - create it */
flags = O_CREAT|O_WRONLY|O_TRUNC;
dev->size = SIZE_MAX;
dev->fd = os_open(dev->path, flags, S_IRUSR|S_IWUSR);
if (dev->fd == -1) {
FAIL("open");
return -1;
}
return 0;
} else {
ERR("failed to open '%s': %s\n", dev->path,
strerror(errno));
return -1;
}
}
struct stat stbuf;
ret = fstat(dev->fd, &stbuf);
if (ret == -1) {
FAIL("stat");
return -1;
}
/* check if this is regular file or device */
if (S_ISREG(stbuf.st_mode)) {
if (is_dst)
dev->size = SIZE_MAX;
else
dev->size = (size_t)stbuf.st_size;
} else if (S_ISBLK(stbuf.st_mode)) {
dev->size = (size_t)stbuf.st_size;
} else if (S_ISCHR(stbuf.st_mode)) {
dev->size = SIZE_MAX;
dev->major = major(stbuf.st_rdev);
dev->minor = minor(stbuf.st_rdev);
} else {
return -1;
}
/* check if this is Device DAX */
if (S_ISCHR(stbuf.st_mode))
find_dev_dax(ndctl_ctx, dev);
if (!dev->is_devdax)
return 0;
if (is_dst && clear_bad_blocks) {
/* XXX - clear only badblocks in range bound by offset/len */
if (badblocks_clear_all(dev->path)) {
ERR("failed to clear bad blocks on \"%s\"\n"
" Probably you have not enough permissions to do that.\n"
" You can choose one of three options now:\n"
" 1) run 'daxio' with 'sudo' or as 'root',\n"
" 2) turn off clearing bad blocks using\n"
" the '-b/--clear-bad-blocks=no' option or\n"
" 3) change permissions of some resource files -\n"
" - for details see the description of the CHECK_BAD_BLOCKS\n"
" compat feature in the pmempool-feature(1) man page.\n",
dev->path);
return -1;
}
}
if (dev->align == ULONG_MAX) {
ERR("cannot determine device alignment for \"%s\"\n",
dev->path);
return -1;
}
if (dev->offset > dev->size) {
ERR("'%zu' -- offset beyond device size (%zu)\n",
dev->offset, dev->size);
return -1;
}
/* align len/offset to the internal device alignment */
dev->maplen = ALIGN_UP(dev->size, dev->align);
size_t offset = ALIGN_DOWN(dev->offset, dev->align);
dev->offset = dev->offset - offset;
dev->maplen = dev->maplen - offset;
dev->addr = mmap(NULL, dev->maplen, prot, MAP_SHARED, dev->fd,
(off_t)offset);
if (dev->addr == MAP_FAILED) {
FAIL("mmap");
return -1;
}
return 0;
}
/*
* setup_devices -- (internal) open/mmap input and output
*/
static int
setup_devices(struct ndctl_ctx *ndctl_ctx, struct daxio_context *ctx)
{
if (!ctx->zero &&
setup_device(ndctl_ctx, &ctx->src, 0, ctx->clear_bad_blocks))
return -1;
return setup_device(ndctl_ctx, &ctx->dst, 1, ctx->clear_bad_blocks);
}
/*
* adjust_io_len -- (internal) calculate I/O length if not specified
*/
static void
adjust_io_len(struct daxio_context *ctx)
{
size_t src_len = ctx->src.maplen - ctx->src.offset;
size_t dst_len = ctx->dst.maplen - ctx->dst.offset;
size_t max_len = SIZE_MAX;
if (ctx->zero)
assert(ctx->dst.is_devdax);
else
assert(ctx->src.is_devdax || ctx->dst.is_devdax);
if (ctx->src.is_devdax)
max_len = src_len;
if (ctx->dst.is_devdax)
max_len = max_len < dst_len ? max_len : dst_len;
/* if length is specified and is not bigger than mmapped region */
if (ctx->len != SIZE_MAX && ctx->len <= max_len)
return;
/* adjust len to device size */
ctx->len = max_len;
}
/*
* cleanup_device -- (internal) unmap/close file/device
*/
static void
cleanup_device(struct daxio_device *dev)
{
if (dev->addr)
(void) munmap(dev->addr, dev->maplen);
if (dev->path && dev->fd != -1)
(void) close(dev->fd);
}
/*
* cleanup_devices -- (internal) unmap/close input and output
*/
static void
cleanup_devices(struct daxio_context *ctx)
{
cleanup_device(&ctx->dst);
if (!ctx->zero)
cleanup_device(&ctx->src);
}
/*
* do_io -- (internal) write data to device/file
*/
static int
do_io(struct ndctl_ctx *ndctl_ctx, struct daxio_context *ctx)
{
ssize_t cnt = 0;
assert(ctx->src.is_devdax || ctx->dst.is_devdax);
if (ctx->zero) {
if (ctx->dst.offset > ctx->dst.maplen) {
ERR("output offset larger than device size");
return -1;
}
if (ctx->dst.offset + ctx->len > ctx->dst.maplen) {
ERR("output offset beyond device size");
return -1;
}
char *dst_addr = ctx->dst.addr + ctx->dst.offset;
pmem_memset_persist(dst_addr, 0, ctx->len);
cnt = (ssize_t)ctx->len;
} else if (ctx->src.is_devdax && ctx->dst.is_devdax) {
/* memcpy between src and dst */
char *src_addr = ctx->src.addr + ctx->src.offset;
char *dst_addr = ctx->dst.addr + ctx->dst.offset;
pmem_memcpy_persist(dst_addr, src_addr, ctx->len);
cnt = (ssize_t)ctx->len;
} else if (ctx->src.is_devdax) {
/* write to file directly from mmap'ed src */
char *src_addr = ctx->src.addr + ctx->src.offset;
if (ctx->dst.offset) {
if (lseek(ctx->dst.fd, (off_t)ctx->dst.offset,
SEEK_SET) < 0) {
FAIL("lseek");
goto err;
}
}
do {
ssize_t wcnt = write(ctx->dst.fd, src_addr + cnt,
ctx->len - (size_t)cnt);
if (wcnt == -1) {
FAIL("write");
goto err;
}
cnt += wcnt;
} while ((size_t)cnt < ctx->len);
} else if (ctx->dst.is_devdax) {
/* read from file directly to mmap'ed dst */
char *dst_addr = ctx->dst.addr + ctx->dst.offset;
if (ctx->src.offset) {
if (lseek(ctx->src.fd, (off_t)ctx->src.offset,
SEEK_SET) < 0) {
FAIL("lseek");
return -1;
}
}
do {
ssize_t rcnt = read(ctx->src.fd, dst_addr + cnt,
ctx->len - (size_t)cnt);
if (rcnt == -1) {
FAIL("read");
goto err;
}
/* end of file */
if (rcnt == 0)
break;
cnt = cnt + rcnt;
} while ((size_t)cnt < ctx->len);
pmem_persist(dst_addr, (size_t)cnt);
if ((size_t)cnt != ctx->len)
ERR("requested size %zu larger than source\n",
ctx->len);
}
ERR("copied %zd bytes to device \"%s\"\n", cnt, ctx->dst.path);
return 0;
err:
ERR("failed to perform I/O\n");
return -1;
}
int
main(int argc, char **argv)
{
struct ndctl_ctx *ndctl_ctx;
int ret = EXIT_SUCCESS;
if (parse_args(&Ctx, argc, argv))
return EXIT_FAILURE;
if (validate_args(&Ctx))
return EXIT_FAILURE;
if (ndctl_new(&ndctl_ctx))
return EXIT_FAILURE;
if (setup_devices(ndctl_ctx, &Ctx)) {
ret = EXIT_FAILURE;
goto err;
}
if (!Ctx.src.is_devdax && !Ctx.dst.is_devdax) {
ERR("neither input nor output is device dax\n");
ret = EXIT_FAILURE;
goto err;
}
adjust_io_len(&Ctx);
if (do_io(ndctl_ctx, &Ctx))
ret = EXIT_FAILURE;
err:
cleanup_devices(&Ctx);
ndctl_unref(ndctl_ctx);
return ret;
}
| 14,160 | 22.291118 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/libpmemlog/log.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* log.h -- internal definitions for libpmem log module
*/
#ifndef LOG_H
#define LOG_H 1
#include <stdint.h>
#include <stddef.h>
#include <endian.h>
#include "ctl.h"
#include "util.h"
#include "os_thread.h"
#include "pool_hdr.h"
#include "page_size.h"
#ifdef __cplusplus
extern "C" {
#endif
#include "alloc.h"
#include "fault_injection.h"
#define PMEMLOG_LOG_PREFIX "libpmemlog"
#define PMEMLOG_LOG_LEVEL_VAR "PMEMLOG_LOG_LEVEL"
#define PMEMLOG_LOG_FILE_VAR "PMEMLOG_LOG_FILE"
/* attributes of the log memory pool format for the pool header */
#define LOG_HDR_SIG "PMEMLOG" /* must be 8 bytes including '\0' */
#define LOG_FORMAT_MAJOR 1
#define LOG_FORMAT_FEAT_DEFAULT \
{POOL_FEAT_COMPAT_DEFAULT, POOL_FEAT_INCOMPAT_DEFAULT, 0x0000}
#define LOG_FORMAT_FEAT_CHECK \
{POOL_FEAT_COMPAT_VALID, POOL_FEAT_INCOMPAT_VALID, 0x0000}
static const features_t log_format_feat_default = LOG_FORMAT_FEAT_DEFAULT;
struct pmemlog {
struct pool_hdr hdr; /* memory pool header */
/* root info for on-media format... */
uint64_t start_offset; /* start offset of the usable log space */
uint64_t end_offset; /* maximum offset of the usable log space */
uint64_t write_offset; /* current write point for the log */
/* some run-time state, allocated out of memory pool... */
void *addr; /* mapped region */
size_t size; /* size of mapped region */
int is_pmem; /* true if pool is PMEM */
int rdonly; /* true if pool is opened read-only */
os_rwlock_t *rwlockp; /* pointer to RW lock */
int is_dev_dax; /* true if mapped on device dax */
struct ctl *ctl; /* top level node of the ctl tree structure */
struct pool_set *set; /* pool set info */
};
/* data area starts at this alignment after the struct pmemlog above */
#define LOG_FORMAT_DATA_ALIGN ((uintptr_t)PMEM_PAGESIZE)
/*
* log_convert2h -- convert pmemlog structure to host byte order
*/
static inline void
log_convert2h(struct pmemlog *plp)
{
plp->start_offset = le64toh(plp->start_offset);
plp->end_offset = le64toh(plp->end_offset);
plp->write_offset = le64toh(plp->write_offset);
}
/*
* log_convert2le -- convert pmemlog structure to LE byte order
*/
static inline void
log_convert2le(struct pmemlog *plp)
{
plp->start_offset = htole64(plp->start_offset);
plp->end_offset = htole64(plp->end_offset);
plp->write_offset = htole64(plp->write_offset);
}
#if FAULT_INJECTION
void
pmemlog_inject_fault_at(enum pmem_allocation_type type, int nth,
const char *at);
int
pmemlog_fault_injection_enabled(void);
#else
static inline void
pmemlog_inject_fault_at(enum pmem_allocation_type type, int nth,
const char *at)
{
abort();
}
static inline int
pmemlog_fault_injection_enabled(void)
{
return 0;
}
#endif
#ifdef __cplusplus
}
#endif
#endif
| 2,832 | 23.422414 | 74 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/libpmemlog/log.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* log.c -- log memory pool entry points for libpmem
*/
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/param.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <stdint.h>
#include <stdbool.h>
#include "libpmem.h"
#include "libpmemlog.h"
#include "ctl_global.h"
#include "os.h"
#include "set.h"
#include "out.h"
#include "log.h"
#include "mmap.h"
#include "sys_util.h"
#include "util_pmem.h"
#include "valgrind_internal.h"
static const struct pool_attr Log_create_attr = {
LOG_HDR_SIG,
LOG_FORMAT_MAJOR,
LOG_FORMAT_FEAT_DEFAULT,
{0}, {0}, {0}, {0}, {0}
};
static const struct pool_attr Log_open_attr = {
LOG_HDR_SIG,
LOG_FORMAT_MAJOR,
LOG_FORMAT_FEAT_CHECK,
{0}, {0}, {0}, {0}, {0}
};
/*
* log_descr_create -- (internal) create log memory pool descriptor
*/
static void
log_descr_create(PMEMlogpool *plp, size_t poolsize)
{
LOG(3, "plp %p poolsize %zu", plp, poolsize);
ASSERTeq(poolsize % Pagesize, 0);
/* create required metadata */
plp->start_offset = htole64(roundup(sizeof(*plp),
LOG_FORMAT_DATA_ALIGN));
plp->end_offset = htole64(poolsize);
plp->write_offset = plp->start_offset;
/* store non-volatile part of pool's descriptor */
util_persist(plp->is_pmem, &plp->start_offset, 3 * sizeof(uint64_t));
}
/*
* log_descr_check -- (internal) validate log memory pool descriptor
*/
static int
log_descr_check(PMEMlogpool *plp, size_t poolsize)
{
LOG(3, "plp %p poolsize %zu", plp, poolsize);
struct pmemlog hdr = *plp;
log_convert2h(&hdr);
if ((hdr.start_offset !=
roundup(sizeof(*plp), LOG_FORMAT_DATA_ALIGN)) ||
(hdr.end_offset != poolsize) ||
(hdr.start_offset > hdr.end_offset)) {
ERR("wrong start/end offsets "
"(start: %" PRIu64 " end: %" PRIu64 "), "
"pool size %zu",
hdr.start_offset, hdr.end_offset, poolsize);
errno = EINVAL;
return -1;
}
if ((hdr.write_offset > hdr.end_offset) || (hdr.write_offset <
hdr.start_offset)) {
ERR("wrong write offset (start: %" PRIu64 " end: %" PRIu64
" write: %" PRIu64 ")",
hdr.start_offset, hdr.end_offset, hdr.write_offset);
errno = EINVAL;
return -1;
}
LOG(3, "start: %" PRIu64 ", end: %" PRIu64 ", write: %" PRIu64 "",
hdr.start_offset, hdr.end_offset, hdr.write_offset);
return 0;
}
/*
* log_runtime_init -- (internal) initialize log memory pool runtime data
*/
static int
log_runtime_init(PMEMlogpool *plp, int rdonly)
{
LOG(3, "plp %p rdonly %d", plp, rdonly);
/* remove volatile part of header */
VALGRIND_REMOVE_PMEM_MAPPING(&plp->addr,
sizeof(struct pmemlog) -
sizeof(struct pool_hdr) -
3 * sizeof(uint64_t));
/*
* Use some of the memory pool area for run-time info. This
* run-time state is never loaded from the file, it is always
* created here, so no need to worry about byte-order.
*/
plp->rdonly = rdonly;
if ((plp->rwlockp = Malloc(sizeof(*plp->rwlockp))) == NULL) {
ERR("!Malloc for a RW lock");
return -1;
}
util_rwlock_init(plp->rwlockp);
/*
* If possible, turn off all permissions on the pool header page.
*
* The prototype PMFS doesn't allow this when large pages are in
* use. It is not considered an error if this fails.
*/
RANGE_NONE(plp->addr, sizeof(struct pool_hdr), plp->is_dev_dax);
/* the rest should be kept read-only (debug version only) */
RANGE_RO((char *)plp->addr + sizeof(struct pool_hdr),
plp->size - sizeof(struct pool_hdr), plp->is_dev_dax);
return 0;
}
/*
* pmemlog_createU -- create a log memory pool
*/
#ifndef _WIN32
static inline
#endif
PMEMlogpool *
pmemlog_createU(const char *path, size_t poolsize, mode_t mode)
{
LOG(3, "path %s poolsize %zu mode %d", path, poolsize, mode);
struct pool_set *set;
struct pool_attr adj_pool_attr = Log_create_attr;
/* force set SDS feature */
if (SDS_at_create)
adj_pool_attr.features.incompat |= POOL_FEAT_SDS;
else
adj_pool_attr.features.incompat &= ~POOL_FEAT_SDS;
if (util_pool_create(&set, path, poolsize, PMEMLOG_MIN_POOL,
PMEMLOG_MIN_PART, &adj_pool_attr, NULL,
REPLICAS_DISABLED) != 0) {
LOG(2, "cannot create pool or pool set");
return NULL;
}
ASSERT(set->nreplicas > 0);
struct pool_replica *rep = set->replica[0];
PMEMlogpool *plp = rep->part[0].addr;
VALGRIND_REMOVE_PMEM_MAPPING(&plp->addr,
sizeof(struct pmemlog) -
((uintptr_t)&plp->addr - (uintptr_t)&plp->hdr));
plp->addr = plp;
plp->size = rep->repsize;
plp->set = set;
plp->is_pmem = rep->is_pmem;
plp->is_dev_dax = rep->part[0].is_dev_dax;
/* is_dev_dax implies is_pmem */
ASSERT(!plp->is_dev_dax || plp->is_pmem);
/* create pool descriptor */
log_descr_create(plp, rep->repsize);
/* initialize runtime parts */
if (log_runtime_init(plp, 0) != 0) {
ERR("pool initialization failed");
goto err;
}
if (util_poolset_chmod(set, mode))
goto err;
util_poolset_fdclose(set);
LOG(3, "plp %p", plp);
return plp;
err:
LOG(4, "error clean up");
int oerrno = errno;
util_poolset_close(set, DELETE_CREATED_PARTS);
errno = oerrno;
return NULL;
}
#ifndef _WIN32
/*
* pmemlog_create -- create a log memory pool
*/
PMEMlogpool *
pmemlog_create(const char *path, size_t poolsize, mode_t mode)
{
return pmemlog_createU(path, poolsize, mode);
}
#else
/*
* pmemlog_createW -- create a log memory pool
*/
PMEMlogpool *
pmemlog_createW(const wchar_t *path, size_t poolsize, mode_t mode)
{
char *upath = util_toUTF8(path);
if (upath == NULL)
return NULL;
PMEMlogpool *ret = pmemlog_createU(upath, poolsize, mode);
util_free_UTF8(upath);
return ret;
}
#endif
/*
* log_open_common -- (internal) open a log memory pool
*
* This routine does all the work, but takes a cow flag so internal
* calls can map a read-only pool if required.
*/
static PMEMlogpool *
log_open_common(const char *path, unsigned flags)
{
LOG(3, "path %s flags 0x%x", path, flags);
struct pool_set *set;
if (util_pool_open(&set, path, PMEMLOG_MIN_PART, &Log_open_attr,
NULL, NULL, flags) != 0) {
LOG(2, "cannot open pool or pool set");
return NULL;
}
ASSERT(set->nreplicas > 0);
struct pool_replica *rep = set->replica[0];
PMEMlogpool *plp = rep->part[0].addr;
VALGRIND_REMOVE_PMEM_MAPPING(&plp->addr,
sizeof(struct pmemlog) -
((uintptr_t)&plp->addr - (uintptr_t)&plp->hdr));
plp->addr = plp;
plp->size = rep->repsize;
plp->set = set;
plp->is_pmem = rep->is_pmem;
plp->is_dev_dax = rep->part[0].is_dev_dax;
/* is_dev_dax implies is_pmem */
ASSERT(!plp->is_dev_dax || plp->is_pmem);
if (set->nreplicas > 1) {
errno = ENOTSUP;
ERR("!replicas not supported");
goto err;
}
/* validate pool descriptor */
if (log_descr_check(plp, rep->repsize) != 0) {
LOG(2, "descriptor check failed");
goto err;
}
/* initialize runtime parts */
if (log_runtime_init(plp, set->rdonly) != 0) {
ERR("pool initialization failed");
goto err;
}
util_poolset_fdclose(set);
LOG(3, "plp %p", plp);
return plp;
err:
LOG(4, "error clean up");
int oerrno = errno;
util_poolset_close(set, DO_NOT_DELETE_PARTS);
errno = oerrno;
return NULL;
}
/*
* pmemlog_openU -- open an existing log memory pool
*/
#ifndef _WIN32
static inline
#endif
PMEMlogpool *
pmemlog_openU(const char *path)
{
LOG(3, "path %s", path);
return log_open_common(path, COW_at_open ? POOL_OPEN_COW : 0);
}
#ifndef _WIN32
/*
* pmemlog_open -- open an existing log memory pool
*/
PMEMlogpool *
pmemlog_open(const char *path)
{
return pmemlog_openU(path);
}
#else
/*
* pmemlog_openW -- open an existing log memory pool
*/
PMEMlogpool *
pmemlog_openW(const wchar_t *path)
{
char *upath = util_toUTF8(path);
if (upath == NULL)
return NULL;
PMEMlogpool *ret = pmemlog_openU(upath);
util_free_UTF8(upath);
return ret;
}
#endif
/*
* pmemlog_close -- close a log memory pool
*/
void
pmemlog_close(PMEMlogpool *plp)
{
LOG(3, "plp %p", plp);
util_rwlock_destroy(plp->rwlockp);
Free((void *)plp->rwlockp);
util_poolset_close(plp->set, DO_NOT_DELETE_PARTS);
}
/*
* pmemlog_nbyte -- return usable size of a log memory pool
*/
size_t
pmemlog_nbyte(PMEMlogpool *plp)
{
LOG(3, "plp %p", plp);
util_rwlock_rdlock(plp->rwlockp);
size_t size = le64toh(plp->end_offset) - le64toh(plp->start_offset);
LOG(4, "plp %p nbyte %zu", plp, size);
util_rwlock_unlock(plp->rwlockp);
return size;
}
/*
* log_persist -- (internal) persist data, then metadata
*
* On entry, the write lock should be held.
*/
static void
log_persist(PMEMlogpool *plp, uint64_t new_write_offset)
{
uint64_t old_write_offset = le64toh(plp->write_offset);
size_t length = new_write_offset - old_write_offset;
/* unprotect the log space range (debug version only) */
RANGE_RW((char *)plp->addr + old_write_offset, length, plp->is_dev_dax);
/* persist the data */
if (plp->is_pmem)
pmem_drain(); /* data already flushed */
else
pmem_msync((char *)plp->addr + old_write_offset, length);
/* protect the log space range (debug version only) */
RANGE_RO((char *)plp->addr + old_write_offset, length, plp->is_dev_dax);
/* unprotect the pool descriptor (debug version only) */
RANGE_RW((char *)plp->addr + sizeof(struct pool_hdr),
LOG_FORMAT_DATA_ALIGN, plp->is_dev_dax);
/* write the metadata */
plp->write_offset = htole64(new_write_offset);
/* persist the metadata */
if (plp->is_pmem)
pmem_persist(&plp->write_offset, sizeof(plp->write_offset));
else
pmem_msync(&plp->write_offset, sizeof(plp->write_offset));
/* set the write-protection again (debug version only) */
RANGE_RO((char *)plp->addr + sizeof(struct pool_hdr),
LOG_FORMAT_DATA_ALIGN, plp->is_dev_dax);
}
/*
* pmemlog_append -- add data to a log memory pool
*/
int
pmemlog_append(PMEMlogpool *plp, const void *buf, size_t count)
{
int ret = 0;
LOG(3, "plp %p buf %p count %zu", plp, buf, count);
if (plp->rdonly) {
ERR("can't append to read-only log");
errno = EROFS;
return -1;
}
util_rwlock_wrlock(plp->rwlockp);
/* get the current values */
uint64_t end_offset = le64toh(plp->end_offset);
uint64_t write_offset = le64toh(plp->write_offset);
if (write_offset >= end_offset) {
/* no space left */
errno = ENOSPC;
ERR("!pmemlog_append");
ret = -1;
goto end;
}
/* make sure we don't write past the available space */
if (count > (end_offset - write_offset)) {
errno = ENOSPC;
ERR("!pmemlog_append");
ret = -1;
goto end;
}
char *data = plp->addr;
/*
* unprotect the log space range, where the new data will be stored
* (debug version only)
*/
RANGE_RW(&data[write_offset], count, plp->is_dev_dax);
if (plp->is_pmem)
pmem_memcpy_nodrain(&data[write_offset], buf, count);
else
memcpy(&data[write_offset], buf, count);
/* protect the log space range (debug version only) */
RANGE_RO(&data[write_offset], count, plp->is_dev_dax);
write_offset += count;
/* persist the data and the metadata */
log_persist(plp, write_offset);
end:
util_rwlock_unlock(plp->rwlockp);
return ret;
}
/*
* pmemlog_appendv -- add gathered data to a log memory pool
*/
int
pmemlog_appendv(PMEMlogpool *plp, const struct iovec *iov, int iovcnt)
{
LOG(3, "plp %p iovec %p iovcnt %d", plp, iov, iovcnt);
int ret = 0;
int i;
if (iovcnt < 0) {
errno = EINVAL;
ERR("iovcnt is less than zero: %d", iovcnt);
return -1;
}
if (plp->rdonly) {
ERR("can't append to read-only log");
errno = EROFS;
return -1;
}
util_rwlock_wrlock(plp->rwlockp);
/* get the current values */
uint64_t end_offset = le64toh(plp->end_offset);
uint64_t write_offset = le64toh(plp->write_offset);
if (write_offset >= end_offset) {
/* no space left */
errno = ENOSPC;
ERR("!pmemlog_appendv");
ret = -1;
goto end;
}
char *data = plp->addr;
uint64_t count = 0;
char *buf;
/* calculate required space */
for (i = 0; i < iovcnt; ++i)
count += iov[i].iov_len;
/* check if there is enough free space */
if (count > (end_offset - write_offset)) {
errno = ENOSPC;
ret = -1;
goto end;
}
/* append the data */
for (i = 0; i < iovcnt; ++i) {
buf = iov[i].iov_base;
count = iov[i].iov_len;
/*
* unprotect the log space range, where the new data will be
* stored (debug version only)
*/
RANGE_RW(&data[write_offset], count, plp->is_dev_dax);
if (plp->is_pmem)
pmem_memcpy_nodrain(&data[write_offset], buf, count);
else
memcpy(&data[write_offset], buf, count);
/*
* protect the log space range (debug version only)
*/
RANGE_RO(&data[write_offset], count, plp->is_dev_dax);
write_offset += count;
}
/* persist the data and the metadata */
log_persist(plp, write_offset);
end:
util_rwlock_unlock(plp->rwlockp);
return ret;
}
/*
* pmemlog_tell -- return current write point in a log memory pool
*/
long long
pmemlog_tell(PMEMlogpool *plp)
{
LOG(3, "plp %p", plp);
util_rwlock_rdlock(plp->rwlockp);
ASSERT(le64toh(plp->write_offset) >= le64toh(plp->start_offset));
long long wp = (long long)(le64toh(plp->write_offset) -
le64toh(plp->start_offset));
LOG(4, "write offset %lld", wp);
util_rwlock_unlock(plp->rwlockp);
return wp;
}
/*
* pmemlog_rewind -- discard all data, resetting a log memory pool to empty
*/
void
pmemlog_rewind(PMEMlogpool *plp)
{
LOG(3, "plp %p", plp);
if (plp->rdonly) {
ERR("can't rewind read-only log");
errno = EROFS;
return;
}
util_rwlock_wrlock(plp->rwlockp);
/* unprotect the pool descriptor (debug version only) */
RANGE_RW((char *)plp->addr + sizeof(struct pool_hdr),
LOG_FORMAT_DATA_ALIGN, plp->is_dev_dax);
plp->write_offset = plp->start_offset;
if (plp->is_pmem)
pmem_persist(&plp->write_offset, sizeof(uint64_t));
else
pmem_msync(&plp->write_offset, sizeof(uint64_t));
/* set the write-protection again (debug version only) */
RANGE_RO((char *)plp->addr + sizeof(struct pool_hdr),
LOG_FORMAT_DATA_ALIGN, plp->is_dev_dax);
util_rwlock_unlock(plp->rwlockp);
}
/*
* pmemlog_walk -- walk through all data in a log memory pool
*
* chunksize of 0 means process_chunk gets called once for all data
* as a single chunk.
*/
void
pmemlog_walk(PMEMlogpool *plp, size_t chunksize,
int (*process_chunk)(const void *buf, size_t len, void *arg), void *arg)
{
LOG(3, "plp %p chunksize %zu", plp, chunksize);
/*
* We are assuming that the walker doesn't change the data it's reading
* in place. We prevent everyone from changing the data behind our back
* until we are done with processing it.
*/
util_rwlock_rdlock(plp->rwlockp);
char *data = plp->addr;
uint64_t write_offset = le64toh(plp->write_offset);
uint64_t data_offset = le64toh(plp->start_offset);
size_t len;
if (chunksize == 0) {
/* most common case: process everything at once */
len = write_offset - data_offset;
LOG(3, "length %zu", len);
(*process_chunk)(&data[data_offset], len, arg);
} else {
/*
* Walk through the complete record, chunk by chunk.
* The callback returns 0 to terminate the walk.
*/
while (data_offset < write_offset) {
len = MIN(chunksize, write_offset - data_offset);
if (!(*process_chunk)(&data[data_offset], len, arg))
break;
data_offset += chunksize;
}
}
util_rwlock_unlock(plp->rwlockp);
}
/*
* pmemlog_checkU -- log memory pool consistency check
*
* Returns true if consistent, zero if inconsistent, -1/error if checking
* cannot happen due to other errors.
*/
#ifndef _WIN32
static inline
#endif
int
pmemlog_checkU(const char *path)
{
LOG(3, "path \"%s\"", path);
PMEMlogpool *plp = log_open_common(path, POOL_OPEN_COW);
if (plp == NULL)
return -1; /* errno set by log_open_common() */
int consistent = 1;
/* validate pool descriptor */
uint64_t hdr_start = le64toh(plp->start_offset);
uint64_t hdr_end = le64toh(plp->end_offset);
uint64_t hdr_write = le64toh(plp->write_offset);
if (hdr_start != roundup(sizeof(*plp), LOG_FORMAT_DATA_ALIGN)) {
ERR("wrong value of start_offset");
consistent = 0;
}
if (hdr_end != plp->size) {
ERR("wrong value of end_offset");
consistent = 0;
}
if (hdr_start > hdr_end) {
ERR("start_offset greater than end_offset");
consistent = 0;
}
if (hdr_start > hdr_write) {
ERR("start_offset greater than write_offset");
consistent = 0;
}
if (hdr_write > hdr_end) {
ERR("write_offset greater than end_offset");
consistent = 0;
}
pmemlog_close(plp);
if (consistent)
LOG(4, "pool consistency check OK");
return consistent;
}
#ifndef _WIN32
/*
* pmemlog_check -- log memory pool consistency check
*
* Returns true if consistent, zero if inconsistent, -1/error if checking
* cannot happen due to other errors.
*/
int
pmemlog_check(const char *path)
{
return pmemlog_checkU(path);
}
#else
/*
* pmemlog_checkW -- log memory pool consistency check
*/
int
pmemlog_checkW(const wchar_t *path)
{
char *upath = util_toUTF8(path);
if (upath == NULL)
return -1;
int ret = pmemlog_checkU(upath);
util_free_UTF8(upath);
return ret;
}
#endif
/*
* pmemlog_ctl_getU -- programmatically executes a read ctl query
*/
#ifndef _WIN32
static inline
#endif
int
pmemlog_ctl_getU(PMEMlogpool *plp, const char *name, void *arg)
{
LOG(3, "plp %p name %s arg %p", plp, name, arg);
return ctl_query(plp == NULL ? NULL : plp->ctl, plp,
CTL_QUERY_PROGRAMMATIC, name, CTL_QUERY_READ, arg);
}
/*
* pmemblk_ctl_setU -- programmatically executes a write ctl query
*/
#ifndef _WIN32
static inline
#endif
int
pmemlog_ctl_setU(PMEMlogpool *plp, const char *name, void *arg)
{
LOG(3, "plp %p name %s arg %p", plp, name, arg);
return ctl_query(plp == NULL ? NULL : plp->ctl, plp,
CTL_QUERY_PROGRAMMATIC, name, CTL_QUERY_WRITE, arg);
}
/*
* pmemlog_ctl_execU -- programmatically executes a runnable ctl query
*/
#ifndef _WIN32
static inline
#endif
int
pmemlog_ctl_execU(PMEMlogpool *plp, const char *name, void *arg)
{
LOG(3, "plp %p name %s arg %p", plp, name, arg);
return ctl_query(plp == NULL ? NULL : plp->ctl, plp,
CTL_QUERY_PROGRAMMATIC, name, CTL_QUERY_RUNNABLE, arg);
}
#ifndef _WIN32
/*
* pmemlog_ctl_get -- programmatically executes a read ctl query
*/
int
pmemlog_ctl_get(PMEMlogpool *plp, const char *name, void *arg)
{
return pmemlog_ctl_getU(plp, name, arg);
}
/*
* pmemlog_ctl_set -- programmatically executes a write ctl query
*/
int
pmemlog_ctl_set(PMEMlogpool *plp, const char *name, void *arg)
{
return pmemlog_ctl_setU(plp, name, arg);
}
/*
* pmemlog_ctl_exec -- programmatically executes a runnable ctl query
*/
int
pmemlog_ctl_exec(PMEMlogpool *plp, const char *name, void *arg)
{
return pmemlog_ctl_execU(plp, name, arg);
}
#else
/*
* pmemlog_ctl_getW -- programmatically executes a read ctl query
*/
int
pmemlog_ctl_getW(PMEMlogpool *plp, const wchar_t *name, void *arg)
{
char *uname = util_toUTF8(name);
if (uname == NULL)
return -1;
int ret = pmemlog_ctl_getU(plp, uname, arg);
util_free_UTF8(uname);
return ret;
}
/*
* pmemlog_ctl_setW -- programmatically executes a write ctl query
*/
int
pmemlog_ctl_setW(PMEMlogpool *plp, const wchar_t *name, void *arg)
{
char *uname = util_toUTF8(name);
if (uname == NULL)
return -1;
int ret = pmemlog_ctl_setU(plp, uname, arg);
util_free_UTF8(uname);
return ret;
}
/*
* pmemlog_ctl_execW -- programmatically executes a runnable ctl query
*/
int
pmemlog_ctl_execW(PMEMlogpool *plp, const wchar_t *name, void *arg)
{
char *uname = util_toUTF8(name);
if (uname == NULL)
return -1;
int ret = pmemlog_ctl_execU(plp, uname, arg);
util_free_UTF8(uname);
return ret;
}
#endif
#if FAULT_INJECTION
void
pmemlog_inject_fault_at(enum pmem_allocation_type type, int nth,
const char *at)
{
core_inject_fault_at(type, nth, at);
}
int
pmemlog_fault_injection_enabled(void)
{
return core_fault_injection_enabled();
}
#endif
| 19,695 | 20.982143 | 75 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/libpmemlog/libpmemlog_main.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2017, Intel Corporation */
/*
* libpmemlog_main.c -- entry point for libpmemlog.dll
*
* XXX - This is a placeholder. All the library initialization/cleanup
* that is done in library ctors/dtors, as well as TLS initialization
* should be moved here.
*/
void libpmemlog_init(void);
void libpmemlog_fini(void);
int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
switch (dwReason) {
case DLL_PROCESS_ATTACH:
libpmemlog_init();
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
libpmemlog_fini();
break;
}
return TRUE;
}
| 669 | 19.30303 | 71 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/libpmemlog/libpmemlog.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* libpmemlog.c -- pmem entry points for libpmemlog
*/
#include <stdio.h>
#include <stdint.h>
#include "libpmemlog.h"
#include "ctl_global.h"
#include "pmemcommon.h"
#include "log.h"
/*
* The variable from which the config is directly loaded. The string
* cannot contain any comments or extraneous white characters.
*/
#define LOG_CONFIG_ENV_VARIABLE "PMEMLOG_CONF"
/*
* The variable that points to a config file from which the config is loaded.
*/
#define LOG_CONFIG_FILE_ENV_VARIABLE "PMEMLOG_CONF_FILE"
/*
* log_ctl_init_and_load -- (static) initializes CTL and loads configuration
* from env variable and file
*/
static int
log_ctl_init_and_load(PMEMlogpool *plp)
{
LOG(3, "plp %p", plp);
if (plp != NULL && (plp->ctl = ctl_new()) == NULL) {
LOG(2, "!ctl_new");
return -1;
}
char *env_config = os_getenv(LOG_CONFIG_ENV_VARIABLE);
if (env_config != NULL) {
if (ctl_load_config_from_string(plp ? plp->ctl : NULL,
plp, env_config) != 0) {
LOG(2, "unable to parse config stored in %s "
"environment variable",
LOG_CONFIG_ENV_VARIABLE);
goto err;
}
}
char *env_config_file = os_getenv(LOG_CONFIG_FILE_ENV_VARIABLE);
if (env_config_file != NULL && env_config_file[0] != '\0') {
if (ctl_load_config_from_file(plp ? plp->ctl : NULL,
plp, env_config_file) != 0) {
LOG(2, "unable to parse config stored in %s "
"file (from %s environment variable)",
env_config_file,
LOG_CONFIG_FILE_ENV_VARIABLE);
goto err;
}
}
return 0;
err:
if (plp)
ctl_delete(plp->ctl);
return -1;
}
/*
* log_init -- load-time initialization for log
*
* Called automatically by the run-time loader.
*/
ATTR_CONSTRUCTOR
void
libpmemlog_init(void)
{
ctl_global_register();
if (log_ctl_init_and_load(NULL))
FATAL("error: %s", pmemlog_errormsg());
common_init(PMEMLOG_LOG_PREFIX, PMEMLOG_LOG_LEVEL_VAR,
PMEMLOG_LOG_FILE_VAR, PMEMLOG_MAJOR_VERSION,
PMEMLOG_MINOR_VERSION);
LOG(3, NULL);
}
/*
* libpmemlog_fini -- libpmemlog cleanup routine
*
* Called automatically when the process terminates.
*/
ATTR_DESTRUCTOR
void
libpmemlog_fini(void)
{
LOG(3, NULL);
common_fini();
}
/*
* pmemlog_check_versionU -- see if lib meets application version requirements
*/
#ifndef _WIN32
static inline
#endif
const char *
pmemlog_check_versionU(unsigned major_required, unsigned minor_required)
{
LOG(3, "major_required %u minor_required %u",
major_required, minor_required);
if (major_required != PMEMLOG_MAJOR_VERSION) {
ERR("libpmemlog major version mismatch (need %u, found %u)",
major_required, PMEMLOG_MAJOR_VERSION);
return out_get_errormsg();
}
if (minor_required > PMEMLOG_MINOR_VERSION) {
ERR("libpmemlog minor version mismatch (need %u, found %u)",
minor_required, PMEMLOG_MINOR_VERSION);
return out_get_errormsg();
}
return NULL;
}
#ifndef _WIN32
/*
* pmemlog_check_version -- see if lib meets application version requirements
*/
const char *
pmemlog_check_version(unsigned major_required, unsigned minor_required)
{
return pmemlog_check_versionU(major_required, minor_required);
}
#else
/*
* pmemlog_check_versionW -- see if lib meets application version requirements
*/
const wchar_t *
pmemlog_check_versionW(unsigned major_required, unsigned minor_required)
{
if (pmemlog_check_versionU(major_required, minor_required) != NULL)
return out_get_errormsgW();
else
return NULL;
}
#endif
/*
* pmemlog_set_funcs -- allow overriding libpmemlog's call to malloc, etc.
*/
void
pmemlog_set_funcs(
void *(*malloc_func)(size_t size),
void (*free_func)(void *ptr),
void *(*realloc_func)(void *ptr, size_t size),
char *(*strdup_func)(const char *s))
{
LOG(3, NULL);
util_set_alloc_funcs(malloc_func, free_func, realloc_func, strdup_func);
}
/*
* pmemlog_errormsgU -- return last error message
*/
#ifndef _WIN32
static inline
#endif
const char *
pmemlog_errormsgU(void)
{
return out_get_errormsg();
}
#ifndef _WIN32
/*
* pmemlog_errormsg -- return last error message
*/
const char *
pmemlog_errormsg(void)
{
return pmemlog_errormsgU();
}
#else
/*
* pmemlog_errormsgW -- return last error message as wchar_t
*/
const wchar_t *
pmemlog_errormsgW(void)
{
return out_get_errormsgW();
}
#endif
| 4,301 | 20.29703 | 78 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/freebsd/include/endian.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* endian.h -- redirect for FreeBSD <sys/endian.h>
*/
#include <sys/endian.h>
| 165 | 17.444444 | 50 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/freebsd/include/features.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* features.h -- Empty file redirect
*/
| 126 | 17.142857 | 40 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/freebsd/include/sys/sysmacros.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* sys/sysmacros.h -- Empty file redirect
*/
| 131 | 17.857143 | 41 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/freebsd/include/linux/kdev_t.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* linux/kdev_t.h -- Empty file redirect
*/
| 130 | 17.714286 | 40 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/freebsd/include/linux/limits.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* linux/limits.h -- Empty file redirect
*/
| 130 | 17.714286 | 40 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/core/os_windows.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
/*
* Copyright (c) 2016, Microsoft Corporation. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* os_windows.c -- windows abstraction layer
*/
#include <io.h>
#include <sys/locking.h>
#include <errno.h>
#include <pmemcompat.h>
#include <windows.h>
#include "alloc.h"
#include "util.h"
#include "os.h"
#include "out.h"
#define UTF8_BOM "\xEF\xBB\xBF"
/*
* os_open -- open abstraction layer
*/
int
os_open(const char *pathname, int flags, ...)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return -1;
int ret;
if (flags & O_CREAT) {
va_list arg;
va_start(arg, flags);
mode_t mode = va_arg(arg, mode_t);
va_end(arg);
ret = _wopen(path, flags, mode);
} else {
ret = _wopen(path, flags);
}
util_free_UTF16(path);
/* BOM skipping should not modify errno */
int orig_errno = errno;
/*
* text files on windows can contain BOM. As we open files
* in binary mode we have to detect bom and skip it
*/
if (ret != -1) {
char bom[3];
if (_read(ret, bom, sizeof(bom)) != 3 ||
memcmp(bom, UTF8_BOM, 3) != 0) {
/* UTF-8 bom not found - reset file to the beginning */
_lseek(ret, 0, SEEK_SET);
}
}
errno = orig_errno;
return ret;
}
/*
* os_fsync -- fsync abstraction layer
*/
int
os_fsync(int fd)
{
HANDLE handle = (HANDLE) _get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE) {
errno = EBADF;
return -1;
}
if (!FlushFileBuffers(handle)) {
errno = EINVAL;
return -1;
}
return 0;
}
/*
* os_fsync_dir -- fsync the directory
*/
int
os_fsync_dir(const char *dir_name)
{
/* XXX not used and not implemented */
ASSERT(0);
return -1;
}
/*
* os_stat -- stat abstraction layer
*/
int
os_stat(const char *pathname, os_stat_t *buf)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return -1;
int ret = _wstat64(path, buf);
util_free_UTF16(path);
return ret;
}
/*
* os_unlink -- unlink abstraction layer
*/
int
os_unlink(const char *pathname)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return -1;
int ret = _wunlink(path);
util_free_UTF16(path);
return ret;
}
/*
* os_access -- access abstraction layer
*/
int
os_access(const char *pathname, int mode)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return -1;
int ret = _waccess(path, mode);
util_free_UTF16(path);
return ret;
}
/*
* os_skipBOM -- (internal) Skip BOM in file stream
*
* text files on windows can contain BOM. We have to detect bom and skip it.
*/
static void
os_skipBOM(FILE *file)
{
if (file == NULL)
return;
/* BOM skipping should not modify errno */
int orig_errno = errno;
/* UTF-8 BOM */
uint8_t bom[3];
size_t read_num = fread(bom, sizeof(bom[0]), sizeof(bom), file);
if (read_num != ARRAY_SIZE(bom))
goto out;
if (memcmp(bom, UTF8_BOM, ARRAY_SIZE(bom)) != 0) {
/* UTF-8 bom not found - reset file to the beginning */
fseek(file, 0, SEEK_SET);
}
out:
errno = orig_errno;
}
/*
* os_fopen -- fopen abstraction layer
*/
FILE *
os_fopen(const char *pathname, const char *mode)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return NULL;
wchar_t *wmode = util_toUTF16(mode);
if (wmode == NULL) {
util_free_UTF16(path);
return NULL;
}
FILE *ret = _wfopen(path, wmode);
util_free_UTF16(path);
util_free_UTF16(wmode);
os_skipBOM(ret);
return ret;
}
/*
* os_fdopen -- fdopen abstraction layer
*/
FILE *
os_fdopen(int fd, const char *mode)
{
FILE *ret = fdopen(fd, mode);
os_skipBOM(ret);
return ret;
}
/*
* os_chmod -- chmod abstraction layer
*/
int
os_chmod(const char *pathname, mode_t mode)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return -1;
int ret = _wchmod(path, mode);
util_free_UTF16(path);
return ret;
}
/*
* os_mkstemp -- generate a unique temporary filename from template
*/
int
os_mkstemp(char *temp)
{
unsigned rnd;
wchar_t *utemp = util_toUTF16(temp);
if (utemp == NULL)
return -1;
wchar_t *path = _wmktemp(utemp);
if (path == NULL) {
util_free_UTF16(utemp);
return -1;
}
wchar_t *npath = Malloc(sizeof(*npath) * wcslen(path) + _MAX_FNAME);
if (npath == NULL) {
util_free_UTF16(utemp);
return -1;
}
wcscpy(npath, path);
util_free_UTF16(utemp);
/*
* Use rand_s to generate more unique tmp file name than _mktemp do.
* In case with multiple threads and multiple files even after close()
* file name conflicts occurred.
* It resolved issue with synchronous removing
* multiples files by system.
*/
rand_s(&rnd);
int ret = _snwprintf(npath + wcslen(npath), _MAX_FNAME, L"%u", rnd);
if (ret < 0)
goto out;
/*
* Use O_TEMPORARY flag to make sure the file is deleted when
* the last file descriptor is closed. Also, it prevents opening
* this file from another process.
*/
ret = _wopen(npath, O_RDWR | O_CREAT | O_EXCL | O_TEMPORARY,
S_IWRITE | S_IREAD);
out:
Free(npath);
return ret;
}
/*
* os_posix_fallocate -- allocate file space
*/
int
os_posix_fallocate(int fd, os_off_t offset, os_off_t len)
{
/*
* From POSIX:
* "EINVAL -- The len argument was zero or the offset argument was
* less than zero."
*
* From Linux man-page:
* "EINVAL -- offset was less than 0, or len was less than or
* equal to 0"
*/
if (offset < 0 || len <= 0)
return EINVAL;
/*
* From POSIX:
* "EFBIG -- The value of offset+len is greater than the maximum
* file size."
*
* Overflow can't be checked for by _chsize_s, since it only gets
* the sum.
*/
if (offset + len < offset)
return EFBIG;
HANDLE handle = (HANDLE)_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE) {
return errno;
}
FILE_ATTRIBUTE_TAG_INFO attributes;
if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo,
&attributes, sizeof(attributes))) {
return EINVAL;
}
/*
* To physically allocate space on windows we have to remove
* sparsefile and file compressed flags. This method is much faster
* than using _chsize_s which has terrible performance. Dax on
* windows doesn't support sparse files and file compression so
* this workaround is acceptable.
*/
if (attributes.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE) {
DWORD unused;
FILE_SET_SPARSE_BUFFER buffer;
buffer.SetSparse = FALSE;
if (!DeviceIoControl(handle, FSCTL_SET_SPARSE, &buffer,
sizeof(buffer), NULL, 0, &unused,
NULL)) {
return EINVAL;
}
}
if (attributes.FileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
DWORD unused;
USHORT buffer = 0; /* magic undocumented value */
if (!DeviceIoControl(handle, FSCTL_SET_COMPRESSION,
&buffer, sizeof(buffer), NULL, 0,
&unused, NULL)) {
return EINVAL;
}
}
/*
* posix_fallocate should not clobber errno, but
* _filelengthi64 might set errno.
*/
int orig_errno = errno;
__int64 current_size = _filelengthi64(fd);
int file_length_errno = errno;
errno = orig_errno;
if (current_size < 0)
return file_length_errno;
__int64 requested_size = offset + len;
if (requested_size <= current_size)
return 0;
int ret = os_ftruncate(fd, requested_size);
if (ret) {
errno = ret;
return -1;
}
return 0;
}
/*
* os_ftruncate -- truncate a file to a specified length
*/
int
os_ftruncate(int fd, os_off_t length)
{
LARGE_INTEGER distanceToMove = {0};
distanceToMove.QuadPart = length;
HANDLE handle = (HANDLE)_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE)
return -1;
if (!SetFilePointerEx(handle, distanceToMove, NULL, FILE_BEGIN)) {
errno = EINVAL;
return -1;
}
if (!SetEndOfFile(handle)) {
errno = EINVAL;
return -1;
}
return 0;
}
/*
* os_flock -- apply or remove an advisory lock on an open file
*/
int
os_flock(int fd, int operation)
{
int flags = 0;
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
switch (operation & (OS_LOCK_EX | OS_LOCK_SH | OS_LOCK_UN)) {
case OS_LOCK_EX:
case OS_LOCK_SH:
if (operation & OS_LOCK_NB)
flags = _LK_NBLCK;
else
flags = _LK_LOCK;
break;
case OS_LOCK_UN:
flags = _LK_UNLCK;
break;
default:
errno = EINVAL;
return -1;
}
os_off_t filelen = _filelengthi64(fd);
if (filelen < 0)
return -1;
/* for our purpose it's enough to lock the first page of the file */
long len = (filelen > systemInfo.dwPageSize) ?
systemInfo.dwPageSize : (long)filelen;
int res = _locking(fd, flags, len);
if (res != 0 && errno == EACCES)
errno = EWOULDBLOCK; /* for consistency with flock() */
return res;
}
/*
* os_writev -- windows version of writev function
*
* XXX: _write and other similar functions are 32 bit on windows
* if size of data is bigger then 2^32, this function
* will be not atomic.
*/
ssize_t
os_writev(int fd, const struct iovec *iov, int iovcnt)
{
size_t size = 0;
/* XXX: _write is 32 bit on windows */
for (int i = 0; i < iovcnt; i++)
size += iov[i].iov_len;
void *buf = malloc(size);
if (buf == NULL)
return ENOMEM;
char *it_buf = buf;
for (int i = 0; i < iovcnt; i++) {
memcpy(it_buf, iov[i].iov_base, iov[i].iov_len);
it_buf += iov[i].iov_len;
}
ssize_t written = 0;
while (size > 0) {
int ret = _write(fd, buf, size >= MAXUINT ?
MAXUINT : (unsigned)size);
if (ret == -1) {
written = -1;
break;
}
written += ret;
size -= ret;
}
free(buf);
return written;
}
#define NSEC_IN_SEC 1000000000ull
/* number of useconds between 1970-01-01T00:00:00Z and 1601-01-01T00:00:00Z */
#define DELTA_WIN2UNIX (11644473600000000ull)
/*
* clock_gettime -- returns elapsed time since the system was restarted
* or since Epoch, depending on the mode id
*/
int
os_clock_gettime(int id, struct timespec *ts)
{
switch (id) {
case CLOCK_MONOTONIC:
{
LARGE_INTEGER time;
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&time);
ts->tv_sec = time.QuadPart / frequency.QuadPart;
ts->tv_nsec = (long)(
(time.QuadPart % frequency.QuadPart) *
NSEC_IN_SEC / frequency.QuadPart);
}
break;
case CLOCK_REALTIME:
{
FILETIME ctime_ft;
GetSystemTimeAsFileTime(&ctime_ft);
ULARGE_INTEGER ctime = {
.HighPart = ctime_ft.dwHighDateTime,
.LowPart = ctime_ft.dwLowDateTime,
};
ts->tv_sec = (ctime.QuadPart - DELTA_WIN2UNIX * 10)
/ 10000000;
ts->tv_nsec = ((ctime.QuadPart - DELTA_WIN2UNIX * 10)
% 10000000) * 100;
}
break;
default:
SetLastError(EINVAL);
return -1;
}
return 0;
}
/*
* os_setenv -- change or add an environment variable
*/
int
os_setenv(const char *name, const char *value, int overwrite)
{
errno_t err;
/*
* If caller doesn't want to overwrite make sure that a environment
* variable with the same name doesn't exist.
*/
if (!overwrite && getenv(name))
return 0;
/*
* _putenv_s returns a non-zero error code on failure but setenv
* needs to return -1 on failure, let's translate the error code.
*/
if ((err = _putenv_s(name, value)) != 0) {
errno = err;
return -1;
}
return 0;
}
/*
* os_unsetenv -- remove an environment variable
*/
int
os_unsetenv(const char *name)
{
errno_t err;
if ((err = _putenv_s(name, "")) != 0) {
errno = err;
return -1;
}
return 0;
}
/*
* os_getenv -- getenv abstraction layer
*/
char *
os_getenv(const char *name)
{
return getenv(name);
}
/*
* rand_r -- rand_r for windows
*
* XXX: RAND_MAX is equal 0x7fff on Windows, so to get 32 bit random number
* we need to merge two numbers returned by rand_s().
* It is not to the best solution as subsequences returned by rand_s are
* not guaranteed to be independent.
*
* XXX: Windows doesn't implement deterministic thread-safe pseudorandom
* generator (generator which can be initialized by seed ).
* We have to chose between a deterministic nonthread-safe generator
* (rand(), srand()) or a non-deterministic thread-safe generator(rand_s())
* as thread-safety is more important, a seed parameter is ignored in this
* implementation.
*/
unsigned
os_rand_r(unsigned *seedp)
{
UNREFERENCED_PARAMETER(seedp);
unsigned part1, part2;
rand_s(&part1);
rand_s(&part2);
return part1 << 16 | part2;
}
/*
* sys_siglist -- map of signal to human readable messages like sys_siglist
*/
const char * const sys_siglist[] = {
"Unknown signal 0", /* 0 */
"Hangup", /* 1 */
"Interrupt", /* 2 */
"Quit", /* 3 */
"Illegal instruction", /* 4 */
"Trace/breakpoint trap", /* 5 */
"Aborted", /* 6 */
"Bus error", /* 7 */
"Floating point exception", /* 8 */
"Killed", /* 9 */
"User defined signal 1", /* 10 */
"Segmentation fault", /* 11 */
"User defined signal 2", /* 12 */
"Broken pipe", /* 13 */
"Alarm clock", /* 14 */
"Terminated", /* 15 */
"Stack fault", /* 16 */
"Child exited", /* 17 */
"Continued", /* 18 */
"Stopped (signal)", /* 19 */
"Stopped", /* 20 */
"Stopped (tty input)", /* 21 */
"Stopped (tty output)", /* 22 */
"Urgent I/O condition", /* 23 */
"CPU time limit exceeded", /* 24 */
"File size limit exceeded", /* 25 */
"Virtual timer expired", /* 26 */
"Profiling timer expired", /* 27 */
"Window changed", /* 28 */
"I/O possible", /* 29 */
"Power failure", /* 30 */
"Bad system call", /* 31 */
"Unknown signal 32" /* 32 */
};
int sys_siglist_size = ARRAYSIZE(sys_siglist);
/*
* string constants for strsignal
* XXX: ideally this should have the signal number as the suffix but then we
* should use a buffer from thread local storage, so deferring the same till
* we need it
* NOTE: In Linux strsignal uses TLS for the same reason but if it fails to get
* a thread local buffer it falls back to using a static buffer trading the
* thread safety.
*/
#define STR_REALTIME_SIGNAL "Real-time signal"
#define STR_UNKNOWN_SIGNAL "Unknown signal"
/*
* strsignal -- returns a string describing the signal number 'sig'
*
* XXX: According to POSIX, this one is of type 'char *', but in our
* implementation it returns 'const char *'.
*/
const char *
os_strsignal(int sig)
{
if (sig >= 0 && sig < ARRAYSIZE(sys_siglist))
return sys_siglist[sig];
else if (sig >= 34 && sig <= 64)
return STR_REALTIME_SIGNAL;
else
return STR_UNKNOWN_SIGNAL;
}
int
os_execv(const char *path, char *const argv[])
{
wchar_t *wpath = util_toUTF16(path);
if (wpath == NULL)
return -1;
int argc = 0;
while (argv[argc])
argc++;
int ret;
wchar_t **wargv = Zalloc((argc + 1) * sizeof(wargv[0]));
if (!wargv) {
ret = -1;
goto wargv_alloc_failed;
}
for (int i = 0; i < argc; ++i) {
wargv[i] = util_toUTF16(argv[i]);
if (!wargv[i]) {
ret = -1;
goto end;
}
}
intptr_t iret = _wexecv(wpath, wargv);
if (iret == 0)
ret = 0;
else
ret = -1;
end:
for (int i = 0; i < argc; ++i)
util_free_UTF16(wargv[i]);
Free(wargv);
wargv_alloc_failed:
util_free_UTF16(wpath);
return ret;
}
| 16,299 | 20.967655 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/core/os_thread_posix.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
/*
* os_thread_posix.c -- Posix thread abstraction layer
*/
#define _GNU_SOURCE
#include <pthread.h>
#ifdef __FreeBSD__
#include <pthread_np.h>
#endif
#include <semaphore.h>
#include "os_thread.h"
#include "util.h"
typedef struct {
pthread_t thread;
} internal_os_thread_t;
/*
* os_once -- pthread_once abstraction layer
*/
int
os_once(os_once_t *o, void (*func)(void))
{
COMPILE_ERROR_ON(sizeof(os_once_t) < sizeof(pthread_once_t));
return pthread_once((pthread_once_t *)o, func);
}
/*
* os_tls_key_create -- pthread_key_create abstraction layer
*/
int
os_tls_key_create(os_tls_key_t *key, void (*destructor)(void *))
{
COMPILE_ERROR_ON(sizeof(os_tls_key_t) < sizeof(pthread_key_t));
return pthread_key_create((pthread_key_t *)key, destructor);
}
/*
* os_tls_key_delete -- pthread_key_delete abstraction layer
*/
int
os_tls_key_delete(os_tls_key_t key)
{
return pthread_key_delete((pthread_key_t)key);
}
/*
* os_tls_setspecific -- pthread_key_setspecific abstraction layer
*/
int
os_tls_set(os_tls_key_t key, const void *value)
{
return pthread_setspecific((pthread_key_t)key, value);
}
/*
* os_tls_get -- pthread_key_getspecific abstraction layer
*/
void *
os_tls_get(os_tls_key_t key)
{
return pthread_getspecific((pthread_key_t)key);
}
/*
* os_mutex_init -- pthread_mutex_init abstraction layer
*/
int
os_mutex_init(os_mutex_t *__restrict mutex)
{
COMPILE_ERROR_ON(sizeof(os_mutex_t) < sizeof(pthread_mutex_t));
return pthread_mutex_init((pthread_mutex_t *)mutex, NULL);
}
/*
* os_mutex_destroy -- pthread_mutex_destroy abstraction layer
*/
int
os_mutex_destroy(os_mutex_t *__restrict mutex)
{
return pthread_mutex_destroy((pthread_mutex_t *)mutex);
}
/*
* os_mutex_lock -- pthread_mutex_lock abstraction layer
*/
int
os_mutex_lock(os_mutex_t *__restrict mutex)
{
return pthread_mutex_lock((pthread_mutex_t *)mutex);
}
/*
* os_mutex_trylock -- pthread_mutex_trylock abstraction layer
*/
int
os_mutex_trylock(os_mutex_t *__restrict mutex)
{
return pthread_mutex_trylock((pthread_mutex_t *)mutex);
}
/*
* os_mutex_unlock -- pthread_mutex_unlock abstraction layer
*/
int
os_mutex_unlock(os_mutex_t *__restrict mutex)
{
return pthread_mutex_unlock((pthread_mutex_t *)mutex);
}
/*
* os_mutex_timedlock -- pthread_mutex_timedlock abstraction layer
*/
int
os_mutex_timedlock(os_mutex_t *__restrict mutex,
const struct timespec *abstime)
{
return pthread_mutex_timedlock((pthread_mutex_t *)mutex, abstime);
}
/*
* os_rwlock_init -- pthread_rwlock_init abstraction layer
*/
int
os_rwlock_init(os_rwlock_t *__restrict rwlock)
{
COMPILE_ERROR_ON(sizeof(os_rwlock_t) < sizeof(pthread_rwlock_t));
return pthread_rwlock_init((pthread_rwlock_t *)rwlock, NULL);
}
/*
* os_rwlock_destroy -- pthread_rwlock_destroy abstraction layer
*/
int
os_rwlock_destroy(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_destroy((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_rdlock - pthread_rwlock_rdlock abstraction layer
*/
int
os_rwlock_rdlock(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_rdlock((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_wrlock -- pthread_rwlock_wrlock abstraction layer
*/
int
os_rwlock_wrlock(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_wrlock((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_unlock -- pthread_rwlock_unlock abstraction layer
*/
int
os_rwlock_unlock(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_unlock((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_tryrdlock -- pthread_rwlock_tryrdlock abstraction layer
*/
int
os_rwlock_tryrdlock(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_tryrdlock((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_tryrwlock -- pthread_rwlock_trywrlock abstraction layer
*/
int
os_rwlock_trywrlock(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_trywrlock((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_timedrdlock -- pthread_rwlock_timedrdlock abstraction layer
*/
int
os_rwlock_timedrdlock(os_rwlock_t *__restrict rwlock,
const struct timespec *abstime)
{
return pthread_rwlock_timedrdlock((pthread_rwlock_t *)rwlock, abstime);
}
/*
* os_rwlock_timedwrlock -- pthread_rwlock_timedwrlock abstraction layer
*/
int
os_rwlock_timedwrlock(os_rwlock_t *__restrict rwlock,
const struct timespec *abstime)
{
return pthread_rwlock_timedwrlock((pthread_rwlock_t *)rwlock, abstime);
}
/*
* os_spin_init -- pthread_spin_init abstraction layer
*/
int
os_spin_init(os_spinlock_t *lock, int pshared)
{
COMPILE_ERROR_ON(sizeof(os_spinlock_t) < sizeof(pthread_spinlock_t));
return pthread_spin_init((pthread_spinlock_t *)lock, pshared);
}
/*
* os_spin_destroy -- pthread_spin_destroy abstraction layer
*/
int
os_spin_destroy(os_spinlock_t *lock)
{
return pthread_spin_destroy((pthread_spinlock_t *)lock);
}
/*
* os_spin_lock -- pthread_spin_lock abstraction layer
*/
int
os_spin_lock(os_spinlock_t *lock)
{
return pthread_spin_lock((pthread_spinlock_t *)lock);
}
/*
* os_spin_unlock -- pthread_spin_unlock abstraction layer
*/
int
os_spin_unlock(os_spinlock_t *lock)
{
return pthread_spin_unlock((pthread_spinlock_t *)lock);
}
/*
* os_spin_trylock -- pthread_spin_trylock abstraction layer
*/
int
os_spin_trylock(os_spinlock_t *lock)
{
return pthread_spin_trylock((pthread_spinlock_t *)lock);
}
/*
* os_cond_init -- pthread_cond_init abstraction layer
*/
int
os_cond_init(os_cond_t *__restrict cond)
{
COMPILE_ERROR_ON(sizeof(os_cond_t) < sizeof(pthread_cond_t));
return pthread_cond_init((pthread_cond_t *)cond, NULL);
}
/*
* os_cond_destroy -- pthread_cond_destroy abstraction layer
*/
int
os_cond_destroy(os_cond_t *__restrict cond)
{
return pthread_cond_destroy((pthread_cond_t *)cond);
}
/*
* os_cond_broadcast -- pthread_cond_broadcast abstraction layer
*/
int
os_cond_broadcast(os_cond_t *__restrict cond)
{
return pthread_cond_broadcast((pthread_cond_t *)cond);
}
/*
* os_cond_signal -- pthread_cond_signal abstraction layer
*/
int
os_cond_signal(os_cond_t *__restrict cond)
{
return pthread_cond_signal((pthread_cond_t *)cond);
}
/*
* os_cond_timedwait -- pthread_cond_timedwait abstraction layer
*/
int
os_cond_timedwait(os_cond_t *__restrict cond,
os_mutex_t *__restrict mutex, const struct timespec *abstime)
{
return pthread_cond_timedwait((pthread_cond_t *)cond,
(pthread_mutex_t *)mutex, abstime);
}
/*
* os_cond_wait -- pthread_cond_wait abstraction layer
*/
int
os_cond_wait(os_cond_t *__restrict cond,
os_mutex_t *__restrict mutex)
{
return pthread_cond_wait((pthread_cond_t *)cond,
(pthread_mutex_t *)mutex);
}
/*
* os_thread_create -- pthread_create abstraction layer
*/
int
os_thread_create(os_thread_t *thread, const os_thread_attr_t *attr,
void *(*start_routine)(void *), void *arg)
{
COMPILE_ERROR_ON(sizeof(os_thread_t) < sizeof(internal_os_thread_t));
internal_os_thread_t *thread_info = (internal_os_thread_t *)thread;
return pthread_create(&thread_info->thread, (pthread_attr_t *)attr,
start_routine, arg);
}
/*
* os_thread_join -- pthread_join abstraction layer
*/
int
os_thread_join(os_thread_t *thread, void **result)
{
internal_os_thread_t *thread_info = (internal_os_thread_t *)thread;
return pthread_join(thread_info->thread, result);
}
/*
* os_thread_self -- pthread_self abstraction layer
*/
void
os_thread_self(os_thread_t *thread)
{
internal_os_thread_t *thread_info = (internal_os_thread_t *)thread;
thread_info->thread = pthread_self();
}
/*
* os_thread_atfork -- pthread_atfork abstraction layer
*/
int
os_thread_atfork(void (*prepare)(void), void (*parent)(void),
void (*child)(void))
{
return pthread_atfork(prepare, parent, child);
}
/*
* os_thread_setaffinity_np -- pthread_atfork abstraction layer
*/
int
os_thread_setaffinity_np(os_thread_t *thread, size_t set_size,
const os_cpu_set_t *set)
{
COMPILE_ERROR_ON(sizeof(os_cpu_set_t) < sizeof(cpu_set_t));
internal_os_thread_t *thread_info = (internal_os_thread_t *)thread;
return pthread_setaffinity_np(thread_info->thread, set_size,
(cpu_set_t *)set);
}
/*
* os_cpu_zero -- CP_ZERO abstraction layer
*/
void
os_cpu_zero(os_cpu_set_t *set)
{
CPU_ZERO((cpu_set_t *)set);
}
/*
* os_cpu_set -- CP_SET abstraction layer
*/
void
os_cpu_set(size_t cpu, os_cpu_set_t *set)
{
CPU_SET(cpu, (cpu_set_t *)set);
}
/*
* os_semaphore_init -- initializes semaphore instance
*/
int
os_semaphore_init(os_semaphore_t *sem, unsigned value)
{
COMPILE_ERROR_ON(sizeof(os_semaphore_t) < sizeof(sem_t));
return sem_init((sem_t *)sem, 0, value);
}
/*
* os_semaphore_destroy -- destroys a semaphore instance
*/
int
os_semaphore_destroy(os_semaphore_t *sem)
{
return sem_destroy((sem_t *)sem);
}
/*
* os_semaphore_wait -- decreases the value of the semaphore
*/
int
os_semaphore_wait(os_semaphore_t *sem)
{
return sem_wait((sem_t *)sem);
}
/*
* os_semaphore_trywait -- tries to decrease the value of the semaphore
*/
int
os_semaphore_trywait(os_semaphore_t *sem)
{
return sem_trywait((sem_t *)sem);
}
/*
* os_semaphore_post -- increases the value of the semaphore
*/
int
os_semaphore_post(os_semaphore_t *sem)
{
return sem_post((sem_t *)sem);
}
| 9,190 | 20.032037 | 72 |
c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.