blob: b4b7746e3c3b9567e308485aa49abe4a1d37822f [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"
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070018#include "Utils.h"
19#include "VolumeManager.h"
Jin Qiana370c142017-10-17 15:41:45 -070020#include "model/PrivateVolume.h"
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070021
Jin Qiana370c142017-10-17 15:41:45 -070022#include <thread>
23
24#include <android-base/chrono_utils.h>
25#include <android-base/file.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080026#include <android-base/logging.h>
Yifan Hong024a1242018-08-10 13:50:46 -070027#include <android-base/stringprintf.h>
28#include <android-base/strings.h>
29#include <android/hardware/health/filesystem/1.0/IFileSystem.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070030#include <fs_mgr.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070031#include <hardware_legacy/power.h>
Yifan Hong024a1242018-08-10 13:50:46 -070032#include <private/android_filesystem_config.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070033
34#include <dirent.h>
35#include <sys/mount.h>
36#include <sys/stat.h>
37#include <sys/types.h>
38#include <sys/wait.h>
39#include <fcntl.h>
40
Jin Qiana370c142017-10-17 15:41:45 -070041using android::base::Basename;
42using android::base::ReadFileToString;
43using android::base::Realpath;
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070044using android::base::StringPrintf;
Jin Qiana370c142017-10-17 15:41:45 -070045using android::base::Timer;
46using android::base::WriteStringToFile;
Yifan Hong024a1242018-08-10 13:50:46 -070047using android::hardware::Return;
48using android::hardware::Void;
49using android::hardware::health::filesystem::V1_0::IFileSystem;
50using android::hardware::health::filesystem::V1_0::IGarbageCollectCallback;
51using android::hardware::health::filesystem::V1_0::Result;
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070052
53namespace android {
54namespace vold {
55
Jin Qiana370c142017-10-17 15:41:45 -070056enum class PathTypes {
57 kMountPoint = 1,
58 kBlkDevice,
59};
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070060
Jin Qiana370c142017-10-17 15:41:45 -070061enum class IdleMaintStats {
62 kStopped = 1,
63 kRunning,
64 kAbort,
65};
66
67static const char* kWakeLock = "IdleMaint";
68static const int DIRTY_SEGMENTS_THRESHOLD = 100;
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -080069/*
70 * Timing policy:
71 * 1. F2FS_GC = 7 mins
72 * 2. Trim = 1 min
73 * 3. Dev GC = 2 mins
74 */
75static const int GC_TIMEOUT_SEC = 420;
76static const int DEVGC_TIMEOUT_SEC = 120;
Jin Qiana370c142017-10-17 15:41:45 -070077
78static IdleMaintStats idle_maint_stat(IdleMaintStats::kStopped);
79static std::condition_variable cv_abort, cv_stop;
80static std::mutex cv_m;
81
82static void addFromVolumeManager(std::list<std::string>* paths,
83 PathTypes path_type) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070084 VolumeManager* vm = VolumeManager::Instance();
85 std::list<std::string> privateIds;
86 vm->listVolumes(VolumeBase::Type::kPrivate, privateIds);
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -070087 for (const auto& id : privateIds) {
Jin Qiana370c142017-10-17 15:41:45 -070088 PrivateVolume* vol = static_cast<PrivateVolume*>(vm->findVolume(id).get());
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070089 if (vol != nullptr && vol->getState() == VolumeBase::State::kMounted) {
Jin Qiana370c142017-10-17 15:41:45 -070090 if (path_type == PathTypes::kMountPoint) {
91 paths->push_back(vol->getPath());
92 } else if (path_type == PathTypes::kBlkDevice) {
93 std::string gc_path;
94 const std::string& fs_type = vol->getFsType();
95 if (fs_type == "f2fs" &&
96 Realpath(vol->getRawDevPath(), &gc_path)) {
97 paths->push_back(std::string("/sys/fs/") + fs_type +
98 "/" + Basename(gc_path));
99 }
100 }
101
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700102 }
103 }
104}
105
Jin Qiana370c142017-10-17 15:41:45 -0700106static void addFromFstab(std::list<std::string>* paths, PathTypes path_type) {
Bowgo Tsaie8fb6c32017-03-09 23:11:33 +0800107 std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
108 fs_mgr_free_fstab);
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700109 struct fstab_rec *prev_rec = NULL;
110
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700111 for (int i = 0; i < fstab->num_entries; i++) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600112 auto fs_type = std::string(fstab->recs[i].fs_type);
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700113 /* Skip raw partitions */
Jeff Sharkey3472e522017-10-06 18:02:53 -0600114 if (fs_type == "emmc" || fs_type == "mtd") {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700115 continue;
116 }
117 /* Skip read-only filesystems */
118 if (fstab->recs[i].flags & MS_RDONLY) {
119 continue;
120 }
121 if (fs_mgr_is_voldmanaged(&fstab->recs[i])) {
122 continue; /* Should we trim fat32 filesystems? */
123 }
124 if (fs_mgr_is_notrim(&fstab->recs[i])) {
125 continue;
126 }
127
128 /* Skip the multi-type partitions, which are required to be following each other.
129 * See fs_mgr.c's mount_with_alternatives().
130 */
131 if (prev_rec && !strcmp(prev_rec->mount_point, fstab->recs[i].mount_point)) {
132 continue;
133 }
134
Jin Qiana370c142017-10-17 15:41:45 -0700135 if (path_type == PathTypes::kMountPoint) {
136 paths->push_back(fstab->recs[i].mount_point);
137 } else if (path_type == PathTypes::kBlkDevice) {
138 std::string gc_path;
139 if (std::string(fstab->recs[i].fs_type) == "f2fs" &&
140 Realpath(fstab->recs[i].blk_device, &gc_path)) {
141 paths->push_back(std::string("/sys/fs/") + fstab->recs[i].fs_type +
142 "/" + Basename(gc_path));
143 }
144 }
145
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700146 prev_rec = &fstab->recs[i];
147 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700148}
149
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600150void Trim(const android::sp<android::os::IVoldTaskListener>& listener) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700151 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
152
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600153 // Collect both fstab and vold volumes
154 std::list<std::string> paths;
Jin Qiana370c142017-10-17 15:41:45 -0700155 addFromFstab(&paths, PathTypes::kMountPoint);
156 addFromVolumeManager(&paths, PathTypes::kMountPoint);
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600157
158 for (const auto& path : paths) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700159 LOG(DEBUG) << "Starting trim of " << path;
160
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600161 android::os::PersistableBundle extras;
162 extras.putString(String16("path"), String16(path.c_str()));
163
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700164 int fd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
165 if (fd < 0) {
166 PLOG(WARNING) << "Failed to open " << path;
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600167 if (listener) {
168 listener->onStatus(-1, extras);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600169 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700170 continue;
171 }
172
173 struct fstrim_range range;
174 memset(&range, 0, sizeof(range));
175 range.len = ULLONG_MAX;
176
177 nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME);
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600178 if (ioctl(fd, FITRIM, &range)) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700179 PLOG(WARNING) << "Trim failed on " << path;
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600180 if (listener) {
181 listener->onStatus(-1, extras);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600182 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700183 } else {
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600184 nsecs_t time = systemTime(SYSTEM_TIME_BOOTTIME) - start;
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700185 LOG(INFO) << "Trimmed " << range.len << " bytes on " << path
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600186 << " in " << nanoseconds_to_milliseconds(time) << "ms";
187 extras.putLong(String16("bytes"), range.len);
188 extras.putLong(String16("time"), time);
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600189 if (listener) {
190 listener->onStatus(0, extras);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600191 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700192 }
193 close(fd);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600194 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700195
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600196 if (listener) {
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600197 android::os::PersistableBundle extras;
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600198 listener->onFinished(0, extras);
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700199 }
200
201 release_wake_lock(kWakeLock);
202}
203
Jin Qiana370c142017-10-17 15:41:45 -0700204static bool waitForGc(const std::list<std::string>& paths) {
205 std::unique_lock<std::mutex> lk(cv_m, std::defer_lock);
206 bool stop = false, aborted = false;
207 Timer timer;
208
209 while (!stop && !aborted) {
210 stop = true;
211 for (const auto& path : paths) {
212 std::string dirty_segments;
213 if (!ReadFileToString(path + "/dirty_segments", &dirty_segments)) {
214 PLOG(WARNING) << "Reading dirty_segments failed in " << path;
215 continue;
216 }
217 if (std::stoi(dirty_segments) > DIRTY_SEGMENTS_THRESHOLD) {
218 stop = false;
219 break;
220 }
221 }
222
223 if (stop) break;
224
225 if (timer.duration() >= std::chrono::seconds(GC_TIMEOUT_SEC)) {
226 LOG(WARNING) << "GC timeout";
227 break;
228 }
229
230 lk.lock();
231 aborted = cv_abort.wait_for(lk, 10s, []{
232 return idle_maint_stat == IdleMaintStats::kAbort;});
233 lk.unlock();
234 }
235
236 return aborted;
237}
238
239static int startGc(const std::list<std::string>& paths) {
240 for (const auto& path : paths) {
241 LOG(DEBUG) << "Start GC on " << path;
Jaegeuk Kima6aae2f2018-02-17 06:02:30 -0800242 if (!WriteStringToFile("1", path + "/discard_granularity")) {
243 PLOG(WARNING) << "Set discard gralunarity failed on" << path;
244 }
Jin Qiana370c142017-10-17 15:41:45 -0700245 if (!WriteStringToFile("1", path + "/gc_urgent")) {
246 PLOG(WARNING) << "Start GC failed on " << path;
247 }
248 }
249 return android::OK;
250}
251
252static int stopGc(const std::list<std::string>& paths) {
253 for (const auto& path : paths) {
254 LOG(DEBUG) << "Stop GC on " << path;
255 if (!WriteStringToFile("0", path + "/gc_urgent")) {
256 PLOG(WARNING) << "Stop GC failed on " << path;
257 }
Jaegeuk Kima6aae2f2018-02-17 06:02:30 -0800258 if (!WriteStringToFile("16", path + "/discard_granularity")) {
259 PLOG(WARNING) << "Set discard gralunarity failed on" << path;
260 }
Jin Qiana370c142017-10-17 15:41:45 -0700261 }
262 return android::OK;
263}
264
Yifan Hong024a1242018-08-10 13:50:46 -0700265static void runDevGcFstab(void) {
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -0800266 std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
267 fs_mgr_free_fstab);
268 struct fstab_rec *rec = NULL;
269
270 for (int i = 0; i < fstab->num_entries; i++) {
271 if (fs_mgr_has_sysfs_path(&fstab->recs[i])) {
272 rec = &fstab->recs[i];
273 break;
274 }
275 }
276 if (!rec) {
277 return;
278 }
279
280 std::string path;
281 path.append(rec->sysfs_path);
282 path = path + "/manual_gc";
283 Timer timer;
284
285 LOG(DEBUG) << "Start Dev GC on " << path;
286 while (1) {
287 std::string require;
288 if (!ReadFileToString(path, &require)) {
289 PLOG(WARNING) << "Reading manual_gc failed in " << path;
290 break;
291 }
Yifan Hong024a1242018-08-10 13:50:46 -0700292 require = android::base::Trim(require);
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -0800293 if (require == "" || require == "off" || require == "disabled") {
294 LOG(DEBUG) << "No more to do Dev GC";
295 break;
296 }
297
298 LOG(DEBUG) << "Trigger Dev GC on " << path;
299 if (!WriteStringToFile("1", path)) {
300 PLOG(WARNING) << "Start Dev GC failed on " << path;
301 break;
302 }
303
304 if (timer.duration() >= std::chrono::seconds(DEVGC_TIMEOUT_SEC)) {
305 LOG(WARNING) << "Dev GC timeout";
306 break;
307 }
308 sleep(2);
309 }
310 LOG(DEBUG) << "Stop Dev GC on " << path;
311 if (!WriteStringToFile("0", path)) {
312 PLOG(WARNING) << "Stop Dev GC failed on " << path;
313 }
314 return;
315}
316
Yifan Hong024a1242018-08-10 13:50:46 -0700317class GcCallback : public IGarbageCollectCallback {
318 public:
319 Return<void> onFinish(Result result) override {
320 std::unique_lock<std::mutex> lock(mMutex);
321 mFinished = true;
322 mResult = result;
323 lock.unlock();
324 mCv.notify_all();
325 return Void();
326 }
327 void wait(uint64_t seconds) {
328 std::unique_lock<std::mutex> lock(mMutex);
329 mCv.wait_for(lock, std::chrono::seconds(seconds), [this] { return mFinished; });
330
331 if (!mFinished) {
332 LOG(WARNING) << "Dev GC on HAL timeout";
333 } else if (mResult != Result::SUCCESS) {
334 LOG(WARNING) << "Dev GC on HAL failed with " << toString(mResult);
335 } else {
336 LOG(INFO) << "Dev GC on HAL successful";
337 }
338 }
339
340 private:
341 std::mutex mMutex;
342 std::condition_variable mCv;
343 bool mFinished{false};
344 Result mResult{Result::UNKNOWN_ERROR};
345};
346
347static void runDevGcOnHal(sp<IFileSystem> service) {
348 LOG(DEBUG) << "Start Dev GC on HAL";
349 sp<GcCallback> cb = new GcCallback();
350 auto ret = service->garbageCollect(DEVGC_TIMEOUT_SEC, cb);
351 if (!ret.isOk()) {
352 LOG(WARNING) << "Cannot start Dev GC on HAL: " << ret.description();
353 return;
354 }
355 cb->wait(DEVGC_TIMEOUT_SEC);
356}
357
358static void runDevGc(void) {
359 auto service = IFileSystem::getService();
360 if (service != nullptr) {
361 runDevGcOnHal(service);
362 } else {
363 // fallback to legacy code path
364 runDevGcFstab();
365 }
366}
367
Jin Qiana370c142017-10-17 15:41:45 -0700368int RunIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener) {
369 std::unique_lock<std::mutex> lk(cv_m);
370 if (idle_maint_stat != IdleMaintStats::kStopped) {
371 LOG(DEBUG) << "idle maintenance is already running";
372 if (listener) {
373 android::os::PersistableBundle extras;
374 listener->onFinished(0, extras);
375 }
376 return android::OK;
377 }
378 idle_maint_stat = IdleMaintStats::kRunning;
379 lk.unlock();
380
381 LOG(DEBUG) << "idle maintenance started";
382
383 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
384
385 std::list<std::string> paths;
386 addFromFstab(&paths, PathTypes::kBlkDevice);
387 addFromVolumeManager(&paths, PathTypes::kBlkDevice);
388
389 startGc(paths);
390
391 bool gc_aborted = waitForGc(paths);
392
393 stopGc(paths);
394
395 lk.lock();
396 idle_maint_stat = IdleMaintStats::kStopped;
397 lk.unlock();
398
399 cv_stop.notify_one();
400
401 if (!gc_aborted) {
402 Trim(nullptr);
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -0800403 runDevGc();
Jin Qiana370c142017-10-17 15:41:45 -0700404 }
405
406 if (listener) {
407 android::os::PersistableBundle extras;
408 listener->onFinished(0, extras);
409 }
410
411 LOG(DEBUG) << "idle maintenance completed";
412
413 release_wake_lock(kWakeLock);
414
415 return android::OK;
416}
417
418int AbortIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener) {
419 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
420
421 std::unique_lock<std::mutex> lk(cv_m);
422 if (idle_maint_stat != IdleMaintStats::kStopped) {
423 idle_maint_stat = IdleMaintStats::kAbort;
424 lk.unlock();
425 cv_abort.notify_one();
426 lk.lock();
427 LOG(DEBUG) << "aborting idle maintenance";
428 cv_stop.wait(lk, []{
429 return idle_maint_stat == IdleMaintStats::kStopped;});
430 }
431 lk.unlock();
432
433 if (listener) {
434 android::os::PersistableBundle extras;
435 listener->onFinished(0, extras);
436 }
437
438 release_wake_lock(kWakeLock);
439
440 LOG(DEBUG) << "idle maintenance stopped";
441
442 return android::OK;
443}
444
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700445} // namespace vold
446} // namespace android