Skip to content

Commit 0d45eca

Browse files
authored
Merge pull request ceph#46122 from tchaikov/wip-pmem
blk/pmem: refactor pmem_check_file_type() using std::filesystem Reviewed-by: Radoslaw Zarzynski <[email protected]>
2 parents b3e725a + 7f0a779 commit 0d45eca

File tree

1 file changed

+23
-39
lines changed

1 file changed

+23
-39
lines changed

src/blk/pmem/PMEMDevice.cc

Lines changed: 23 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@
2323
#include <errno.h>
2424
#include <fcntl.h>
2525
#include <string.h>
26+
#include <filesystem>
27+
#include <fstream>
28+
29+
#include <fmt/format.h>
2630

2731
#include "PMEMDevice.h"
2832
#include "libpmem.h"
@@ -66,51 +70,31 @@ int PMEMDevice::_lock()
6670

6771
static int pmem_check_file_type(int fd, const char *pmem_file, uint64_t *total_size)
6872
{
69-
int rc = 0;
70-
struct stat file_stat;
71-
72-
rc = ::fstat(fd, &file_stat);
73-
if (rc) {
74-
return -1;
75-
}
76-
77-
if ((file_stat.st_mode & S_IFCHR) != S_IFCHR) {
78-
return -1;
73+
namespace fs = std::filesystem;
74+
if (!fs::is_character_file(pmem_file)) {
75+
return -EINVAL;
7976
}
80-
81-
char spath[PATH_MAX], npath[PATH_MAX];
82-
snprintf(spath, PATH_MAX, "/sys/dev/char/%d:%d/subsystem",
83-
major(file_stat.st_rdev), minor(file_stat.st_rdev));
84-
85-
char *real_path = realpath(spath, npath);
86-
if (!real_path) {
87-
return -1;
77+
struct stat file_stat;
78+
if (::fstat(fd, &file_stat)) {
79+
return -EINVAL;
8880
}
89-
81+
fs::path char_dir = fmt::format("/sys/dev/char/{}:{}",
82+
major(file_stat.st_rdev),
83+
minor(file_stat.st_rdev));
9084
// Need to check if it is a DAX device
91-
char *base_name = strrchr(real_path, '/');
92-
if (!base_name || strcmp("dax", base_name + 1)) {
93-
return -1;
85+
if (auto subsys_path = char_dir / "subsystem";
86+
fs::read_symlink(subsys_path).filename().string() != "dax") {
87+
return -EINVAL;
9488
}
95-
96-
snprintf(spath, PATH_MAX, "/sys/dev/char/%d:%d/size",
97-
major(file_stat.st_rdev), minor(file_stat.st_rdev));
98-
FILE *sfile = fopen(spath, "r");
99-
if (!sfile) {
100-
return -1;
89+
if (total_size == nullptr) {
90+
return 0;
10191
}
102-
103-
if (total_size != nullptr) {
104-
rc = fscanf(sfile, "%lu", total_size);
105-
if (rc < 0) {
106-
rc = -1;
107-
} else {
108-
rc = 0;
109-
}
92+
if (std::ifstream size_file(char_dir / "size"); size_file) {
93+
size_file >> *total_size;
94+
return size_file ? 0 : -EINVAL;
95+
} else {
96+
return -EINVAL;
11097
}
111-
112-
fclose(sfile);
113-
return rc;
11498
}
11599

116100
int PMEMDevice::open(const std::string& p)

0 commit comments

Comments
 (0)