1 /*
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 
17 #include "IdleMaint.h"
18 #include "FileDeviceUtils.h"
19 #include "Utils.h"
20 #include "VoldUtil.h"
21 #include "VolumeManager.h"
22 #include "model/PrivateVolume.h"
23 
24 #include <thread>
25 #include <utility>
26 
27 #include <aidl/android/hardware/health/storage/BnGarbageCollectCallback.h>
28 #include <aidl/android/hardware/health/storage/IStorage.h>
29 #include <android-base/chrono_utils.h>
30 #include <android-base/file.h>
31 #include <android-base/logging.h>
32 #include <android-base/stringprintf.h>
33 #include <android-base/strings.h>
34 #include <android/binder_manager.h>
35 #include <android/hardware/health/storage/1.0/IStorage.h>
36 #include <fs_mgr.h>
37 #include <private/android_filesystem_config.h>
38 #include <wakelock/wakelock.h>
39 
40 #include <dirent.h>
41 #include <fcntl.h>
42 #include <sys/mount.h>
43 #include <sys/stat.h>
44 #include <sys/types.h>
45 #include <sys/wait.h>
46 
47 using android::base::Basename;
48 using android::base::ReadFileToString;
49 using android::base::Realpath;
50 using android::base::StringPrintf;
51 using android::base::Timer;
52 using android::base::WriteStringToFile;
53 using android::hardware::Return;
54 using android::hardware::Void;
55 using AStorage = aidl::android::hardware::health::storage::IStorage;
56 using ABnGarbageCollectCallback =
57         aidl::android::hardware::health::storage::BnGarbageCollectCallback;
58 using AResult = aidl::android::hardware::health::storage::Result;
59 using HStorage = android::hardware::health::storage::V1_0::IStorage;
60 using HGarbageCollectCallback = android::hardware::health::storage::V1_0::IGarbageCollectCallback;
61 using HResult = android::hardware::health::storage::V1_0::Result;
62 using std::string_literals::operator""s;
63 
64 namespace android {
65 namespace vold {
66 
67 enum class PathTypes {
68     kMountPoint = 1,
69     kBlkDevice,
70 };
71 
72 enum class IdleMaintStats {
73     kStopped = 1,
74     kRunning,
75     kAbort,
76 };
77 
78 static const char* kWakeLock = "IdleMaint";
79 static const int DIRTY_SEGMENTS_THRESHOLD = 100;
80 /*
81  * Timing policy:
82  *  1. F2FS_GC = 7 mins
83  *  2. Trim = 1 min
84  *  3. Dev GC = 2 mins
85  */
86 static const int GC_TIMEOUT_SEC = 420;
87 static const int DEVGC_TIMEOUT_SEC = 120;
88 static const int KBYTES_IN_SEGMENT = 2048;
89 static const int ONE_MINUTE_IN_MS = 60000;
90 static const int GC_NORMAL_MODE = 0;
91 static const int GC_URGENT_MID_MODE = 3;
92 
93 static int32_t previousSegmentWrite = 0;
94 
95 static IdleMaintStats idle_maint_stat(IdleMaintStats::kStopped);
96 static std::condition_variable cv_abort, cv_stop;
97 static std::mutex cv_m;
98 
addFromVolumeManager(std::list<std::string> * paths,PathTypes path_type)99 static void addFromVolumeManager(std::list<std::string>* paths, PathTypes path_type) {
100     VolumeManager* vm = VolumeManager::Instance();
101     std::list<std::string> privateIds;
102     vm->listVolumes(VolumeBase::Type::kPrivate, privateIds);
103     for (const auto& id : privateIds) {
104         PrivateVolume* vol = static_cast<PrivateVolume*>(vm->findVolume(id).get());
105         if (vol != nullptr && vol->getState() == VolumeBase::State::kMounted) {
106             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();
111                 if (fs_type == "f2fs" && (Realpath(vol->getRawDmDevPath(), &gc_path) ||
112                                           Realpath(vol->getRawDevPath(), &gc_path))) {
113                     paths->push_back(std::string("/sys/fs/") + fs_type + "/" + Basename(gc_path));
114                 }
115             }
116         }
117     }
118 }
119 
addFromFstab(std::list<std::string> * paths,PathTypes path_type,bool only_data_part)120 static void addFromFstab(std::list<std::string>* paths, PathTypes path_type, bool only_data_part) {
121     std::string previous_mount_point;
122     for (const auto& entry : fstab_default) {
123         // Skip raw partitions and swap space.
124         if (entry.fs_type == "emmc" || entry.fs_type == "mtd" || entry.fs_type == "swap") {
125             continue;
126         }
127         // 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] != '/') {
133             continue;
134         }
135         if (entry.fs_mgr_flags.vold_managed) {
136             continue;  // Should we trim fat32 filesystems?
137         }
138         if (entry.fs_mgr_flags.no_trim) {
139             continue;
140         }
141 
142         if (only_data_part && entry.mount_point != "/data") {
143             continue;
144         }
145 
146         // 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) {
149             continue;
150         }
151 
152         if (path_type == PathTypes::kMountPoint) {
153             paths->push_back(entry.mount_point);
154         } else if (path_type == PathTypes::kBlkDevice) {
155             std::string path;
156             if (entry.fs_type == "f2fs" &&
157                 Realpath(android::vold::BlockDeviceForPath(entry.mount_point + "/"), &path)) {
158                 paths->push_back("/sys/fs/" + entry.fs_type + "/" + Basename(path));
159             }
160         }
161 
162         previous_mount_point = entry.mount_point;
163     }
164 }
165 
Trim(const android::sp<android::os::IVoldTaskListener> & listener)166 void Trim(const android::sp<android::os::IVoldTaskListener>& listener) {
167     auto wl = android::wakelock::WakeLock::tryGet(kWakeLock);
168     if (!wl.has_value()) {
169         return;
170     }
171 
172     // Collect both fstab and vold volumes
173     std::list<std::string> paths;
174     addFromFstab(&paths, PathTypes::kMountPoint, false);
175     addFromVolumeManager(&paths, PathTypes::kMountPoint);
176 
177     for (const auto& path : paths) {
178         LOG(DEBUG) << "Starting trim of " << path;
179 
180         android::os::PersistableBundle extras;
181         extras.putString(String16("path"), String16(path.c_str()));
182 
183         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;
186             if (listener) {
187                 listener->onStatus(-1, extras);
188             }
189             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);
197         if (ioctl(fd, FITRIM, &range)) {
198             PLOG(WARNING) << "Trim failed on " << path;
199             if (listener) {
200                 listener->onStatus(-1, extras);
201             }
202         } else {
203             nsecs_t time = systemTime(SYSTEM_TIME_BOOTTIME) - start;
204             LOG(INFO) << "Trimmed " << range.len << " bytes on " << path << " in "
205                       << nanoseconds_to_milliseconds(time) << "ms";
206             extras.putLong(String16("bytes"), range.len);
207             extras.putLong(String16("time"), time);
208             if (listener) {
209                 listener->onStatus(0, extras);
210             }
211         }
212         close(fd);
213     }
214 
215     if (listener) {
216         android::os::PersistableBundle extras;
217         listener->onFinished(0, extras);
218     }
219 
220 }
221 
waitForGc(const std::list<std::string> & paths)222 static 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();
249         aborted =
250             cv_abort.wait_for(lk, 10s, [] { return idle_maint_stat == IdleMaintStats::kAbort; });
251         lk.unlock();
252     }
253 
254     return aborted;
255 }
256 
startGc(const std::list<std::string> & paths)257 static 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 
stopGc(const std::list<std::string> & paths)267 static 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 
getDevSysfsPath()277 static std::string getDevSysfsPath() {
278     for (const auto& entry : fstab_default) {
279         if (!entry.sysfs_path.empty()) {
280             return entry.sysfs_path;
281         }
282     }
283     LOG(WARNING) << "Cannot find dev sysfs path";
284     return "";
285 }
286 
runDevGcFstab(void)287 static void runDevGcFstab(void) {
288     std::string path = getDevSysfsPath();
289     if (path.empty()) {
290         return;
291     }
292 
293     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         }
303         require = android::base::Trim(require);
304         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 
328 enum class IDL { HIDL, AIDL };
operator <<(std::ostream & os,IDL idl)329 std::ostream& operator<<(std::ostream& os, IDL idl) {
330     return os << (idl == IDL::HIDL ? "HIDL" : "AIDL");
331 }
332 
333 template <IDL idl, typename Result>
334 class GcCallbackImpl {
335   protected:
onFinishInternal(Result result)336     void onFinishInternal(Result result) {
337         std::unique_lock<std::mutex> lock(mMutex);
338         mFinished = true;
339         mResult = result;
340         lock.unlock();
341         mCv.notify_all();
342     }
343 
344   public:
wait(uint64_t seconds)345     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) {
350             LOG(WARNING) << "Dev GC on " << idl << " HAL timeout";
351         } else if (mResult != Result::SUCCESS) {
352             LOG(WARNING) << "Dev GC on " << idl << " HAL failed with " << toString(mResult);
353         } else {
354             LOG(INFO) << "Dev GC on " << idl << " HAL successful";
355         }
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 
365 class AGcCallbackImpl : public ABnGarbageCollectCallback,
366                         public GcCallbackImpl<IDL::AIDL, AResult> {
onFinish(AResult result)367     ndk::ScopedAStatus onFinish(AResult result) override {
368         onFinishInternal(result);
369         return ndk::ScopedAStatus::ok();
370     }
371 };
372 
373 class HGcCallbackImpl : public HGarbageCollectCallback, public GcCallbackImpl<IDL::HIDL, HResult> {
onFinish(HResult result)374     Return<void> onFinish(HResult result) override {
375         onFinishInternal(result);
376         return Void();
377     }
378 };
379 
380 template <IDL idl, typename Service, typename GcCallbackImpl, typename GetDescription>
runDevGcOnHal(Service service,GcCallbackImpl cb,GetDescription get_description)381 static void runDevGcOnHal(Service service, GcCallbackImpl cb, GetDescription get_description) {
382     LOG(DEBUG) << "Start Dev GC on " << idl << " HAL";
383     auto ret = service->garbageCollect(DEVGC_TIMEOUT_SEC, cb);
384     if (!ret.isOk()) {
385         LOG(WARNING) << "Cannot start Dev GC on " << idl
386                      << " HAL: " << std::invoke(get_description, ret);
387         return;
388     }
389     cb->wait(DEVGC_TIMEOUT_SEC);
390 }
391 
runDevGc(void)392 static void runDevGc(void) {
393     runDevGcFstab();
394 }
395 
RunIdleMaint(bool needGC,const android::sp<android::os::IVoldTaskListener> & listener)396 int RunIdleMaint(bool needGC, const android::sp<android::os::IVoldTaskListener>& listener) {
397     std::unique_lock<std::mutex> lk(cv_m);
398     bool gc_aborted = false;
399 
400     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 
413     auto wl = android::wakelock::WakeLock::tryGet(kWakeLock);
414     if (!wl.has_value()) {
415         return android::UNEXPECTED_NULL;
416     }
417 
418     if (needGC) {
419         std::list<std::string> paths;
420         addFromFstab(&paths, PathTypes::kBlkDevice, false);
421         addFromVolumeManager(&paths, PathTypes::kBlkDevice);
422 
423         startGc(paths);
424 
425         gc_aborted = waitForGc(paths);
426 
427         stopGc(paths);
428     }
429 
430     if (!gc_aborted) {
431         Trim(nullptr);
432         runDevGc();
433     }
434 
435     lk.lock();
436     idle_maint_stat = IdleMaintStats::kStopped;
437     lk.unlock();
438 
439     cv_stop.notify_all();
440 
441     if (listener) {
442         android::os::PersistableBundle extras;
443         listener->onFinished(0, extras);
444     }
445 
446     LOG(DEBUG) << "idle maintenance completed";
447 
448     return android::OK;
449 }
450 
AbortIdleMaint(const android::sp<android::os::IVoldTaskListener> & listener)451 int AbortIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener) {
452     auto wl = android::wakelock::WakeLock::tryGet(kWakeLock);
453     if (!wl.has_value()) {
454         return android::UNEXPECTED_NULL;
455     }
456 
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";
464         cv_stop.wait(lk, [] { return idle_maint_stat == IdleMaintStats::kStopped; });
465     }
466     lk.unlock();
467 
468     if (listener) {
469         android::os::PersistableBundle extras;
470         listener->onFinished(0, extras);
471     }
472 
473     LOG(DEBUG) << "idle maintenance stopped";
474 
475     return android::OK;
476 }
477 
getLifeTime(const std::string & path)478 int 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 
GetStorageLifeTime()488 int32_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 
GetStorageRemainingLifetime()510 int32_t GetStorageRemainingLifetime() {
511     std::string path = getDevSysfsPath();
512     if (path.empty()) {
513         return -1;
514     }
515 
516     std::string lifeTimeBasePath = path + "/health_descriptor/life_time_estimation_";
517 
518     int32_t lifeTime = getLifeTime(lifeTimeBasePath + "c");
519     if (lifeTime == -1) {
520         int32_t lifeTimeA = getLifeTime(lifeTimeBasePath + "a");
521         int32_t lifeTimeB = getLifeTime(lifeTimeBasePath + "b");
522         lifeTime = std::max(lifeTimeA, lifeTimeB);
523         if (lifeTime <= 0) {
524             return -1;
525         }
526 
527         // 1 = 0-10% used, 10 = 90-100% used. Subtract 1 so that a brand new
528         // device looks 0% used.
529         lifeTime = (lifeTime - 1) * 10;
530     }
531     return 100 - std::clamp(lifeTime, 0, 100);
532 }
533 
SetGCUrgentPace(int32_t neededSegments,int32_t minSegmentThreshold,float dirtyReclaimRate,float reclaimWeight,int32_t gcPeriod,int32_t minGCSleepTime,int32_t targetDirtyRatio)534 void SetGCUrgentPace(int32_t neededSegments, int32_t minSegmentThreshold, float dirtyReclaimRate,
535                      float reclaimWeight, int32_t gcPeriod, int32_t minGCSleepTime,
536                      int32_t targetDirtyRatio) {
537     std::list<std::string> paths;
538     bool needGC = false;
539     int32_t sleepTime;
540 
541     addFromFstab(&paths, PathTypes::kBlkDevice, true);
542     if (paths.empty()) {
543         LOG(WARNING) << "There is no valid blk device path for data partition";
544         return;
545     }
546 
547     std::string f2fsSysfsPath = paths.front();
548     std::string freeSegmentsPath = f2fsSysfsPath + "/free_segments";
549     std::string dirtySegmentsPath = f2fsSysfsPath + "/dirty_segments";
550     std::string gcSleepTimePath = f2fsSysfsPath + "/gc_urgent_sleep_time";
551     std::string gcUrgentModePath = f2fsSysfsPath + "/gc_urgent";
552     std::string ovpSegmentsPath = f2fsSysfsPath + "/ovp_segments";
553     std::string reservedBlocksPath = f2fsSysfsPath + "/reserved_blocks";
554     std::string freeSegmentsStr, dirtySegmentsStr, ovpSegmentsStr, reservedBlocksStr;
555 
556     if (!ReadFileToString(freeSegmentsPath, &freeSegmentsStr)) {
557         PLOG(WARNING) << "Reading failed in " << freeSegmentsPath;
558         return;
559     }
560 
561     if (!ReadFileToString(dirtySegmentsPath, &dirtySegmentsStr)) {
562         PLOG(WARNING) << "Reading failed in " << dirtySegmentsPath;
563         return;
564     }
565 
566     if (!ReadFileToString(ovpSegmentsPath, &ovpSegmentsStr)) {
567             PLOG(WARNING) << "Reading failed in " << ovpSegmentsPath;
568             return;
569         }
570 
571     if (!ReadFileToString(reservedBlocksPath, &reservedBlocksStr)) {
572             PLOG(WARNING) << "Reading failed in " << reservedBlocksPath;
573             return;
574         }
575 
576     int32_t freeSegments = std::stoi(freeSegmentsStr);
577     int32_t dirtySegments = std::stoi(dirtySegmentsStr);
578     int32_t reservedSegments = std::stoi(ovpSegmentsStr) + std::stoi(reservedBlocksStr) / 512;
579 
580     freeSegments = freeSegments > reservedSegments ? freeSegments - reservedSegments : 0;
581     int32_t totalSegments = freeSegments + dirtySegments;
582     int32_t finalTargetSegments = 0;
583 
584     if (totalSegments < minSegmentThreshold) {
585         LOG(INFO) << "The sum of free segments: " << freeSegments
586                   << ", dirty segments: " << dirtySegments << " is under " << minSegmentThreshold;
587     } else {
588         int32_t dirtyRatio = dirtySegments * 100 / totalSegments;
589         int32_t neededForTargetRatio =
590                 (dirtyRatio > targetDirtyRatio)
591                         ? totalSegments * (dirtyRatio - targetDirtyRatio) / 100
592                         : 0;
593         neededSegments *= reclaimWeight;
594         neededSegments = (neededSegments > freeSegments) ? neededSegments - freeSegments : 0;
595 
596         finalTargetSegments = std::max(neededSegments, neededForTargetRatio);
597         if (finalTargetSegments == 0) {
598             LOG(INFO) << "Enough free segments: " << freeSegments;
599         } else {
600             finalTargetSegments =
601                     std::min(finalTargetSegments, (int32_t)(dirtySegments * dirtyReclaimRate));
602             if (finalTargetSegments == 0) {
603                 LOG(INFO) << "Low dirty segments: " << dirtySegments;
604             } else if (neededSegments >= neededForTargetRatio) {
605                 LOG(INFO) << "Trigger GC, because of needed segments exceeding free segments";
606                 needGC = true;
607             } else {
608                 LOG(INFO) << "Trigger GC for target dirty ratio diff of: "
609                           << dirtyRatio - targetDirtyRatio;
610                 needGC = true;
611             }
612         }
613     }
614 
615     if (!needGC) {
616         if (!WriteStringToFile(std::to_string(GC_NORMAL_MODE), gcUrgentModePath)) {
617             PLOG(WARNING) << "Writing failed in " << gcUrgentModePath;
618         }
619         return;
620     }
621 
622     sleepTime = gcPeriod * ONE_MINUTE_IN_MS / finalTargetSegments;
623     if (sleepTime < minGCSleepTime) {
624         sleepTime = minGCSleepTime;
625     }
626 
627     if (!WriteStringToFile(std::to_string(sleepTime), gcSleepTimePath)) {
628         PLOG(WARNING) << "Writing failed in " << gcSleepTimePath;
629         return;
630     }
631 
632     if (!WriteStringToFile(std::to_string(GC_URGENT_MID_MODE), gcUrgentModePath)) {
633         PLOG(WARNING) << "Writing failed in " << gcUrgentModePath;
634         return;
635     }
636 
637     LOG(INFO) << "Successfully set gc urgent mode: "
638               << "free segments: " << freeSegments << ", reclaim target: " << finalTargetSegments
639               << ", sleep time: " << sleepTime;
640 }
641 
getLifeTimeWrite()642 static int32_t getLifeTimeWrite() {
643     std::list<std::string> paths;
644     addFromFstab(&paths, PathTypes::kBlkDevice, true);
645     if (paths.empty()) {
646         LOG(WARNING) << "There is no valid blk device path for data partition";
647         return -1;
648     }
649 
650     std::string writeKbytesPath = paths.front() + "/lifetime_write_kbytes";
651     std::string writeKbytesStr;
652     if (!ReadFileToString(writeKbytesPath, &writeKbytesStr)) {
653         PLOG(WARNING) << "Reading failed in " << writeKbytesPath;
654         return -1;
655     }
656 
657     unsigned long long writeBytes = std::strtoull(writeKbytesStr.c_str(), NULL, 0);
658     /* Careful: values > LLONG_MAX can appear in the file due to a kernel bug. */
659     if (writeBytes / KBYTES_IN_SEGMENT > INT32_MAX) {
660         LOG(WARNING) << "Bad lifetime_write_kbytes: " << writeKbytesStr;
661         return -1;
662     }
663     return writeBytes / KBYTES_IN_SEGMENT;
664 }
665 
RefreshLatestWrite()666 void RefreshLatestWrite() {
667     int32_t segmentWrite = getLifeTimeWrite();
668     if (segmentWrite != -1) {
669         previousSegmentWrite = segmentWrite;
670     }
671 }
672 
GetWriteAmount()673 int32_t GetWriteAmount() {
674     int32_t currentSegmentWrite = getLifeTimeWrite();
675     if (currentSegmentWrite == -1) {
676         return -1;
677     }
678 
679     int32_t writeAmount = currentSegmentWrite - previousSegmentWrite;
680     previousSegmentWrite = currentSegmentWrite;
681     return writeAmount;
682 }
683 
684 }  // namespace vold
685 }  // namespace android
686