2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "IdleMaint.h"
18 #include "FileDeviceUtils.h"
20 #include "VolumeManager.h"
21 #include "model/PrivateVolume.h"
25 #include <android-base/chrono_utils.h>
26 #include <android-base/file.h>
27 #include <android-base/logging.h>
28 #include <android-base/stringprintf.h>
29 #include <android-base/strings.h>
30 #include <android/hardware/health/storage/1.0/IStorage.h>
32 #include <hardware_legacy/power.h>
33 #include <private/android_filesystem_config.h>
37 #include <sys/mount.h>
39 #include <sys/types.h>
42 using android::base::Basename;
43 using android::base::ReadFileToString;
44 using android::base::Realpath;
45 using android::base::StringPrintf;
46 using android::base::Timer;
47 using android::base::WriteStringToFile;
48 using android::fs_mgr::Fstab;
49 using android::fs_mgr::ReadDefaultFstab;
50 using android::hardware::Return;
51 using android::hardware::Void;
52 using android::hardware::health::storage::V1_0::IGarbageCollectCallback;
53 using android::hardware::health::storage::V1_0::IStorage;
54 using android::hardware::health::storage::V1_0::Result;
59 enum class PathTypes {
64 enum class IdleMaintStats {
70 static const char* kWakeLock = "IdleMaint";
71 static const int DIRTY_SEGMENTS_THRESHOLD = 100;
78 static const int GC_TIMEOUT_SEC = 420;
79 static const int DEVGC_TIMEOUT_SEC = 120;
81 static IdleMaintStats idle_maint_stat(IdleMaintStats::kStopped);
82 static std::condition_variable cv_abort, cv_stop;
83 static std::mutex cv_m;
85 static void addFromVolumeManager(std::list<std::string>* paths, PathTypes path_type) {
86 VolumeManager* vm = VolumeManager::Instance();
87 std::list<std::string> privateIds;
88 vm->listVolumes(VolumeBase::Type::kPrivate, privateIds);
89 for (const auto& id : privateIds) {
90 PrivateVolume* vol = static_cast<PrivateVolume*>(vm->findVolume(id).get());
91 if (vol != nullptr && vol->getState() == VolumeBase::State::kMounted) {
92 if (path_type == PathTypes::kMountPoint) {
93 paths->push_back(vol->getPath());
94 } else if (path_type == PathTypes::kBlkDevice) {
96 const std::string& fs_type = vol->getFsType();
97 if (fs_type == "f2fs" && (Realpath(vol->getRawDmDevPath(), &gc_path) ||
98 Realpath(vol->getRawDevPath(), &gc_path))) {
99 paths->push_back(std::string("/sys/fs/") + fs_type + "/" + Basename(gc_path));
106 static void addFromFstab(std::list<std::string>* paths, PathTypes path_type) {
108 ReadDefaultFstab(&fstab);
110 std::string previous_mount_point;
111 for (const auto& entry : fstab) {
112 // Skip raw partitions.
113 if (entry.fs_type == "emmc" || entry.fs_type == "mtd") {
116 // Skip read-only filesystems
117 if (entry.flags & MS_RDONLY) {
120 if (entry.fs_mgr_flags.vold_managed) {
121 continue; // Should we trim fat32 filesystems?
123 if (entry.fs_mgr_flags.no_trim) {
127 // Skip the multi-type partitions, which are required to be following each other.
128 // See fs_mgr.c's mount_with_alternatives().
129 if (entry.mount_point == previous_mount_point) {
133 if (path_type == PathTypes::kMountPoint) {
134 paths->push_back(entry.mount_point);
135 } else if (path_type == PathTypes::kBlkDevice) {
137 if (entry.fs_type == "f2fs" &&
138 Realpath(android::vold::BlockDeviceForPath(entry.mount_point + "/"), &gc_path)) {
139 paths->push_back("/sys/fs/" + entry.fs_type + "/" + Basename(gc_path));
143 previous_mount_point = entry.mount_point;
147 void Trim(const android::sp<android::os::IVoldTaskListener>& listener) {
148 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
150 // Collect both fstab and vold volumes
151 std::list<std::string> paths;
152 addFromFstab(&paths, PathTypes::kMountPoint);
153 addFromVolumeManager(&paths, PathTypes::kMountPoint);
155 for (const auto& path : paths) {
156 LOG(DEBUG) << "Starting trim of " << path;
158 android::os::PersistableBundle extras;
159 extras.putString(String16("path"), String16(path.c_str()));
161 int fd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
163 PLOG(WARNING) << "Failed to open " << path;
165 listener->onStatus(-1, extras);
170 struct fstrim_range range;
171 memset(&range, 0, sizeof(range));
172 range.len = ULLONG_MAX;
174 nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME);
175 if (ioctl(fd, FITRIM, &range)) {
176 PLOG(WARNING) << "Trim failed on " << path;
178 listener->onStatus(-1, extras);
181 nsecs_t time = systemTime(SYSTEM_TIME_BOOTTIME) - start;
182 LOG(INFO) << "Trimmed " << range.len << " bytes on " << path << " in "
183 << nanoseconds_to_milliseconds(time) << "ms";
184 extras.putLong(String16("bytes"), range.len);
185 extras.putLong(String16("time"), time);
187 listener->onStatus(0, extras);
194 android::os::PersistableBundle extras;
195 listener->onFinished(0, extras);
198 release_wake_lock(kWakeLock);
201 static bool waitForGc(const std::list<std::string>& paths) {
202 std::unique_lock<std::mutex> lk(cv_m, std::defer_lock);
203 bool stop = false, aborted = false;
206 while (!stop && !aborted) {
208 for (const auto& path : paths) {
209 std::string dirty_segments;
210 if (!ReadFileToString(path + "/dirty_segments", &dirty_segments)) {
211 PLOG(WARNING) << "Reading dirty_segments failed in " << path;
214 if (std::stoi(dirty_segments) > DIRTY_SEGMENTS_THRESHOLD) {
222 if (timer.duration() >= std::chrono::seconds(GC_TIMEOUT_SEC)) {
223 LOG(WARNING) << "GC timeout";
229 cv_abort.wait_for(lk, 10s, [] { return idle_maint_stat == IdleMaintStats::kAbort; });
236 static int startGc(const std::list<std::string>& paths) {
237 for (const auto& path : paths) {
238 LOG(DEBUG) << "Start GC on " << path;
239 if (!WriteStringToFile("1", path + "/discard_granularity")) {
240 PLOG(WARNING) << "Set discard gralunarity failed on" << path;
242 if (!WriteStringToFile("1", path + "/gc_urgent")) {
243 PLOG(WARNING) << "Start GC failed on " << path;
249 static int stopGc(const std::list<std::string>& paths) {
250 for (const auto& path : paths) {
251 LOG(DEBUG) << "Stop GC on " << path;
252 if (!WriteStringToFile("0", path + "/gc_urgent")) {
253 PLOG(WARNING) << "Stop GC failed on " << path;
255 if (!WriteStringToFile("16", path + "/discard_granularity")) {
256 PLOG(WARNING) << "Set discard gralunarity failed on" << path;
262 static void runDevGcFstab(void) {
264 ReadDefaultFstab(&fstab);
267 for (const auto& entry : fstab) {
268 if (!entry.sysfs_path.empty()) {
269 path = entry.sysfs_path;
278 path = path + "/manual_gc";
281 LOG(DEBUG) << "Start Dev GC on " << path;
284 if (!ReadFileToString(path, &require)) {
285 PLOG(WARNING) << "Reading manual_gc failed in " << path;
288 require = android::base::Trim(require);
289 if (require == "" || require == "off" || require == "disabled") {
290 LOG(DEBUG) << "No more to do Dev GC";
294 LOG(DEBUG) << "Trigger Dev GC on " << path;
295 if (!WriteStringToFile("1", path)) {
296 PLOG(WARNING) << "Start Dev GC failed on " << path;
300 if (timer.duration() >= std::chrono::seconds(DEVGC_TIMEOUT_SEC)) {
301 LOG(WARNING) << "Dev GC timeout";
306 LOG(DEBUG) << "Stop Dev GC on " << path;
307 if (!WriteStringToFile("0", path)) {
308 PLOG(WARNING) << "Stop Dev GC failed on " << path;
313 class GcCallback : public IGarbageCollectCallback {
315 Return<void> onFinish(Result result) override {
316 std::unique_lock<std::mutex> lock(mMutex);
323 void wait(uint64_t seconds) {
324 std::unique_lock<std::mutex> lock(mMutex);
325 mCv.wait_for(lock, std::chrono::seconds(seconds), [this] { return mFinished; });
328 LOG(WARNING) << "Dev GC on HAL timeout";
329 } else if (mResult != Result::SUCCESS) {
330 LOG(WARNING) << "Dev GC on HAL failed with " << toString(mResult);
332 LOG(INFO) << "Dev GC on HAL successful";
338 std::condition_variable mCv;
339 bool mFinished{false};
340 Result mResult{Result::UNKNOWN_ERROR};
343 static void runDevGcOnHal(sp<IStorage> service) {
344 LOG(DEBUG) << "Start Dev GC on HAL";
345 sp<GcCallback> cb = new GcCallback();
346 auto ret = service->garbageCollect(DEVGC_TIMEOUT_SEC, cb);
348 LOG(WARNING) << "Cannot start Dev GC on HAL: " << ret.description();
351 cb->wait(DEVGC_TIMEOUT_SEC);
354 static void runDevGc(void) {
355 auto service = IStorage::getService();
356 if (service != nullptr) {
357 runDevGcOnHal(service);
359 // fallback to legacy code path
364 int RunIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener) {
365 std::unique_lock<std::mutex> lk(cv_m);
366 if (idle_maint_stat != IdleMaintStats::kStopped) {
367 LOG(DEBUG) << "idle maintenance is already running";
369 android::os::PersistableBundle extras;
370 listener->onFinished(0, extras);
374 idle_maint_stat = IdleMaintStats::kRunning;
377 LOG(DEBUG) << "idle maintenance started";
379 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
381 std::list<std::string> paths;
382 addFromFstab(&paths, PathTypes::kBlkDevice);
383 addFromVolumeManager(&paths, PathTypes::kBlkDevice);
387 bool gc_aborted = waitForGc(paths);
392 idle_maint_stat = IdleMaintStats::kStopped;
395 cv_stop.notify_one();
403 android::os::PersistableBundle extras;
404 listener->onFinished(0, extras);
407 LOG(DEBUG) << "idle maintenance completed";
409 release_wake_lock(kWakeLock);
414 int AbortIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener) {
415 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
417 std::unique_lock<std::mutex> lk(cv_m);
418 if (idle_maint_stat != IdleMaintStats::kStopped) {
419 idle_maint_stat = IdleMaintStats::kAbort;
421 cv_abort.notify_one();
423 LOG(DEBUG) << "aborting idle maintenance";
424 cv_stop.wait(lk, [] { return idle_maint_stat == IdleMaintStats::kStopped; });
429 android::os::PersistableBundle extras;
430 listener->onFinished(0, extras);
433 release_wake_lock(kWakeLock);
435 LOG(DEBUG) << "idle maintenance stopped";
441 } // namespace android