blob: 0c6b1156980ec23c381054159ba22207c701349c [file] [log] [blame]
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -07001/*
2 * Copyright (C) 2015 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
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -060017#include "IdleMaint.h"
Jaegeuk Kim31e962f2018-07-29 06:56:57 -070018#include "FileDeviceUtils.h"
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070019#include "Utils.h"
Eric Biggers019d5162020-10-15 16:54:38 -070020#include "VoldUtil.h"
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070021#include "VolumeManager.h"
Jin Qiana370c142017-10-17 15:41:45 -070022#include "model/PrivateVolume.h"
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070023
Jin Qiana370c142017-10-17 15:41:45 -070024#include <thread>
Yifan Hong8f0d4542021-01-13 17:10:47 -080025#include <utility>
Jin Qiana370c142017-10-17 15:41:45 -070026
Yifan Honge1e49452021-01-13 17:27:42 -080027#include <aidl/android/hardware/health/storage/BnGarbageCollectCallback.h>
28#include <aidl/android/hardware/health/storage/IStorage.h>
Jin Qiana370c142017-10-17 15:41:45 -070029#include <android-base/chrono_utils.h>
30#include <android-base/file.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080031#include <android-base/logging.h>
Yifan Hong024a1242018-08-10 13:50:46 -070032#include <android-base/stringprintf.h>
33#include <android-base/strings.h>
Yifan Honge1e49452021-01-13 17:27:42 -080034#include <android/binder_manager.h>
Yifan Hong7a37c932018-09-19 10:28:16 -070035#include <android/hardware/health/storage/1.0/IStorage.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070036#include <fs_mgr.h>
Yifan Hong024a1242018-08-10 13:50:46 -070037#include <private/android_filesystem_config.h>
Tri Vo15bbe222019-06-21 12:21:48 -070038#include <wakelock/wakelock.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070039
40#include <dirent.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070041#include <fcntl.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070042#include <sys/mount.h>
43#include <sys/stat.h>
44#include <sys/types.h>
45#include <sys/wait.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070046
Jin Qiana370c142017-10-17 15:41:45 -070047using android::base::Basename;
48using android::base::ReadFileToString;
49using android::base::Realpath;
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070050using android::base::StringPrintf;
Jin Qiana370c142017-10-17 15:41:45 -070051using android::base::Timer;
52using android::base::WriteStringToFile;
Yifan Hong024a1242018-08-10 13:50:46 -070053using android::hardware::Return;
54using android::hardware::Void;
Yifan Honge1e49452021-01-13 17:27:42 -080055using AStorage = aidl::android::hardware::health::storage::IStorage;
56using ABnGarbageCollectCallback =
57 aidl::android::hardware::health::storage::BnGarbageCollectCallback;
58using AResult = aidl::android::hardware::health::storage::Result;
Yifan Hong8f0d4542021-01-13 17:10:47 -080059using HStorage = android::hardware::health::storage::V1_0::IStorage;
60using HGarbageCollectCallback = android::hardware::health::storage::V1_0::IGarbageCollectCallback;
61using HResult = android::hardware::health::storage::V1_0::Result;
Yifan Honge1e49452021-01-13 17:27:42 -080062using std::string_literals::operator""s;
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070063
64namespace android {
65namespace vold {
66
Jin Qiana370c142017-10-17 15:41:45 -070067enum class PathTypes {
68 kMountPoint = 1,
69 kBlkDevice,
70};
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070071
Jin Qiana370c142017-10-17 15:41:45 -070072enum class IdleMaintStats {
73 kStopped = 1,
74 kRunning,
75 kAbort,
76};
77
78static const char* kWakeLock = "IdleMaint";
79static const int DIRTY_SEGMENTS_THRESHOLD = 100;
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -080080/*
81 * Timing policy:
82 * 1. F2FS_GC = 7 mins
83 * 2. Trim = 1 min
84 * 3. Dev GC = 2 mins
85 */
86static const int GC_TIMEOUT_SEC = 420;
87static const int DEVGC_TIMEOUT_SEC = 120;
Daeho Jeong999fceb2022-01-04 11:37:39 -080088static const int KBYTES_IN_SEGMENT = 2048;
Daeho Jeong7c788fc2022-03-18 12:24:41 -070089static const int ONE_MINUTE_IN_MS = 60000;
Daeho Jeong999fceb2022-01-04 11:37:39 -080090static const int GC_NORMAL_MODE = 0;
Daeho Jeong5e879422022-03-15 21:42:55 -070091static const int GC_URGENT_MID_MODE = 3;
Daeho Jeong999fceb2022-01-04 11:37:39 -080092
93static int32_t previousSegmentWrite = 0;
Jin Qiana370c142017-10-17 15:41:45 -070094
95static IdleMaintStats idle_maint_stat(IdleMaintStats::kStopped);
96static std::condition_variable cv_abort, cv_stop;
97static std::mutex cv_m;
98
Paul Crowley14c8c072018-09-18 13:30:21 -070099static void addFromVolumeManager(std::list<std::string>* paths, PathTypes path_type) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700100 VolumeManager* vm = VolumeManager::Instance();
101 std::list<std::string> privateIds;
102 vm->listVolumes(VolumeBase::Type::kPrivate, privateIds);
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700103 for (const auto& id : privateIds) {
Jin Qiana370c142017-10-17 15:41:45 -0700104 PrivateVolume* vol = static_cast<PrivateVolume*>(vm->findVolume(id).get());
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700105 if (vol != nullptr && vol->getState() == VolumeBase::State::kMounted) {
Jin Qiana370c142017-10-17 15:41:45 -0700106 if (path_type == PathTypes::kMountPoint) {
107 paths->push_back(vol->getPath());
108 } else if (path_type == PathTypes::kBlkDevice) {
109 std::string gc_path;
110 const std::string& fs_type = vol->getFsType();
Jaegeuk Kim31e962f2018-07-29 06:56:57 -0700111 if (fs_type == "f2fs" && (Realpath(vol->getRawDmDevPath(), &gc_path) ||
112 Realpath(vol->getRawDevPath(), &gc_path))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700113 paths->push_back(std::string("/sys/fs/") + fs_type + "/" + Basename(gc_path));
Jin Qiana370c142017-10-17 15:41:45 -0700114 }
115 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700116 }
117 }
118}
119
Daeho Jeong999fceb2022-01-04 11:37:39 -0800120static void addFromFstab(std::list<std::string>* paths, PathTypes path_type, bool only_data_part) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800121 std::string previous_mount_point;
Eric Biggers019d5162020-10-15 16:54:38 -0700122 for (const auto& entry : fstab_default) {
Eric Biggers9a3dc8c2020-10-15 16:54:38 -0700123 // Skip raw partitions and swap space.
124 if (entry.fs_type == "emmc" || entry.fs_type == "mtd" || entry.fs_type == "swap") {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700125 continue;
126 }
Eric Biggers9a3dc8c2020-10-15 16:54:38 -0700127 // Skip read-only filesystems and bind mounts.
128 if (entry.flags & (MS_RDONLY | MS_BIND)) {
129 continue;
130 }
131 // Skip anything without an underlying block device, e.g. virtiofs.
132 if (entry.blk_device[0] != '/') {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700133 continue;
134 }
Tom Cherry4c5bde22019-01-29 14:34:01 -0800135 if (entry.fs_mgr_flags.vold_managed) {
136 continue; // Should we trim fat32 filesystems?
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700137 }
Tom Cherry4c5bde22019-01-29 14:34:01 -0800138 if (entry.fs_mgr_flags.no_trim) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700139 continue;
140 }
141
Daeho Jeong999fceb2022-01-04 11:37:39 -0800142 if (only_data_part && entry.mount_point != "/data") {
143 continue;
144 }
145
Tom Cherry4c5bde22019-01-29 14:34:01 -0800146 // Skip the multi-type partitions, which are required to be following each other.
147 // See fs_mgr.c's mount_with_alternatives().
148 if (entry.mount_point == previous_mount_point) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700149 continue;
150 }
151
Jin Qiana370c142017-10-17 15:41:45 -0700152 if (path_type == PathTypes::kMountPoint) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800153 paths->push_back(entry.mount_point);
Jin Qiana370c142017-10-17 15:41:45 -0700154 } else if (path_type == PathTypes::kBlkDevice) {
Daeho Jeong999fceb2022-01-04 11:37:39 -0800155 std::string path;
Tom Cherry4c5bde22019-01-29 14:34:01 -0800156 if (entry.fs_type == "f2fs" &&
Daeho Jeong999fceb2022-01-04 11:37:39 -0800157 Realpath(android::vold::BlockDeviceForPath(entry.mount_point + "/"), &path)) {
158 paths->push_back("/sys/fs/" + entry.fs_type + "/" + Basename(path));
Jin Qiana370c142017-10-17 15:41:45 -0700159 }
160 }
161
Tom Cherry4c5bde22019-01-29 14:34:01 -0800162 previous_mount_point = entry.mount_point;
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700163 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700164}
165
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600166void Trim(const android::sp<android::os::IVoldTaskListener>& listener) {
Kalesh Singh98062dc2021-02-22 15:10:45 -0500167 auto wl = android::wakelock::WakeLock::tryGet(kWakeLock);
168 if (!wl.has_value()) {
169 return;
170 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700171
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600172 // Collect both fstab and vold volumes
173 std::list<std::string> paths;
Daeho Jeong999fceb2022-01-04 11:37:39 -0800174 addFromFstab(&paths, PathTypes::kMountPoint, false);
Jin Qiana370c142017-10-17 15:41:45 -0700175 addFromVolumeManager(&paths, PathTypes::kMountPoint);
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600176
177 for (const auto& path : paths) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700178 LOG(DEBUG) << "Starting trim of " << path;
179
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600180 android::os::PersistableBundle extras;
181 extras.putString(String16("path"), String16(path.c_str()));
182
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700183 int fd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
184 if (fd < 0) {
185 PLOG(WARNING) << "Failed to open " << path;
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600186 if (listener) {
187 listener->onStatus(-1, extras);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600188 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700189 continue;
190 }
191
192 struct fstrim_range range;
193 memset(&range, 0, sizeof(range));
194 range.len = ULLONG_MAX;
195
196 nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME);
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600197 if (ioctl(fd, FITRIM, &range)) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700198 PLOG(WARNING) << "Trim failed on " << path;
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600199 if (listener) {
200 listener->onStatus(-1, extras);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600201 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700202 } else {
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600203 nsecs_t time = systemTime(SYSTEM_TIME_BOOTTIME) - start;
Paul Crowley14c8c072018-09-18 13:30:21 -0700204 LOG(INFO) << "Trimmed " << range.len << " bytes on " << path << " in "
205 << nanoseconds_to_milliseconds(time) << "ms";
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600206 extras.putLong(String16("bytes"), range.len);
207 extras.putLong(String16("time"), time);
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600208 if (listener) {
209 listener->onStatus(0, extras);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600210 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700211 }
212 close(fd);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600213 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700214
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600215 if (listener) {
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600216 android::os::PersistableBundle extras;
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600217 listener->onFinished(0, extras);
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700218 }
219
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700220}
221
Jin Qiana370c142017-10-17 15:41:45 -0700222static bool waitForGc(const std::list<std::string>& paths) {
223 std::unique_lock<std::mutex> lk(cv_m, std::defer_lock);
224 bool stop = false, aborted = false;
225 Timer timer;
226
227 while (!stop && !aborted) {
228 stop = true;
229 for (const auto& path : paths) {
230 std::string dirty_segments;
231 if (!ReadFileToString(path + "/dirty_segments", &dirty_segments)) {
232 PLOG(WARNING) << "Reading dirty_segments failed in " << path;
233 continue;
234 }
235 if (std::stoi(dirty_segments) > DIRTY_SEGMENTS_THRESHOLD) {
236 stop = false;
237 break;
238 }
239 }
240
241 if (stop) break;
242
243 if (timer.duration() >= std::chrono::seconds(GC_TIMEOUT_SEC)) {
244 LOG(WARNING) << "GC timeout";
245 break;
246 }
247
248 lk.lock();
Paul Crowley14c8c072018-09-18 13:30:21 -0700249 aborted =
250 cv_abort.wait_for(lk, 10s, [] { return idle_maint_stat == IdleMaintStats::kAbort; });
Jin Qiana370c142017-10-17 15:41:45 -0700251 lk.unlock();
252 }
253
254 return aborted;
255}
256
257static int startGc(const std::list<std::string>& paths) {
258 for (const auto& path : paths) {
259 LOG(DEBUG) << "Start GC on " << path;
260 if (!WriteStringToFile("1", path + "/gc_urgent")) {
261 PLOG(WARNING) << "Start GC failed on " << path;
262 }
263 }
264 return android::OK;
265}
266
267static int stopGc(const std::list<std::string>& paths) {
268 for (const auto& path : paths) {
269 LOG(DEBUG) << "Stop GC on " << path;
270 if (!WriteStringToFile("0", path + "/gc_urgent")) {
271 PLOG(WARNING) << "Stop GC failed on " << path;
272 }
273 }
274 return android::OK;
275}
276
Daeho Jeong999fceb2022-01-04 11:37:39 -0800277static std::string getDevSysfsPath() {
Eric Biggers019d5162020-10-15 16:54:38 -0700278 for (const auto& entry : fstab_default) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800279 if (!entry.sysfs_path.empty()) {
Daeho Jeong999fceb2022-01-04 11:37:39 -0800280 return entry.sysfs_path;
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -0800281 }
282 }
Daeho Jeong999fceb2022-01-04 11:37:39 -0800283 LOG(WARNING) << "Cannot find dev sysfs path";
284 return "";
285}
Tom Cherry4c5bde22019-01-29 14:34:01 -0800286
Daeho Jeong999fceb2022-01-04 11:37:39 -0800287static void runDevGcFstab(void) {
288 std::string path = getDevSysfsPath();
Tom Cherry4c5bde22019-01-29 14:34:01 -0800289 if (path.empty()) {
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -0800290 return;
291 }
292
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -0800293 path = path + "/manual_gc";
294 Timer timer;
295
296 LOG(DEBUG) << "Start Dev GC on " << path;
297 while (1) {
298 std::string require;
299 if (!ReadFileToString(path, &require)) {
300 PLOG(WARNING) << "Reading manual_gc failed in " << path;
301 break;
302 }
Yifan Hong024a1242018-08-10 13:50:46 -0700303 require = android::base::Trim(require);
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -0800304 if (require == "" || require == "off" || require == "disabled") {
305 LOG(DEBUG) << "No more to do Dev GC";
306 break;
307 }
308
309 LOG(DEBUG) << "Trigger Dev GC on " << path;
310 if (!WriteStringToFile("1", path)) {
311 PLOG(WARNING) << "Start Dev GC failed on " << path;
312 break;
313 }
314
315 if (timer.duration() >= std::chrono::seconds(DEVGC_TIMEOUT_SEC)) {
316 LOG(WARNING) << "Dev GC timeout";
317 break;
318 }
319 sleep(2);
320 }
321 LOG(DEBUG) << "Stop Dev GC on " << path;
322 if (!WriteStringToFile("0", path)) {
323 PLOG(WARNING) << "Stop Dev GC failed on " << path;
324 }
325 return;
326}
327
Yifan Honge1e49452021-01-13 17:27:42 -0800328enum class IDL { HIDL, AIDL };
Yifan Hong8f0d4542021-01-13 17:10:47 -0800329std::ostream& operator<<(std::ostream& os, IDL idl) {
Yifan Honge1e49452021-01-13 17:27:42 -0800330 return os << (idl == IDL::HIDL ? "HIDL" : "AIDL");
Yifan Hong8f0d4542021-01-13 17:10:47 -0800331}
332
333template <IDL idl, typename Result>
334class GcCallbackImpl {
335 protected:
336 void onFinishInternal(Result result) {
Yifan Hong024a1242018-08-10 13:50:46 -0700337 std::unique_lock<std::mutex> lock(mMutex);
338 mFinished = true;
339 mResult = result;
340 lock.unlock();
341 mCv.notify_all();
Yifan Hong024a1242018-08-10 13:50:46 -0700342 }
Yifan Hong8f0d4542021-01-13 17:10:47 -0800343
344 public:
Yifan Hong024a1242018-08-10 13:50:46 -0700345 void wait(uint64_t seconds) {
346 std::unique_lock<std::mutex> lock(mMutex);
347 mCv.wait_for(lock, std::chrono::seconds(seconds), [this] { return mFinished; });
348
349 if (!mFinished) {
Yifan Hong8f0d4542021-01-13 17:10:47 -0800350 LOG(WARNING) << "Dev GC on " << idl << " HAL timeout";
Yifan Hong024a1242018-08-10 13:50:46 -0700351 } else if (mResult != Result::SUCCESS) {
Yifan Hong8f0d4542021-01-13 17:10:47 -0800352 LOG(WARNING) << "Dev GC on " << idl << " HAL failed with " << toString(mResult);
Yifan Hong024a1242018-08-10 13:50:46 -0700353 } else {
Yifan Hong8f0d4542021-01-13 17:10:47 -0800354 LOG(INFO) << "Dev GC on " << idl << " HAL successful";
Yifan Hong024a1242018-08-10 13:50:46 -0700355 }
356 }
357
358 private:
359 std::mutex mMutex;
360 std::condition_variable mCv;
361 bool mFinished{false};
362 Result mResult{Result::UNKNOWN_ERROR};
363};
364
Yifan Honge1e49452021-01-13 17:27:42 -0800365class AGcCallbackImpl : public ABnGarbageCollectCallback,
366 public GcCallbackImpl<IDL::AIDL, AResult> {
367 ndk::ScopedAStatus onFinish(AResult result) override {
368 onFinishInternal(result);
369 return ndk::ScopedAStatus::ok();
370 }
371};
372
Yifan Hong8f0d4542021-01-13 17:10:47 -0800373class HGcCallbackImpl : public HGarbageCollectCallback, public GcCallbackImpl<IDL::HIDL, HResult> {
374 Return<void> onFinish(HResult result) override {
375 onFinishInternal(result);
376 return Void();
377 }
378};
379
380template <IDL idl, typename Service, typename GcCallbackImpl, typename GetDescription>
381static void runDevGcOnHal(Service service, GcCallbackImpl cb, GetDescription get_description) {
382 LOG(DEBUG) << "Start Dev GC on " << idl << " HAL";
Yifan Hong024a1242018-08-10 13:50:46 -0700383 auto ret = service->garbageCollect(DEVGC_TIMEOUT_SEC, cb);
384 if (!ret.isOk()) {
Yifan Hong8f0d4542021-01-13 17:10:47 -0800385 LOG(WARNING) << "Cannot start Dev GC on " << idl
386 << " HAL: " << std::invoke(get_description, ret);
Yifan Hong024a1242018-08-10 13:50:46 -0700387 return;
388 }
389 cb->wait(DEVGC_TIMEOUT_SEC);
390}
391
392static void runDevGc(void) {
Yifan Hong8f0d4542021-01-13 17:10:47 -0800393 runDevGcFstab();
Yifan Hong024a1242018-08-10 13:50:46 -0700394}
395
Daeho Jeong999fceb2022-01-04 11:37:39 -0800396int RunIdleMaint(bool needGC, const android::sp<android::os::IVoldTaskListener>& listener) {
Jin Qiana370c142017-10-17 15:41:45 -0700397 std::unique_lock<std::mutex> lk(cv_m);
Daeho Jeong999fceb2022-01-04 11:37:39 -0800398 bool gc_aborted = false;
399
Jin Qiana370c142017-10-17 15:41:45 -0700400 if (idle_maint_stat != IdleMaintStats::kStopped) {
401 LOG(DEBUG) << "idle maintenance is already running";
402 if (listener) {
403 android::os::PersistableBundle extras;
404 listener->onFinished(0, extras);
405 }
406 return android::OK;
407 }
408 idle_maint_stat = IdleMaintStats::kRunning;
409 lk.unlock();
410
411 LOG(DEBUG) << "idle maintenance started";
412
Kalesh Singh98062dc2021-02-22 15:10:45 -0500413 auto wl = android::wakelock::WakeLock::tryGet(kWakeLock);
414 if (!wl.has_value()) {
415 return android::UNEXPECTED_NULL;
416 }
Jin Qiana370c142017-10-17 15:41:45 -0700417
Daeho Jeong999fceb2022-01-04 11:37:39 -0800418 if (needGC) {
419 std::list<std::string> paths;
420 addFromFstab(&paths, PathTypes::kBlkDevice, false);
421 addFromVolumeManager(&paths, PathTypes::kBlkDevice);
Jin Qiana370c142017-10-17 15:41:45 -0700422
Daeho Jeong999fceb2022-01-04 11:37:39 -0800423 startGc(paths);
Jin Qiana370c142017-10-17 15:41:45 -0700424
Daeho Jeong999fceb2022-01-04 11:37:39 -0800425 gc_aborted = waitForGc(paths);
Jin Qiana370c142017-10-17 15:41:45 -0700426
Daeho Jeong999fceb2022-01-04 11:37:39 -0800427 stopGc(paths);
428 }
Jin Qiana370c142017-10-17 15:41:45 -0700429
Daeho Jeong7667d642022-05-18 09:03:15 -0700430 if (!gc_aborted) {
431 Trim(nullptr);
432 runDevGc();
433 }
434
Jin Qiana370c142017-10-17 15:41:45 -0700435 lk.lock();
436 idle_maint_stat = IdleMaintStats::kStopped;
437 lk.unlock();
438
439 cv_stop.notify_one();
440
Jin Qiana370c142017-10-17 15:41:45 -0700441 if (listener) {
442 android::os::PersistableBundle extras;
443 listener->onFinished(0, extras);
444 }
445
446 LOG(DEBUG) << "idle maintenance completed";
447
Jin Qiana370c142017-10-17 15:41:45 -0700448 return android::OK;
449}
450
451int AbortIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener) {
Kalesh Singh98062dc2021-02-22 15:10:45 -0500452 auto wl = android::wakelock::WakeLock::tryGet(kWakeLock);
453 if (!wl.has_value()) {
454 return android::UNEXPECTED_NULL;
455 }
Jin Qiana370c142017-10-17 15:41:45 -0700456
457 std::unique_lock<std::mutex> lk(cv_m);
458 if (idle_maint_stat != IdleMaintStats::kStopped) {
459 idle_maint_stat = IdleMaintStats::kAbort;
460 lk.unlock();
461 cv_abort.notify_one();
462 lk.lock();
463 LOG(DEBUG) << "aborting idle maintenance";
Paul Crowley14c8c072018-09-18 13:30:21 -0700464 cv_stop.wait(lk, [] { return idle_maint_stat == IdleMaintStats::kStopped; });
Jin Qiana370c142017-10-17 15:41:45 -0700465 }
466 lk.unlock();
467
468 if (listener) {
469 android::os::PersistableBundle extras;
470 listener->onFinished(0, extras);
471 }
472
Jin Qiana370c142017-10-17 15:41:45 -0700473 LOG(DEBUG) << "idle maintenance stopped";
474
475 return android::OK;
476}
477
Daeho Jeong999fceb2022-01-04 11:37:39 -0800478int getLifeTime(const std::string& path) {
479 std::string result;
480
481 if (!ReadFileToString(path, &result)) {
482 PLOG(WARNING) << "Reading lifetime estimation failed for " << path;
483 return -1;
484 }
485 return std::stoi(result, 0, 16);
486}
487
488int32_t GetStorageLifeTime() {
489 std::string path = getDevSysfsPath();
490 if (path.empty()) {
491 return -1;
492 }
493
494 std::string lifeTimeBasePath = path + "/health_descriptor/life_time_estimation_";
495
496 int32_t lifeTime = getLifeTime(lifeTimeBasePath + "c");
497 if (lifeTime != -1) {
498 return lifeTime;
499 }
500
501 int32_t lifeTimeA = getLifeTime(lifeTimeBasePath + "a");
502 int32_t lifeTimeB = getLifeTime(lifeTimeBasePath + "b");
503 lifeTime = std::max(lifeTimeA, lifeTimeB);
504 if (lifeTime != -1) {
505 return lifeTime == 0 ? -1 : lifeTime * 10;
506 }
507 return -1;
508}
509
510void SetGCUrgentPace(int32_t neededSegments, int32_t minSegmentThreshold, float dirtyReclaimRate,
Daeho Jeong3f8e8552022-06-24 14:50:47 -0700511 float reclaimWeight, int32_t gcPeriod, int32_t minGCSleepTime,
512 int32_t targetDirtyRatio) {
Daeho Jeong999fceb2022-01-04 11:37:39 -0800513 std::list<std::string> paths;
Daeho Jeong3f8e8552022-06-24 14:50:47 -0700514 bool needGC = false;
Daeho Jeong0b5f3972022-03-18 21:30:47 -0700515 int32_t sleepTime;
Daeho Jeong999fceb2022-01-04 11:37:39 -0800516
517 addFromFstab(&paths, PathTypes::kBlkDevice, true);
518 if (paths.empty()) {
519 LOG(WARNING) << "There is no valid blk device path for data partition";
520 return;
521 }
522
523 std::string f2fsSysfsPath = paths.front();
524 std::string freeSegmentsPath = f2fsSysfsPath + "/free_segments";
525 std::string dirtySegmentsPath = f2fsSysfsPath + "/dirty_segments";
526 std::string gcSleepTimePath = f2fsSysfsPath + "/gc_urgent_sleep_time";
527 std::string gcUrgentModePath = f2fsSysfsPath + "/gc_urgent";
Daeho Jeong3ccdeb32022-03-25 10:02:57 -0700528 std::string ovpSegmentsPath = f2fsSysfsPath + "/ovp_segments";
529 std::string reservedBlocksPath = f2fsSysfsPath + "/reserved_blocks";
530 std::string freeSegmentsStr, dirtySegmentsStr, ovpSegmentsStr, reservedBlocksStr;
Daeho Jeong999fceb2022-01-04 11:37:39 -0800531
532 if (!ReadFileToString(freeSegmentsPath, &freeSegmentsStr)) {
533 PLOG(WARNING) << "Reading failed in " << freeSegmentsPath;
534 return;
535 }
536
537 if (!ReadFileToString(dirtySegmentsPath, &dirtySegmentsStr)) {
538 PLOG(WARNING) << "Reading failed in " << dirtySegmentsPath;
539 return;
540 }
541
Daeho Jeong3ccdeb32022-03-25 10:02:57 -0700542 if (!ReadFileToString(ovpSegmentsPath, &ovpSegmentsStr)) {
543 PLOG(WARNING) << "Reading failed in " << ovpSegmentsPath;
544 return;
545 }
546
547 if (!ReadFileToString(reservedBlocksPath, &reservedBlocksStr)) {
548 PLOG(WARNING) << "Reading failed in " << reservedBlocksPath;
549 return;
550 }
551
Daeho Jeong999fceb2022-01-04 11:37:39 -0800552 int32_t freeSegments = std::stoi(freeSegmentsStr);
553 int32_t dirtySegments = std::stoi(dirtySegmentsStr);
Daeho Jeong3ccdeb32022-03-25 10:02:57 -0700554 int32_t reservedBlocks = std::stoi(ovpSegmentsStr) + std::stoi(reservedBlocksStr);
Daeho Jeong999fceb2022-01-04 11:37:39 -0800555
Daeho Jeong3ccdeb32022-03-25 10:02:57 -0700556 freeSegments = freeSegments > reservedBlocks ? freeSegments - reservedBlocks : 0;
Daeho Jeong3f8e8552022-06-24 14:50:47 -0700557 int32_t totalSegments = freeSegments + dirtySegments;
558 int32_t finalTargetSegments = 0;
559
560 if (totalSegments < minSegmentThreshold) {
Daeho Jeong999fceb2022-01-04 11:37:39 -0800561 LOG(INFO) << "The sum of free segments: " << freeSegments
Daeho Jeong3f8e8552022-06-24 14:50:47 -0700562 << ", dirty segments: " << dirtySegments << " is under " << minSegmentThreshold;
Daeho Jeong0b5f3972022-03-18 21:30:47 -0700563 } else {
Daeho Jeong3f8e8552022-06-24 14:50:47 -0700564 int32_t dirtyRatio = dirtySegments * 100 / totalSegments;
565 int32_t neededForTargetRatio =
566 (dirtyRatio > targetDirtyRatio)
567 ? totalSegments * (dirtyRatio - targetDirtyRatio) / 100
568 : 0;
569 neededSegments *= reclaimWeight;
570 neededSegments = (neededSegments > freeSegments) ? neededSegments - freeSegments : 0;
571
572 finalTargetSegments = std::max(neededSegments, neededForTargetRatio);
573 if (finalTargetSegments == 0) {
574 LOG(INFO) << "Enough free segments: " << freeSegments;
Daeho Jeong0b5f3972022-03-18 21:30:47 -0700575 } else {
Daeho Jeong3f8e8552022-06-24 14:50:47 -0700576 finalTargetSegments =
577 std::min(finalTargetSegments, (int32_t)(dirtySegments * dirtyReclaimRate));
578 if (finalTargetSegments == 0) {
579 LOG(INFO) << "Low dirty segments: " << dirtySegments;
580 } else if (neededSegments >= neededForTargetRatio) {
581 LOG(INFO) << "Trigger GC, because of needed segments exceeding free segments";
582 needGC = true;
583 } else {
584 LOG(INFO) << "Trigger GC for target dirty ratio diff of: "
585 << dirtyRatio - targetDirtyRatio;
586 needGC = true;
Daeho Jeong0b5f3972022-03-18 21:30:47 -0700587 }
588 }
Daeho Jeong999fceb2022-01-04 11:37:39 -0800589 }
590
591 if (!needGC) {
592 if (!WriteStringToFile(std::to_string(GC_NORMAL_MODE), gcUrgentModePath)) {
593 PLOG(WARNING) << "Writing failed in " << gcUrgentModePath;
594 }
595 return;
596 }
597
Daeho Jeong3f8e8552022-06-24 14:50:47 -0700598 sleepTime = gcPeriod * ONE_MINUTE_IN_MS / finalTargetSegments;
599 if (sleepTime < minGCSleepTime) {
600 sleepTime = minGCSleepTime;
601 }
602
Daeho Jeong999fceb2022-01-04 11:37:39 -0800603 if (!WriteStringToFile(std::to_string(sleepTime), gcSleepTimePath)) {
604 PLOG(WARNING) << "Writing failed in " << gcSleepTimePath;
605 return;
606 }
607
Daeho Jeong5e879422022-03-15 21:42:55 -0700608 if (!WriteStringToFile(std::to_string(GC_URGENT_MID_MODE), gcUrgentModePath)) {
Daeho Jeong999fceb2022-01-04 11:37:39 -0800609 PLOG(WARNING) << "Writing failed in " << gcUrgentModePath;
610 return;
611 }
612
613 LOG(INFO) << "Successfully set gc urgent mode: "
Daeho Jeong3f8e8552022-06-24 14:50:47 -0700614 << "free segments: " << freeSegments << ", reclaim target: " << finalTargetSegments
615 << ", sleep time: " << sleepTime;
Daeho Jeong999fceb2022-01-04 11:37:39 -0800616}
617
618static int32_t getLifeTimeWrite() {
619 std::list<std::string> paths;
620 addFromFstab(&paths, PathTypes::kBlkDevice, true);
621 if (paths.empty()) {
622 LOG(WARNING) << "There is no valid blk device path for data partition";
623 return -1;
624 }
625
626 std::string writeKbytesPath = paths.front() + "/lifetime_write_kbytes";
627 std::string writeKbytesStr;
628 if (!ReadFileToString(writeKbytesPath, &writeKbytesStr)) {
629 PLOG(WARNING) << "Reading failed in " << writeKbytesPath;
630 return -1;
631 }
632
633 long long writeBytes = std::stoll(writeKbytesStr);
634 return writeBytes / KBYTES_IN_SEGMENT;
635}
636
637void RefreshLatestWrite() {
638 int32_t segmentWrite = getLifeTimeWrite();
639 if (segmentWrite != -1) {
640 previousSegmentWrite = segmentWrite;
641 }
642}
643
644int32_t GetWriteAmount() {
645 int32_t currentSegmentWrite = getLifeTimeWrite();
646 if (currentSegmentWrite == -1) {
647 return -1;
648 }
649
650 int32_t writeAmount = currentSegmentWrite - previousSegmentWrite;
651 previousSegmentWrite = currentSegmentWrite;
652 return writeAmount;
653}
654
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700655} // namespace vold
656} // namespace android