blob: 459b3b89a3b24aa69110695e34d22d225bf383be [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 Kim1251ef02018-07-29 06:56:57 -070018#include "FileDeviceUtils.h"
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070019#include "Utils.h"
20#include "VolumeManager.h"
Jin Qiana370c142017-10-17 15:41:45 -070021#include "model/PrivateVolume.h"
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070022
Jin Qiana370c142017-10-17 15:41:45 -070023#include <thread>
24
25#include <android-base/chrono_utils.h>
26#include <android-base/file.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080027#include <android-base/logging.h>
Yifan Hong024a1242018-08-10 13:50:46 -070028#include <android-base/stringprintf.h>
29#include <android-base/strings.h>
30#include <android/hardware/health/filesystem/1.0/IFileSystem.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070031#include <fs_mgr.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070032#include <hardware_legacy/power.h>
Yifan Hong024a1242018-08-10 13:50:46 -070033#include <private/android_filesystem_config.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070034
35#include <dirent.h>
36#include <sys/mount.h>
37#include <sys/stat.h>
38#include <sys/types.h>
39#include <sys/wait.h>
40#include <fcntl.h>
41
Jin Qiana370c142017-10-17 15:41:45 -070042using android::base::Basename;
43using android::base::ReadFileToString;
44using android::base::Realpath;
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070045using android::base::StringPrintf;
Jin Qiana370c142017-10-17 15:41:45 -070046using android::base::Timer;
47using android::base::WriteStringToFile;
Yifan Hong024a1242018-08-10 13:50:46 -070048using android::hardware::Return;
49using android::hardware::Void;
50using android::hardware::health::filesystem::V1_0::IFileSystem;
51using android::hardware::health::filesystem::V1_0::IGarbageCollectCallback;
52using android::hardware::health::filesystem::V1_0::Result;
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070053
54namespace android {
55namespace vold {
56
Jin Qiana370c142017-10-17 15:41:45 -070057enum class PathTypes {
58 kMountPoint = 1,
59 kBlkDevice,
60};
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070061
Jin Qiana370c142017-10-17 15:41:45 -070062enum class IdleMaintStats {
63 kStopped = 1,
64 kRunning,
65 kAbort,
66};
67
68static const char* kWakeLock = "IdleMaint";
69static const int DIRTY_SEGMENTS_THRESHOLD = 100;
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -080070/*
71 * Timing policy:
72 * 1. F2FS_GC = 7 mins
73 * 2. Trim = 1 min
74 * 3. Dev GC = 2 mins
75 */
76static const int GC_TIMEOUT_SEC = 420;
77static const int DEVGC_TIMEOUT_SEC = 120;
Jin Qiana370c142017-10-17 15:41:45 -070078
79static IdleMaintStats idle_maint_stat(IdleMaintStats::kStopped);
80static std::condition_variable cv_abort, cv_stop;
81static std::mutex cv_m;
82
83static void addFromVolumeManager(std::list<std::string>* paths,
84 PathTypes path_type) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070085 VolumeManager* vm = VolumeManager::Instance();
86 std::list<std::string> privateIds;
87 vm->listVolumes(VolumeBase::Type::kPrivate, privateIds);
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -070088 for (const auto& id : privateIds) {
Jin Qiana370c142017-10-17 15:41:45 -070089 PrivateVolume* vol = static_cast<PrivateVolume*>(vm->findVolume(id).get());
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070090 if (vol != nullptr && vol->getState() == VolumeBase::State::kMounted) {
Jin Qiana370c142017-10-17 15:41:45 -070091 if (path_type == PathTypes::kMountPoint) {
92 paths->push_back(vol->getPath());
93 } else if (path_type == PathTypes::kBlkDevice) {
94 std::string gc_path;
95 const std::string& fs_type = vol->getFsType();
Jaegeuk Kim1251ef02018-07-29 06:56:57 -070096 if (fs_type == "f2fs" && (Realpath(vol->getRawDmDevPath(), &gc_path) ||
97 Realpath(vol->getRawDevPath(), &gc_path))) {
Jin Qiana370c142017-10-17 15:41:45 -070098 paths->push_back(std::string("/sys/fs/") + fs_type +
99 "/" + Basename(gc_path));
100 }
101 }
102
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700103 }
104 }
105}
106
Jin Qiana370c142017-10-17 15:41:45 -0700107static void addFromFstab(std::list<std::string>* paths, PathTypes path_type) {
Bowgo Tsaie8fb6c32017-03-09 23:11:33 +0800108 std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
109 fs_mgr_free_fstab);
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700110 struct fstab_rec *prev_rec = NULL;
111
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700112 for (int i = 0; i < fstab->num_entries; i++) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600113 auto fs_type = std::string(fstab->recs[i].fs_type);
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700114 /* Skip raw partitions */
Jeff Sharkey3472e522017-10-06 18:02:53 -0600115 if (fs_type == "emmc" || fs_type == "mtd") {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700116 continue;
117 }
118 /* Skip read-only filesystems */
119 if (fstab->recs[i].flags & MS_RDONLY) {
120 continue;
121 }
122 if (fs_mgr_is_voldmanaged(&fstab->recs[i])) {
123 continue; /* Should we trim fat32 filesystems? */
124 }
125 if (fs_mgr_is_notrim(&fstab->recs[i])) {
126 continue;
127 }
128
129 /* Skip the multi-type partitions, which are required to be following each other.
130 * See fs_mgr.c's mount_with_alternatives().
131 */
132 if (prev_rec && !strcmp(prev_rec->mount_point, fstab->recs[i].mount_point)) {
133 continue;
134 }
135
Jin Qiana370c142017-10-17 15:41:45 -0700136 if (path_type == PathTypes::kMountPoint) {
137 paths->push_back(fstab->recs[i].mount_point);
138 } else if (path_type == PathTypes::kBlkDevice) {
139 std::string gc_path;
140 if (std::string(fstab->recs[i].fs_type) == "f2fs" &&
Jaegeuk Kim1251ef02018-07-29 06:56:57 -0700141 Realpath(android::vold::BlockDeviceForPath(
142 std::string(fstab->recs[i].mount_point) + "/"), &gc_path)) {
Jin Qiana370c142017-10-17 15:41:45 -0700143 paths->push_back(std::string("/sys/fs/") + fstab->recs[i].fs_type +
144 "/" + Basename(gc_path));
145 }
146 }
147
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700148 prev_rec = &fstab->recs[i];
149 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700150}
151
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600152void Trim(const android::sp<android::os::IVoldTaskListener>& listener) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700153 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
154
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600155 // Collect both fstab and vold volumes
156 std::list<std::string> paths;
Jin Qiana370c142017-10-17 15:41:45 -0700157 addFromFstab(&paths, PathTypes::kMountPoint);
158 addFromVolumeManager(&paths, PathTypes::kMountPoint);
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600159
160 for (const auto& path : paths) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700161 LOG(DEBUG) << "Starting trim of " << path;
162
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600163 android::os::PersistableBundle extras;
164 extras.putString(String16("path"), String16(path.c_str()));
165
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700166 int fd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
167 if (fd < 0) {
168 PLOG(WARNING) << "Failed to open " << path;
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600169 if (listener) {
170 listener->onStatus(-1, extras);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600171 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700172 continue;
173 }
174
175 struct fstrim_range range;
176 memset(&range, 0, sizeof(range));
177 range.len = ULLONG_MAX;
178
179 nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME);
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600180 if (ioctl(fd, FITRIM, &range)) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700181 PLOG(WARNING) << "Trim failed on " << path;
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600182 if (listener) {
183 listener->onStatus(-1, extras);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600184 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700185 } else {
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600186 nsecs_t time = systemTime(SYSTEM_TIME_BOOTTIME) - start;
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700187 LOG(INFO) << "Trimmed " << range.len << " bytes on " << path
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600188 << " in " << nanoseconds_to_milliseconds(time) << "ms";
189 extras.putLong(String16("bytes"), range.len);
190 extras.putLong(String16("time"), time);
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600191 if (listener) {
192 listener->onStatus(0, extras);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600193 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700194 }
195 close(fd);
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600196 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700197
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600198 if (listener) {
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600199 android::os::PersistableBundle extras;
Jeff Sharkey01a0e7f2017-10-17 16:06:32 -0600200 listener->onFinished(0, extras);
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700201 }
202
203 release_wake_lock(kWakeLock);
204}
205
Jin Qiana370c142017-10-17 15:41:45 -0700206static bool waitForGc(const std::list<std::string>& paths) {
207 std::unique_lock<std::mutex> lk(cv_m, std::defer_lock);
208 bool stop = false, aborted = false;
209 Timer timer;
210
211 while (!stop && !aborted) {
212 stop = true;
213 for (const auto& path : paths) {
214 std::string dirty_segments;
215 if (!ReadFileToString(path + "/dirty_segments", &dirty_segments)) {
216 PLOG(WARNING) << "Reading dirty_segments failed in " << path;
217 continue;
218 }
219 if (std::stoi(dirty_segments) > DIRTY_SEGMENTS_THRESHOLD) {
220 stop = false;
221 break;
222 }
223 }
224
225 if (stop) break;
226
227 if (timer.duration() >= std::chrono::seconds(GC_TIMEOUT_SEC)) {
228 LOG(WARNING) << "GC timeout";
229 break;
230 }
231
232 lk.lock();
233 aborted = cv_abort.wait_for(lk, 10s, []{
234 return idle_maint_stat == IdleMaintStats::kAbort;});
235 lk.unlock();
236 }
237
238 return aborted;
239}
240
241static int startGc(const std::list<std::string>& paths) {
242 for (const auto& path : paths) {
243 LOG(DEBUG) << "Start GC on " << path;
Jaegeuk Kima6aae2f2018-02-17 06:02:30 -0800244 if (!WriteStringToFile("1", path + "/discard_granularity")) {
245 PLOG(WARNING) << "Set discard gralunarity failed on" << path;
246 }
Jin Qiana370c142017-10-17 15:41:45 -0700247 if (!WriteStringToFile("1", path + "/gc_urgent")) {
248 PLOG(WARNING) << "Start GC failed on " << path;
249 }
250 }
251 return android::OK;
252}
253
254static int stopGc(const std::list<std::string>& paths) {
255 for (const auto& path : paths) {
256 LOG(DEBUG) << "Stop GC on " << path;
257 if (!WriteStringToFile("0", path + "/gc_urgent")) {
258 PLOG(WARNING) << "Stop GC failed on " << path;
259 }
Jaegeuk Kima6aae2f2018-02-17 06:02:30 -0800260 if (!WriteStringToFile("16", path + "/discard_granularity")) {
261 PLOG(WARNING) << "Set discard gralunarity failed on" << path;
262 }
Jin Qiana370c142017-10-17 15:41:45 -0700263 }
264 return android::OK;
265}
266
Yifan Hong024a1242018-08-10 13:50:46 -0700267static void runDevGcFstab(void) {
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -0800268 std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
269 fs_mgr_free_fstab);
270 struct fstab_rec *rec = NULL;
271
272 for (int i = 0; i < fstab->num_entries; i++) {
273 if (fs_mgr_has_sysfs_path(&fstab->recs[i])) {
274 rec = &fstab->recs[i];
275 break;
276 }
277 }
278 if (!rec) {
279 return;
280 }
281
282 std::string path;
283 path.append(rec->sysfs_path);
284 path = path + "/manual_gc";
285 Timer timer;
286
287 LOG(DEBUG) << "Start Dev GC on " << path;
288 while (1) {
289 std::string require;
290 if (!ReadFileToString(path, &require)) {
291 PLOG(WARNING) << "Reading manual_gc failed in " << path;
292 break;
293 }
Yifan Hong024a1242018-08-10 13:50:46 -0700294 require = android::base::Trim(require);
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -0800295 if (require == "" || require == "off" || require == "disabled") {
296 LOG(DEBUG) << "No more to do Dev GC";
297 break;
298 }
299
300 LOG(DEBUG) << "Trigger Dev GC on " << path;
301 if (!WriteStringToFile("1", path)) {
302 PLOG(WARNING) << "Start Dev GC failed on " << path;
303 break;
304 }
305
306 if (timer.duration() >= std::chrono::seconds(DEVGC_TIMEOUT_SEC)) {
307 LOG(WARNING) << "Dev GC timeout";
308 break;
309 }
310 sleep(2);
311 }
312 LOG(DEBUG) << "Stop Dev GC on " << path;
313 if (!WriteStringToFile("0", path)) {
314 PLOG(WARNING) << "Stop Dev GC failed on " << path;
315 }
316 return;
317}
318
Yifan Hong024a1242018-08-10 13:50:46 -0700319class GcCallback : public IGarbageCollectCallback {
320 public:
321 Return<void> onFinish(Result result) override {
322 std::unique_lock<std::mutex> lock(mMutex);
323 mFinished = true;
324 mResult = result;
325 lock.unlock();
326 mCv.notify_all();
327 return Void();
328 }
329 void wait(uint64_t seconds) {
330 std::unique_lock<std::mutex> lock(mMutex);
331 mCv.wait_for(lock, std::chrono::seconds(seconds), [this] { return mFinished; });
332
333 if (!mFinished) {
334 LOG(WARNING) << "Dev GC on HAL timeout";
335 } else if (mResult != Result::SUCCESS) {
336 LOG(WARNING) << "Dev GC on HAL failed with " << toString(mResult);
337 } else {
338 LOG(INFO) << "Dev GC on HAL successful";
339 }
340 }
341
342 private:
343 std::mutex mMutex;
344 std::condition_variable mCv;
345 bool mFinished{false};
346 Result mResult{Result::UNKNOWN_ERROR};
347};
348
349static void runDevGcOnHal(sp<IFileSystem> service) {
350 LOG(DEBUG) << "Start Dev GC on HAL";
351 sp<GcCallback> cb = new GcCallback();
352 auto ret = service->garbageCollect(DEVGC_TIMEOUT_SEC, cb);
353 if (!ret.isOk()) {
354 LOG(WARNING) << "Cannot start Dev GC on HAL: " << ret.description();
355 return;
356 }
357 cb->wait(DEVGC_TIMEOUT_SEC);
358}
359
360static void runDevGc(void) {
361 auto service = IFileSystem::getService();
362 if (service != nullptr) {
363 runDevGcOnHal(service);
364 } else {
365 // fallback to legacy code path
366 runDevGcFstab();
367 }
368}
369
Jin Qiana370c142017-10-17 15:41:45 -0700370int RunIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener) {
371 std::unique_lock<std::mutex> lk(cv_m);
372 if (idle_maint_stat != IdleMaintStats::kStopped) {
373 LOG(DEBUG) << "idle maintenance is already running";
374 if (listener) {
375 android::os::PersistableBundle extras;
376 listener->onFinished(0, extras);
377 }
378 return android::OK;
379 }
380 idle_maint_stat = IdleMaintStats::kRunning;
381 lk.unlock();
382
383 LOG(DEBUG) << "idle maintenance started";
384
385 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
386
387 std::list<std::string> paths;
388 addFromFstab(&paths, PathTypes::kBlkDevice);
389 addFromVolumeManager(&paths, PathTypes::kBlkDevice);
390
391 startGc(paths);
392
393 bool gc_aborted = waitForGc(paths);
394
395 stopGc(paths);
396
397 lk.lock();
398 idle_maint_stat = IdleMaintStats::kStopped;
399 lk.unlock();
400
401 cv_stop.notify_one();
402
403 if (!gc_aborted) {
404 Trim(nullptr);
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -0800405 runDevGc();
Jin Qiana370c142017-10-17 15:41:45 -0700406 }
407
408 if (listener) {
409 android::os::PersistableBundle extras;
410 listener->onFinished(0, extras);
411 }
412
413 LOG(DEBUG) << "idle maintenance completed";
414
415 release_wake_lock(kWakeLock);
416
417 return android::OK;
418}
419
420int AbortIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener) {
421 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
422
423 std::unique_lock<std::mutex> lk(cv_m);
424 if (idle_maint_stat != IdleMaintStats::kStopped) {
425 idle_maint_stat = IdleMaintStats::kAbort;
426 lk.unlock();
427 cv_abort.notify_one();
428 lk.lock();
429 LOG(DEBUG) << "aborting idle maintenance";
430 cv_stop.wait(lk, []{
431 return idle_maint_stat == IdleMaintStats::kStopped;});
432 }
433 lk.unlock();
434
435 if (listener) {
436 android::os::PersistableBundle extras;
437 listener->onFinished(0, extras);
438 }
439
440 release_wake_lock(kWakeLock);
441
442 LOG(DEBUG) << "idle maintenance stopped";
443
444 return android::OK;
445}
446
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700447} // namespace vold
448} // namespace android