1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <android-base/file.h>
18 #include <android-base/logging.h>
19 #include <android-base/stringprintf.h>
20 #include <android-base/strings.h>
21
22 #include <dirent.h>
23 #include <libdm/dm.h>
24 #include <sys/stat.h>
25 #include <sys/sysmacros.h>
26 #include <sys/types.h>
27 #include "blockdev.h"
28
29 using android::base::Basename;
30 using android::base::ErrnoError;
31 using android::base::Error;
32 using android::base::Result;
33 using android::base::ResultError;
34 using android::base::StartsWith;
35 using android::base::StringPrintf;
36 using android::base::unique_fd;
37 using android::dm::DeviceMapper;
38
39 // Return the parent device of a partition. Converts e.g. "sda26" into "sda".
PartitionParent(const std::string & blockdev)40 static std::string PartitionParent(const std::string& blockdev) {
41 if (blockdev.find('/') != std::string::npos) {
42 LOG(ERROR) << __func__ << ": invalid argument " << blockdev;
43 return blockdev;
44 }
45 auto dir = std::unique_ptr<DIR, decltype(&closedir)>{opendir("/sys/class/block"), closedir};
46 if (!dir) {
47 return blockdev;
48 }
49 for (struct dirent* ent = readdir(dir.get()); ent; ent = readdir(dir.get())) {
50 if (ent->d_name[0] == '.') {
51 continue;
52 }
53 std::string path = StringPrintf("/sys/class/block/%s/%s", ent->d_name, blockdev.c_str());
54 struct stat statbuf;
55 if (stat(path.c_str(), &statbuf) >= 0) {
56 return ent->d_name;
57 }
58 }
59 return blockdev;
60 }
61
62 // Convert a major:minor pair into a block device name.
BlockdevName(dev_t dev)63 static std::string BlockdevName(dev_t dev) {
64 auto dir = std::unique_ptr<DIR, decltype(&closedir)>{opendir("/dev/block"), closedir};
65 if (!dir) {
66 return {};
67 }
68 for (struct dirent* ent = readdir(dir.get()); ent; ent = readdir(dir.get())) {
69 if (ent->d_name[0] == '.') {
70 continue;
71 }
72 const std::string path = std::string("/dev/block/") + ent->d_name;
73 struct stat statbuf;
74 if (stat(path.c_str(), &statbuf) >= 0 && dev == statbuf.st_rdev) {
75 return ent->d_name;
76 }
77 }
78 return {};
79 }
80
81 // Trim whitespace from the end of a string.
rtrim(std::string & s)82 static void rtrim(std::string& s) {
83 s.erase(s.find_last_not_of('\n') + 1, s.length());
84 }
85
86 // For file `file_path`, retrieve the block device backing the filesystem on
87 // which the file exists and return the queue depth of the block device.
BlockDeviceQueueDepth(const std::string & file_path)88 static Result<uint32_t> BlockDeviceQueueDepth(const std::string& file_path) {
89 struct stat statbuf;
90 int res = stat(file_path.c_str(), &statbuf);
91 if (res < 0) {
92 return ErrnoError() << "stat(" << file_path << ")";
93 }
94 std::string blockdev = "/dev/block/" + BlockdevName(statbuf.st_dev);
95 LOG(DEBUG) << __func__ << ": " << file_path << " -> " << blockdev;
96 if (blockdev.empty()) {
97 const std::string err_msg =
98 StringPrintf("Failed to convert %u:%u (path %s)", major(statbuf.st_dev),
99 minor(statbuf.st_dev), file_path.c_str());
100 return ResultError(err_msg, 0);
101 }
102 auto& dm = DeviceMapper::Instance();
103 for (;;) {
104 std::optional<std::string> child = dm.GetParentBlockDeviceByPath(blockdev);
105 if (!child) {
106 break;
107 }
108 LOG(DEBUG) << __func__ << ": " << blockdev << " -> " << *child;
109 blockdev = *child;
110 }
111 std::optional<std::string> maybe_blockdev = android::dm::ExtractBlockDeviceName(blockdev);
112 if (!maybe_blockdev) {
113 return ResultError("Failed to remove /dev/block/ prefix from " + blockdev, 0);
114 }
115 blockdev = PartitionParent(*maybe_blockdev);
116 LOG(DEBUG) << __func__ << ": "
117 << "Partition parent: " << blockdev;
118 const std::string nr_tags_path =
119 StringPrintf("/sys/class/block/%s/mq/0/nr_tags", blockdev.c_str());
120 std::string nr_tags;
121 if (!android::base::ReadFileToString(nr_tags_path, &nr_tags)) {
122 return ResultError("Failed to read " + nr_tags_path, 0);
123 }
124 rtrim(nr_tags);
125 LOG(DEBUG) << __func__ << ": " << file_path << " is backed by /dev/" << blockdev
126 << " and that block device supports queue depth " << nr_tags;
127 return strtol(nr_tags.c_str(), NULL, 0);
128 }
129
130 // Set 'nr_requests' of `loop_device_path` to the queue depth of the block
131 // device backing `file_path`.
ConfigureQueueDepth(const std::string & loop_device_path,const std::string & file_path)132 Result<void> ConfigureQueueDepth(const std::string& loop_device_path,
133 const std::string& file_path) {
134 if (!StartsWith(loop_device_path, "/dev/")) {
135 return Error() << "Invalid argument " << loop_device_path;
136 }
137
138 const std::string loop_device_name = Basename(loop_device_path);
139
140 const Result<uint32_t> qd = BlockDeviceQueueDepth(file_path);
141 if (!qd.ok()) {
142 LOG(DEBUG) << __func__ << ": "
143 << "BlockDeviceQueueDepth() returned " << qd.error();
144 return ResultError(qd.error());
145 }
146 const std::string nr_requests = StringPrintf("%u", *qd);
147 const std::string sysfs_path =
148 StringPrintf("/sys/class/block/%s/queue/nr_requests", loop_device_name.c_str());
149 unique_fd sysfs_fd(open(sysfs_path.c_str(), O_RDWR | O_CLOEXEC));
150 if (sysfs_fd == -1) {
151 return ErrnoError() << "Failed to open " << sysfs_path;
152 }
153
154 const int res = write(sysfs_fd.get(), nr_requests.data(), nr_requests.length());
155 if (res < 0) {
156 return ErrnoError() << "Failed to write to " << sysfs_path;
157 }
158 return {};
159 }
160