Add GetBlockDevSize, GetBlockDevSectors helpers
Helpers to get a block device size in bytes or 512 byte sectors,
using BLKGETSIZE64 and returning value of uint64_t type.
This also removes get_blkdev_size().
Test: build, manual, mount exFAT volume
Bug: 80202067
Change-Id: Ib07e8ac6ef7ff49de0ed570d1fa202e8b558b80c
diff --git a/Utils.cpp b/Utils.cpp
index f085c22..736d721 100644
--- a/Utils.cpp
+++ b/Utils.cpp
@@ -476,6 +476,42 @@
return StrToHex(tmp, out);
}
+status_t GetBlockDevSize(int fd, uint64_t* size) {
+ if (ioctl(fd, BLKGETSIZE64, size)) {
+ return -errno;
+ }
+
+ return OK;
+}
+
+status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
+ int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
+ status_t res = OK;
+
+ if (fd < 0) {
+ return -errno;
+ }
+
+ res = GetBlockDevSize(fd, size);
+
+ close(fd);
+
+ return res;
+}
+
+status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
+ uint64_t size;
+ status_t res = GetBlockDevSize(path, &size);
+
+ if (res != OK) {
+ return res;
+ }
+
+ *nr_sec = size / 512;
+
+ return OK;
+}
+
uint64_t GetFreeBytes(const std::string& path) {
struct statvfs sb;
if (statvfs(path.c_str(), &sb) == 0) {
@@ -560,8 +596,7 @@
status_t WipeBlockDevice(const std::string& path) {
status_t res = -1;
const char* c_path = path.c_str();
- unsigned long nr_sec = 0;
- unsigned long long range[2];
+ uint64_t range[2] = {0, 0};
int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
if (fd == -1) {
@@ -569,14 +604,11 @@
goto done;
}
- if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
+ if (GetBlockDevSize(fd, &range[1]) != OK) {
PLOG(ERROR) << "Failed to determine size of " << path;
goto done;
}
- range[0] = 0;
- range[1] = (unsigned long long)nr_sec * 512;
-
LOG(INFO) << "About to discard " << range[1] << " on " << path;
if (ioctl(fd, BLKDISCARD, &range) == 0) {
LOG(INFO) << "Discard success on " << path;