blob: 79894fc69de77e826d35b792874ca1096aeeee0f [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>
Yifan Hong91a68df2018-09-19 10:28:16 -070030#include <android/hardware/health/storage/1.0/IStorage.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>
Paul Crowley14c8c072018-09-18 13:30:21 -070036#include <fcntl.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070037#include <sys/mount.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40#include <sys/wait.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070041
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;
Yifan Hong91a68df2018-09-19 10:28:16 -070050using android::hardware::health::storage::V1_0::IGarbageCollectCallback;
51using android::hardware::health::storage::V1_0::IStorage;
52using android::hardware::health::storage::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
Paul Crowley14c8c072018-09-18 13:30:21 -070083static void addFromVolumeManager(std::list<std::string>* paths, 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();
Jaegeuk Kim1251ef02018-07-29 06:56:57 -070095 if (fs_type == "f2fs" && (Realpath(vol->getRawDmDevPath(), &gc_path) ||
96 Realpath(vol->getRawDevPath(), &gc_path))) {
Paul Crowley14c8c072018-09-18 13:30:21 -070097 paths->push_back(std::string("/sys/fs/") + fs_type + "/" + Basename(gc_path));
Jin Qiana370c142017-10-17 15:41:45 -070098 }
99 }
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700100 }
101 }
102}
103
Jin Qiana370c142017-10-17 15:41:45 -0700104static void addFromFstab(std::list<std::string>* paths, PathTypes path_type) {
Bowgo Tsaie8fb6c32017-03-09 23:11:33 +0800105 std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
106 fs_mgr_free_fstab);
Paul Crowley14c8c072018-09-18 13:30:21 -0700107 struct fstab_rec* prev_rec = NULL;
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700108
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700109 for (int i = 0; i < fstab->num_entries; i++) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600110 auto fs_type = std::string(fstab->recs[i].fs_type);
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700111 /* Skip raw partitions */
Jeff Sharkey3472e522017-10-06 18:02:53 -0600112 if (fs_type == "emmc" || fs_type == "mtd") {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700113 continue;
114 }
115 /* Skip read-only filesystems */
116 if (fstab->recs[i].flags & MS_RDONLY) {
117 continue;
118 }
119 if (fs_mgr_is_voldmanaged(&fstab->recs[i])) {
120 continue; /* Should we trim fat32 filesystems? */
121 }
122 if (fs_mgr_is_notrim(&fstab->recs[i])) {
123 continue;
124 }
125
126 /* Skip the multi-type partitions, which are required to be following each other.
127 * See fs_mgr.c's mount_with_alternatives().
128 */
129 if (prev_rec && !strcmp(prev_rec->mount_point, fstab->recs[i].mount_point)) {
130 continue;
131 }
132
Jin Qiana370c142017-10-17 15:41:45 -0700133 if (path_type == PathTypes::kMountPoint) {
134 paths->push_back(fstab->recs[i].mount_point);
135 } else if (path_type == PathTypes::kBlkDevice) {
136 std::string gc_path;
137 if (std::string(fstab->recs[i].fs_type) == "f2fs" &&
Paul Crowley14c8c072018-09-18 13:30:21 -0700138 Realpath(
139 android::vold::BlockDeviceForPath(std::string(fstab->recs[i].mount_point) + "/"),
140 &gc_path)) {
141 paths->push_back(std::string("/sys/fs/") + fstab->recs[i].fs_type + "/" +
142 Basename(gc_path));
Jin Qiana370c142017-10-17 15:41:45 -0700143 }
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;
Paul Crowley14c8c072018-09-18 13:30:21 -0700185 LOG(INFO) << "Trimmed " << range.len << " bytes on " << path << " in "
186 << nanoseconds_to_milliseconds(time) << "ms";
Jeff Sharkey52f7a912017-09-15 12:57:44 -0600187 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();
Paul Crowley14c8c072018-09-18 13:30:21 -0700231 aborted =
232 cv_abort.wait_for(lk, 10s, [] { return idle_maint_stat == IdleMaintStats::kAbort; });
Jin Qiana370c142017-10-17 15:41:45 -0700233 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);
Paul Crowley14c8c072018-09-18 13:30:21 -0700268 struct fstab_rec* rec = NULL;
Jaegeuk Kimeefc5ee2018-02-12 21:57:04 -0800269
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
Yifan Hong91a68df2018-09-19 10:28:16 -0700347static void runDevGcOnHal(sp<IStorage> service) {
Yifan Hong024a1242018-08-10 13:50:46 -0700348 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) {
Yifan Hong91a68df2018-09-19 10:28:16 -0700359 auto service = IStorage::getService();
Yifan Hong024a1242018-08-10 13:50:46 -0700360 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";
Paul Crowley14c8c072018-09-18 13:30:21 -0700428 cv_stop.wait(lk, [] { return idle_maint_stat == IdleMaintStats::kStopped; });
Jin Qiana370c142017-10-17 15:41:45 -0700429 }
430 lk.unlock();
431
432 if (listener) {
433 android::os::PersistableBundle extras;
434 listener->onFinished(0, extras);
435 }
436
437 release_wake_lock(kWakeLock);
438
439 LOG(DEBUG) << "idle maintenance stopped";
440
441 return android::OK;
442}
443
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700444} // namespace vold
445} // namespace android