blob: 45c9ad9b344b9a0c9db23bb8342b90a7bfaed2fe [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 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#define LOG_TAG "IncrementalService"
18
19#include "IncrementalService.h"
20
Songchun Fan3c82a302019-11-29 14:23:45 -080021#include <android-base/logging.h>
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -070022#include <android-base/no_destructor.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080023#include <android-base/properties.h>
24#include <android-base/stringprintf.h>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070025#include <binder/AppOpsManager.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080026#include <binder/Status.h>
27#include <sys/stat.h>
28#include <uuid/uuid.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080029
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070030#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080031#include <ctime>
Songchun Fan3c82a302019-11-29 14:23:45 -080032#include <iterator>
33#include <span>
Songchun Fan3c82a302019-11-29 14:23:45 -080034#include <type_traits>
35
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070036#include "IncrementalServiceValidation.h"
Songchun Fan3c82a302019-11-29 14:23:45 -080037#include "Metadata.pb.h"
38
39using namespace std::literals;
Songchun Fan3c82a302019-11-29 14:23:45 -080040
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070041constexpr const char* kDataUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070042constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070043
Songchun Fan3c82a302019-11-29 14:23:45 -080044namespace android::incremental {
45
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070046using content::pm::DataLoaderParamsParcel;
47using content::pm::FileSystemControlParcel;
48using content::pm::IDataLoader;
49
Songchun Fan3c82a302019-11-29 14:23:45 -080050namespace {
51
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070052using IncrementalFileSystemControlParcel = os::incremental::IncrementalFileSystemControlParcel;
Songchun Fan3c82a302019-11-29 14:23:45 -080053
54struct Constants {
55 static constexpr auto backing = "backing_store"sv;
56 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080057 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080058 static constexpr auto storagePrefix = "st"sv;
59 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
60 static constexpr auto infoMdName = ".info"sv;
Alex Buynytskyy04035452020-06-06 20:15:58 -070061 static constexpr auto readLogsDisabledMarkerName = ".readlogs_disabled"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080062 static constexpr auto libDir = "lib"sv;
63 static constexpr auto libSuffix = ".so"sv;
64 static constexpr auto blockSize = 4096;
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -070065 static constexpr auto systemPackage = "android"sv;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -080066
67 static constexpr auto progressUpdateInterval = 1000ms;
68 static constexpr auto perUidTimeoutOffset = progressUpdateInterval * 2;
69 static constexpr auto minPerUidTimeout = progressUpdateInterval * 3;
Songchun Fan3c82a302019-11-29 14:23:45 -080070};
71
72static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070073 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080074 return c;
75}
76
77template <base::LogSeverity level = base::ERROR>
78bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
79 auto cstr = path::c_str(name);
80 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080081 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080082 PLOG(level) << "Can't create directory '" << name << '\'';
83 return false;
84 }
85 struct stat st;
86 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
87 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
88 return false;
89 }
90 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080091 if (::chmod(cstr, mode)) {
92 PLOG(level) << "Changing permission failed for '" << name << '\'';
93 return false;
94 }
95
Songchun Fan3c82a302019-11-29 14:23:45 -080096 return true;
97}
98
99static std::string toMountKey(std::string_view path) {
100 if (path.empty()) {
101 return "@none";
102 }
103 if (path == "/"sv) {
104 return "@root";
105 }
106 if (path::isAbsolute(path)) {
107 path.remove_prefix(1);
108 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700109 if (path.size() > 16) {
110 path = path.substr(0, 16);
111 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800112 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700113 std::replace_if(
114 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
115 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800116}
117
118static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
119 std::string_view path) {
120 auto mountKey = toMountKey(path);
121 const auto prefixSize = mountKey.size();
122 for (int counter = 0; counter < 1000;
123 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
124 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800125 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800126 return {mountKey, mountRoot};
127 }
128 }
129 return {};
130}
131
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700132template <class Map>
133typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
134 const auto nextIt = map.upper_bound(path);
135 if (nextIt == map.begin()) {
136 return map.end();
137 }
138 const auto suspectIt = std::prev(nextIt);
139 if (!path::startsWith(path, suspectIt->first)) {
140 return map.end();
141 }
142 return suspectIt;
143}
144
145static base::unique_fd dup(base::borrowed_fd fd) {
146 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
147 return base::unique_fd(res);
148}
149
Songchun Fan3c82a302019-11-29 14:23:45 -0800150template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700151static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800152 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800153 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800154 ProtoMessage message;
155 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
156}
157
158static bool isValidMountTarget(std::string_view path) {
159 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
160}
161
162std::string makeBindMdName() {
163 static constexpr auto uuidStringSize = 36;
164
165 uuid_t guid;
166 uuid_generate(guid);
167
168 std::string name;
169 const auto prefixSize = constants().mountpointMdPrefix.size();
170 name.reserve(prefixSize + uuidStringSize);
171
172 name = constants().mountpointMdPrefix;
173 name.resize(prefixSize + uuidStringSize);
174 uuid_unparse(guid, name.data() + prefixSize);
175
176 return name;
177}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700178
179static bool checkReadLogsDisabledMarker(std::string_view root) {
180 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
181 struct stat st;
182 return (::stat(markerPath, &st) == 0);
183}
184
Songchun Fan3c82a302019-11-29 14:23:45 -0800185} // namespace
186
187IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700188 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700189 dataLoaderStub->cleanupResources();
190 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700191 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700192 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800193 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
194 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700195 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800196 incrementalService.mVold->unmountIncFs(target);
197 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700198 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800199 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
200 cleanupFilesystem(root);
201}
202
203auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800204 std::string name;
205 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
206 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
207 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800208 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
209 constants().storagePrefix.data(), id, no);
210 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800211 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800212 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800213 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
214 } else if (err != EEXIST) {
215 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
216 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800217 }
218 }
219 nextStorageDirNo = 0;
220 return storages.end();
221}
222
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700223template <class Func>
224static auto makeCleanup(Func&& f) {
225 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700226 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700227 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
228}
229
230static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
231 return {::opendir(dir), ::closedir};
232}
233
234static auto openDir(std::string_view dir) {
235 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800236}
237
238static int rmDirContent(const char* path) {
239 auto dir = openDir(path);
240 if (!dir) {
241 return -EINVAL;
242 }
243 while (auto entry = ::readdir(dir.get())) {
244 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
245 continue;
246 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700247 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800248 if (entry->d_type == DT_DIR) {
249 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
250 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
251 return err;
252 }
253 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
254 PLOG(WARNING) << "Failed to rmdir " << fullPath;
255 return err;
256 }
257 } else {
258 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
259 PLOG(WARNING) << "Failed to delete " << fullPath;
260 return err;
261 }
262 }
263 }
264 return 0;
265}
266
Songchun Fan3c82a302019-11-29 14:23:45 -0800267void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800268 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800269 ::rmdir(path::join(root, constants().backing).c_str());
270 ::rmdir(path::join(root, constants().mount).c_str());
271 ::rmdir(path::c_str(root));
272}
273
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800274IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800275 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800276 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800277 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700278 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700279 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700280 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700281 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700282 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700283 mFs(sm.getFs()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800284 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700285 CHECK(mVold) << "Vold service is unavailable";
286 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
287 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
288 CHECK(mJni) << "JNI is unavailable";
289 CHECK(mLooper) << "Looper is unavailable";
290 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700291 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700292 CHECK(mFs) << "Fs is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700293
294 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700295 mJobProcessor = std::thread([this]() {
296 mJni->initializeForCurrentThread();
297 runJobProcessing();
298 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700299 mCmdLooperThread = std::thread([this]() {
300 mJni->initializeForCurrentThread();
301 runCmdLooper();
302 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700303
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700304 const auto mountedRootNames = adoptMountedInstances();
305 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800306}
307
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700308IncrementalService::~IncrementalService() {
309 {
310 std::lock_guard lock(mJobMutex);
311 mRunning = false;
312 }
313 mJobCondition.notify_all();
314 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700315 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700316 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700317 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700318 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700319 // Ensure that mounts are destroyed while the service is still valid.
320 mBindsByPath.clear();
321 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700322}
Songchun Fan3c82a302019-11-29 14:23:45 -0800323
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700324static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800325 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800326 case IncrementalService::BindKind::Temporary:
327 return "Temporary";
328 case IncrementalService::BindKind::Permanent:
329 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800330 }
331}
332
333void IncrementalService::onDump(int fd) {
334 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
335 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
336
337 std::unique_lock l(mLock);
338
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700339 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800340 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700341 const IncFsMount& mnt = *ifs;
342 dprintf(fd, " [%d]: {\n", id);
343 if (id != mnt.mountId) {
344 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
345 } else {
346 dprintf(fd, " mountId: %d\n", mnt.mountId);
347 dprintf(fd, " root: %s\n", mnt.root.c_str());
348 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
349 if (mnt.dataLoaderStub) {
350 mnt.dataLoaderStub->onDump(fd);
351 } else {
352 dprintf(fd, " dataLoader: null\n");
353 }
354 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
355 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700356 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800357 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
358 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700359 }
360 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800361
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700362 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
363 for (auto&& [target, bind] : mnt.bindPoints) {
364 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
365 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
366 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
367 dprintf(fd, " kind: %s\n", toString(bind.kind));
368 }
369 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800370 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700371 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800372 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700373 dprintf(fd, "}\n");
374 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800375 for (auto&& [target, mountPairIt] : mBindsByPath) {
376 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700377 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
378 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
379 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
380 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800381 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700382 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800383}
384
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700385void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800386 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700387 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800388 }
389
390 std::vector<IfsMountPtr> mounts;
391 {
392 std::lock_guard l(mLock);
393 mounts.reserve(mMounts.size());
394 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -0700395 if (ifs->mountId == id &&
396 ifs->dataLoaderStub->params().packageName == Constants::systemPackage) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800397 mounts.push_back(ifs);
398 }
399 }
400 }
401
Alex Buynytskyy69941662020-04-11 21:40:37 -0700402 if (mounts.empty()) {
403 return;
404 }
405
Songchun Fan3c82a302019-11-29 14:23:45 -0800406 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700407 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800408 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700409 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800410 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800411 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800412}
413
414auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
415 for (;;) {
416 if (mNextId == kMaxStorageId) {
417 mNextId = 0;
418 }
419 auto id = ++mNextId;
420 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
421 if (inserted) {
422 return it;
423 }
424 }
425}
426
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800427StorageId IncrementalService::createStorage(
428 std::string_view mountPoint, content::pm::DataLoaderParamsParcel&& dataLoaderParams,
429 CreateOptions options, const DataLoaderStatusListener& statusListener,
430 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener& healthListener,
431 const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800432 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
433 if (!path::isAbsolute(mountPoint)) {
434 LOG(ERROR) << "path is not absolute: " << mountPoint;
435 return kInvalidStorageId;
436 }
437
438 auto mountNorm = path::normalize(mountPoint);
439 {
440 const auto id = findStorageId(mountNorm);
441 if (id != kInvalidStorageId) {
442 if (options & CreateOptions::OpenExisting) {
443 LOG(INFO) << "Opened existing storage " << id;
444 return id;
445 }
446 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
447 return kInvalidStorageId;
448 }
449 }
450
451 if (!(options & CreateOptions::CreateNew)) {
452 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
453 return kInvalidStorageId;
454 }
455
456 if (!path::isEmptyDir(mountNorm)) {
457 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
458 return kInvalidStorageId;
459 }
460 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
461 if (mountRoot.empty()) {
462 LOG(ERROR) << "Bad mount point";
463 return kInvalidStorageId;
464 }
465 // Make sure the code removes all crap it may create while still failing.
466 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
467 auto firstCleanupOnFailure =
468 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
469
470 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800471 const auto backing = path::join(mountRoot, constants().backing);
472 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800473 return kInvalidStorageId;
474 }
475
Songchun Fan3c82a302019-11-29 14:23:45 -0800476 IncFsMount::Control control;
477 {
478 std::lock_guard l(mMountOperationLock);
479 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800480
481 if (auto err = rmDirContent(backing.c_str())) {
482 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
483 return kInvalidStorageId;
484 }
485 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
486 return kInvalidStorageId;
487 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800488 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
489 return kInvalidStorageId;
490 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800491 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800492 if (!status.isOk()) {
493 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
494 return kInvalidStorageId;
495 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800496 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
497 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800498 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
499 return kInvalidStorageId;
500 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800501 int cmd = controlParcel.cmd.release().release();
502 int pendingReads = controlParcel.pendingReads.release().release();
503 int logs = controlParcel.log.release().release();
504 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800505 }
506
507 std::unique_lock l(mLock);
508 const auto mountIt = getStorageSlotLocked();
509 const auto mountId = mountIt->first;
510 l.unlock();
511
512 auto ifs =
513 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
514 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
515 // is the removal of the |ifs|.
516 firstCleanupOnFailure.release();
517
518 auto secondCleanup = [this, &l](auto itPtr) {
519 if (!l.owns_lock()) {
520 l.lock();
521 }
522 mMounts.erase(*itPtr);
523 };
524 auto secondCleanupOnFailure =
525 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
526
527 const auto storageIt = ifs->makeStorage(ifs->mountId);
528 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800529 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800530 return kInvalidStorageId;
531 }
532
533 {
534 metadata::Mount m;
535 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700536 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700537 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
538 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
539 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800540 const auto metadata = m.SerializeAsString();
541 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800542 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800543 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800544 if (auto err =
545 mIncFs->makeFile(ifs->control,
546 path::join(ifs->root, constants().mount,
547 constants().infoMdName),
548 0777, idFromMetadata(metadata),
549 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800550 LOG(ERROR) << "Saving mount metadata failed: " << -err;
551 return kInvalidStorageId;
552 }
553 }
554
555 const auto bk =
556 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800557 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
558 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800559 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800560 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800561 return kInvalidStorageId;
562 }
563
564 // Done here as well, all data structures are in good state.
565 secondCleanupOnFailure.release();
566
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800567 // DataLoader.
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700568 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
569 std::move(healthCheckParams), &healthListener);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700570 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800571
572 mountIt->second = std::move(ifs);
573 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700574
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800575 // Per Uid timeouts.
576 if (!perUidReadTimeouts.empty()) {
577 setUidReadTimeouts(mountId, perUidReadTimeouts);
578 }
579
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700580 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700581 // failed to create data loader
582 LOG(ERROR) << "initializeDataLoader() failed";
583 deleteStorage(dataLoaderStub->id());
584 return kInvalidStorageId;
585 }
586
Songchun Fan3c82a302019-11-29 14:23:45 -0800587 LOG(INFO) << "created storage " << mountId;
588 return mountId;
589}
590
591StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
592 StorageId linkedStorage,
593 IncrementalService::CreateOptions options) {
594 if (!isValidMountTarget(mountPoint)) {
595 LOG(ERROR) << "Mount point is invalid or missing";
596 return kInvalidStorageId;
597 }
598
599 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700600 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800601 if (!ifs) {
602 LOG(ERROR) << "Ifs unavailable";
603 return kInvalidStorageId;
604 }
605
606 const auto mountIt = getStorageSlotLocked();
607 const auto storageId = mountIt->first;
608 const auto storageIt = ifs->makeStorage(storageId);
609 if (storageIt == ifs->storages.end()) {
610 LOG(ERROR) << "Can't create a new storage";
611 mMounts.erase(mountIt);
612 return kInvalidStorageId;
613 }
614
615 l.unlock();
616
617 const auto bk =
618 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800619 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
620 std::string(storageIt->second.name), path::normalize(mountPoint),
621 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800622 err < 0) {
623 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700624 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
625 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800626 return kInvalidStorageId;
627 }
628
629 mountIt->second = ifs;
630 return storageId;
631}
632
633IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
634 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700635 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800636}
637
638StorageId IncrementalService::findStorageId(std::string_view path) const {
639 std::lock_guard l(mLock);
640 auto it = findStorageLocked(path);
641 if (it == mBindsByPath.end()) {
642 return kInvalidStorageId;
643 }
644 return it->second->second.storage;
645}
646
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800647void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700648 std::unique_lock l(mLock);
649 const auto ifs = getIfsLocked(storageId);
650 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800651 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700652 return;
653 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800654 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700655 return;
656 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800657 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700658 l.unlock();
659
660 const auto metadata = constants().readLogsDisabledMarkerName;
661 if (auto err = mIncFs->makeFile(ifs->control,
662 path::join(ifs->root, constants().mount,
663 constants().readLogsDisabledMarkerName),
664 0777, idFromMetadata(metadata), {})) {
665 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
666 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
667 return;
668 }
669
670 setStorageParams(storageId, /*enableReadLogs=*/false);
671}
672
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700673int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
674 const auto ifs = getIfs(storageId);
675 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700676 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700677 return -EINVAL;
678 }
679
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700680 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700681 if (enableReadLogs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800682 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700683 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
684 return -EPERM;
685 }
686
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700687 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
688 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700689 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700690 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700691 return fromBinderStatus(status);
692 }
693 }
694
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700695 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
696 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
697 return fromBinderStatus(status);
698 }
699
700 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700701 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700702 }
703
704 return 0;
705}
706
707binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700708 os::incremental::IncrementalFileSystemControlParcel control;
709 control.cmd.reset(dup(ifs.control.cmd()));
710 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700711 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700712 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700713 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700714 }
715
716 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800717 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
718 if (status.isOk()) {
719 // Store enabled state.
720 ifs.setReadLogsEnabled(enableReadLogs);
721 }
722 return status;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700723}
724
Songchun Fan3c82a302019-11-29 14:23:45 -0800725void IncrementalService::deleteStorage(StorageId storageId) {
726 const auto ifs = getIfs(storageId);
727 if (!ifs) {
728 return;
729 }
730 deleteStorage(*ifs);
731}
732
733void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
734 std::unique_lock l(ifs.lock);
735 deleteStorageLocked(ifs, std::move(l));
736}
737
738void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
739 std::unique_lock<std::mutex>&& ifsLock) {
740 const auto storages = std::move(ifs.storages);
741 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
742 const auto bindPoints = ifs.bindPoints;
743 ifsLock.unlock();
744
745 std::lock_guard l(mLock);
746 for (auto&& [id, _] : storages) {
747 if (id != ifs.mountId) {
748 mMounts.erase(id);
749 }
750 }
751 for (auto&& [path, _] : bindPoints) {
752 mBindsByPath.erase(path);
753 }
754 mMounts.erase(ifs.mountId);
755}
756
757StorageId IncrementalService::openStorage(std::string_view pathInMount) {
758 if (!path::isAbsolute(pathInMount)) {
759 return kInvalidStorageId;
760 }
761
762 return findStorageId(path::normalize(pathInMount));
763}
764
Songchun Fan3c82a302019-11-29 14:23:45 -0800765IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
766 std::lock_guard l(mLock);
767 return getIfsLocked(storage);
768}
769
770const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
771 auto it = mMounts.find(storage);
772 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700773 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700774 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800775 }
776 return it->second;
777}
778
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800779int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
780 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800781 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700782 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800783 return -EINVAL;
784 }
785
786 const auto ifs = getIfs(storage);
787 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700788 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800789 return -EINVAL;
790 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800791
Songchun Fan3c82a302019-11-29 14:23:45 -0800792 std::unique_lock l(ifs->lock);
793 const auto storageInfo = ifs->storages.find(storage);
794 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700795 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800796 return -EINVAL;
797 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700798 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700799 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700800 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700801 return -EINVAL;
802 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800803 l.unlock();
804 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800805 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
806 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800807}
808
809int IncrementalService::unbind(StorageId storage, std::string_view target) {
810 if (!path::isAbsolute(target)) {
811 return -EINVAL;
812 }
813
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700814 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800815
816 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
817 // otherwise there's a chance to unmount something completely unrelated
818 const auto norm = path::normalize(target);
819 std::unique_lock l(mLock);
820 const auto storageIt = mBindsByPath.find(norm);
821 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
822 return -EINVAL;
823 }
824 const auto bindIt = storageIt->second;
825 const auto storageId = bindIt->second.storage;
826 const auto ifs = getIfsLocked(storageId);
827 if (!ifs) {
828 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
829 << " is missing";
830 return -EFAULT;
831 }
832 mBindsByPath.erase(storageIt);
833 l.unlock();
834
835 mVold->unmountIncFs(bindIt->first);
836 std::unique_lock l2(ifs->lock);
837 if (ifs->bindPoints.size() <= 1) {
838 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700839 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800840 } else {
841 const std::string savedFile = std::move(bindIt->second.savedFilename);
842 ifs->bindPoints.erase(bindIt);
843 l2.unlock();
844 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800845 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800846 }
847 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700848
Songchun Fan3c82a302019-11-29 14:23:45 -0800849 return 0;
850}
851
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700852std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700853 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700854 std::string_view path) const {
855 if (!path::isAbsolute(path)) {
856 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700857 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700858 auto normPath = path::normalize(path);
859 if (path::startsWith(normPath, storageIt->second.name)) {
860 return normPath;
861 }
862 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700863 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
864 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700865 return {};
866 }
867 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700868}
869
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700870std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700871 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700872 std::unique_lock l(ifs.lock);
873 const auto storageInfo = ifs.storages.find(storage);
874 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800875 return {};
876 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700877 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800878}
879
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800880int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700881 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800882 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700883 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800884 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700885 LOG(ERROR) << "Internal error: storageId " << storage
886 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800887 return -EINVAL;
888 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700889 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700890 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800891 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800892 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700893 if (!data.empty()) {
894 if (auto err = setFileContent(ifs, id, path, data); err) {
895 return err;
896 }
897 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800898 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800899 }
900 return -EINVAL;
901}
902
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800903int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800904 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700905 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800906 if (normPath.empty()) {
907 return -EINVAL;
908 }
909 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800910 }
911 return -EINVAL;
912}
913
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800914int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800915 const auto ifs = getIfs(storageId);
916 if (!ifs) {
917 return -EINVAL;
918 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700919 return makeDirs(*ifs, storageId, path, mode);
920}
921
922int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
923 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800924 std::string normPath = normalizePathToStorage(ifs, storageId, path);
925 if (normPath.empty()) {
926 return -EINVAL;
927 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700928 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800929}
930
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800931int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
932 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700933 std::unique_lock l(mLock);
934 auto ifsSrc = getIfsLocked(sourceStorageId);
935 if (!ifsSrc) {
936 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800937 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700938 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
939 return -EINVAL;
940 }
941 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700942 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
943 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700944 if (normOldPath.empty() || normNewPath.empty()) {
945 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
946 return -EINVAL;
947 }
948 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800949}
950
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800951int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800952 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700953 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800954 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800955 }
956 return -EINVAL;
957}
958
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800959int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
960 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800961 std::string&& target, BindKind kind,
962 std::unique_lock<std::mutex>& mainLock) {
963 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700964 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800965 return -EINVAL;
966 }
967
968 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700969 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800970 if (kind != BindKind::Temporary) {
971 metadata::BindPoint bp;
972 bp.set_storage_id(storage);
973 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800974 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800975 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800976 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800977 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800978 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700979 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
980 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
981 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800982 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700983 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800984 return int(node);
985 }
986 }
987
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700988 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
989 std::move(target), kind, mainLock);
990 if (res) {
991 mIncFs->unlink(ifs.control, metadataFullPath);
992 }
993 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800994}
995
996int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800997 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800998 std::string&& target, BindKind kind,
999 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001000 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001001 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001002 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001003 if (!status.isOk()) {
1004 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1005 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1006 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1007 : status.serviceSpecificErrorCode() == 0
1008 ? -EFAULT
1009 : status.serviceSpecificErrorCode()
1010 : -EIO;
1011 }
1012 }
1013
1014 if (!mainLock.owns_lock()) {
1015 mainLock.lock();
1016 }
1017 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001018 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1019 std::move(target), kind);
1020 return 0;
1021}
1022
1023void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1024 std::string&& metadataName, std::string&& source,
1025 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001026 const auto [it, _] =
1027 ifs.bindPoints.insert_or_assign(target,
1028 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001029 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001030 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001031}
1032
1033RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1034 const auto ifs = getIfs(storage);
1035 if (!ifs) {
1036 return {};
1037 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001038 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001039 if (normPath.empty()) {
1040 return {};
1041 }
1042 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001043}
1044
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001045RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001046 const auto ifs = getIfs(storage);
1047 if (!ifs) {
1048 return {};
1049 }
1050 return mIncFs->getMetadata(ifs->control, node);
1051}
1052
Songchun Fan3c82a302019-11-29 14:23:45 -08001053bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001054 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001055 {
1056 std::unique_lock l(mLock);
1057 const auto& ifs = getIfsLocked(storage);
1058 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001059 return false;
1060 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001061 dataLoaderStub = ifs->dataLoaderStub;
1062 if (!dataLoaderStub) {
1063 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001064 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001065 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001066 dataLoaderStub->requestStart();
1067 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001068}
1069
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001070void IncrementalService::setUidReadTimeouts(
1071 StorageId storage, const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
1072 using microseconds = std::chrono::microseconds;
1073 using milliseconds = std::chrono::milliseconds;
1074
1075 auto maxPendingTimeUs = microseconds(0);
1076 for (const auto& timeouts : perUidReadTimeouts) {
1077 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1078 }
1079 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
1080 return;
1081 }
1082
1083 const auto ifs = getIfs(storage);
1084 if (!ifs) {
1085 return;
1086 }
1087
1088 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1089 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1090 return;
1091 }
1092
1093 const auto timeout = std::chrono::duration_cast<milliseconds>(maxPendingTimeUs) -
1094 Constants::perUidTimeoutOffset;
1095 updateUidReadTimeouts(storage, Clock::now() + timeout);
1096}
1097
1098void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1099 const auto ifs = getIfs(storage);
1100 if (!ifs) {
1101 return;
1102 }
1103
1104 mIncFs->setUidReadTimeouts(ifs->control, {});
1105}
1106
1107void IncrementalService::updateUidReadTimeouts(StorageId storage, Clock::time_point timeLimit) {
1108 // Reached maximum timeout.
1109 if (Clock::now() >= timeLimit) {
1110 return clearUidReadTimeouts(storage);
1111 }
1112
1113 // Still loading?
1114 const auto progress = getLoadingProgress(storage);
1115 if (progress.isError()) {
1116 // Something is wrong, abort.
1117 return clearUidReadTimeouts(storage);
1118 }
1119
1120 if (progress.started() && progress.fullyLoaded()) {
1121 // Fully loaded, check readLogs collection.
1122 const auto ifs = getIfs(storage);
1123 if (!ifs->readLogsEnabled()) {
1124 return clearUidReadTimeouts(storage);
1125 }
1126 }
1127
1128 const auto timeLeft = timeLimit - Clock::now();
1129 if (timeLeft < Constants::progressUpdateInterval) {
1130 // Don't bother.
1131 return clearUidReadTimeouts(storage);
1132 }
1133
1134 addTimedJob(*mTimedQueue, storage, Constants::progressUpdateInterval,
1135 [this, storage, timeLimit]() { updateUidReadTimeouts(storage, timeLimit); });
1136}
1137
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001138std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1139 std::unordered_set<std::string_view> mountedRootNames;
1140 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1141 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1142 for (auto [source, target] : binds) {
1143 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1144 LOG(INFO) << " " << path::join(root, source);
1145 }
1146
1147 // Ensure it's a kind of a mount that's managed by IncrementalService
1148 if (path::basename(root) != constants().mount ||
1149 path::basename(backingDir) != constants().backing) {
1150 return;
1151 }
1152 const auto expectedRoot = path::dirname(root);
1153 if (path::dirname(backingDir) != expectedRoot) {
1154 return;
1155 }
1156 if (path::dirname(expectedRoot) != mIncrementalDir) {
1157 return;
1158 }
1159 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1160 return;
1161 }
1162
1163 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1164
1165 // make sure we clean up the mount if it happens to be a bad one.
1166 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1167 auto cleanupFiles = makeCleanup([&]() {
1168 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1169 IncFsMount::cleanupFilesystem(expectedRoot);
1170 });
1171 auto cleanupMounts = makeCleanup([&]() {
1172 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1173 for (auto&& [_, target] : binds) {
1174 mVold->unmountIncFs(std::string(target));
1175 }
1176 mVold->unmountIncFs(std::string(root));
1177 });
1178
1179 auto control = mIncFs->openMount(root);
1180 if (!control) {
1181 LOG(INFO) << "failed to open mount " << root;
1182 return;
1183 }
1184
1185 auto mountRecord =
1186 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1187 path::join(root, constants().infoMdName));
1188 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1189 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1190 return;
1191 }
1192
1193 auto mountId = mountRecord.storage().id();
1194 mNextId = std::max(mNextId, mountId + 1);
1195
1196 DataLoaderParamsParcel dataLoaderParams;
1197 {
1198 const auto& loader = mountRecord.loader();
1199 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1200 dataLoaderParams.packageName = loader.package_name();
1201 dataLoaderParams.className = loader.class_name();
1202 dataLoaderParams.arguments = loader.arguments();
1203 }
1204
1205 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1206 std::move(control), *this);
1207 cleanupFiles.release(); // ifs will take care of that now
1208
Alex Buynytskyy04035452020-06-06 20:15:58 -07001209 // Check if marker file present.
1210 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001211 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001212 }
1213
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001214 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1215 auto d = openDir(root);
1216 while (auto e = ::readdir(d.get())) {
1217 if (e->d_type == DT_REG) {
1218 auto name = std::string_view(e->d_name);
1219 if (name.starts_with(constants().mountpointMdPrefix)) {
1220 permanentBindPoints
1221 .emplace_back(name,
1222 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1223 ifs->control,
1224 path::join(root,
1225 name)));
1226 if (permanentBindPoints.back().second.dest_path().empty() ||
1227 permanentBindPoints.back().second.source_subdir().empty()) {
1228 permanentBindPoints.pop_back();
1229 mIncFs->unlink(ifs->control, path::join(root, name));
1230 } else {
1231 LOG(INFO) << "Permanent bind record: '"
1232 << permanentBindPoints.back().second.source_subdir() << "'->'"
1233 << permanentBindPoints.back().second.dest_path() << "'";
1234 }
1235 }
1236 } else if (e->d_type == DT_DIR) {
1237 if (e->d_name == "."sv || e->d_name == ".."sv) {
1238 continue;
1239 }
1240 auto name = std::string_view(e->d_name);
1241 if (name.starts_with(constants().storagePrefix)) {
1242 int storageId;
1243 const auto res =
1244 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1245 name.data() + name.size(), storageId);
1246 if (res.ec != std::errc{} || *res.ptr != '_') {
1247 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1248 << "' for mount " << expectedRoot;
1249 continue;
1250 }
1251 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1252 if (!inserted) {
1253 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1254 << " for mount " << expectedRoot;
1255 continue;
1256 }
1257 ifs->storages.insert_or_assign(storageId,
1258 IncFsMount::Storage{path::join(root, name)});
1259 mNextId = std::max(mNextId, storageId + 1);
1260 }
1261 }
1262 }
1263
1264 if (ifs->storages.empty()) {
1265 LOG(WARNING) << "No valid storages in mount " << root;
1266 return;
1267 }
1268
1269 // now match the mounted directories with what we expect to have in the metadata
1270 {
1271 std::unique_lock l(mLock, std::defer_lock);
1272 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1273 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1274 [&, bindRecord = bindRecord](auto&& bind) {
1275 return bind.second == bindRecord.dest_path() &&
1276 path::join(root, bind.first) ==
1277 bindRecord.source_subdir();
1278 });
1279 if (mountedIt != binds.end()) {
1280 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1281 << " to mount " << mountedIt->first;
1282 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1283 std::move(*bindRecord.mutable_source_subdir()),
1284 std::move(*bindRecord.mutable_dest_path()),
1285 BindKind::Permanent);
1286 if (mountedIt != binds.end() - 1) {
1287 std::iter_swap(mountedIt, binds.end() - 1);
1288 }
1289 binds = binds.first(binds.size() - 1);
1290 } else {
1291 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1292 << ", mounting";
1293 // doesn't exist - try mounting back
1294 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1295 std::move(*bindRecord.mutable_source_subdir()),
1296 std::move(*bindRecord.mutable_dest_path()),
1297 BindKind::Permanent, l)) {
1298 mIncFs->unlink(ifs->control, metadataFile);
1299 }
1300 }
1301 }
1302 }
1303
1304 // if anything stays in |binds| those are probably temporary binds; system restarted since
1305 // they were mounted - so let's unmount them all.
1306 for (auto&& [source, target] : binds) {
1307 if (source.empty()) {
1308 continue;
1309 }
1310 mVold->unmountIncFs(std::string(target));
1311 }
1312 cleanupMounts.release(); // ifs now manages everything
1313
1314 if (ifs->bindPoints.empty()) {
1315 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1316 deleteStorage(*ifs);
1317 return;
1318 }
1319
1320 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1321 CHECK(ifs->dataLoaderStub);
1322
1323 mountedRootNames.insert(path::basename(ifs->root));
1324
1325 // not locking here at all: we're still in the constructor, no other calls can happen
1326 mMounts[ifs->mountId] = std::move(ifs);
1327 });
1328
1329 return mountedRootNames;
1330}
1331
1332void IncrementalService::mountExistingImages(
1333 const std::unordered_set<std::string_view>& mountedRootNames) {
1334 auto dir = openDir(mIncrementalDir);
1335 if (!dir) {
1336 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1337 return;
1338 }
1339 while (auto entry = ::readdir(dir.get())) {
1340 if (entry->d_type != DT_DIR) {
1341 continue;
1342 }
1343 std::string_view name = entry->d_name;
1344 if (!name.starts_with(constants().mountKeyPrefix)) {
1345 continue;
1346 }
1347 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001348 continue;
1349 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001350 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001351 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001352 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001353 }
1354 }
1355}
1356
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001357bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001358 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001359 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001360
Songchun Fan3c82a302019-11-29 14:23:45 -08001361 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001362 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001363 if (!status.isOk()) {
1364 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1365 return false;
1366 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001367
1368 int cmd = controlParcel.cmd.release().release();
1369 int pendingReads = controlParcel.pendingReads.release().release();
1370 int logs = controlParcel.log.release().release();
1371 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001372
1373 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1374
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001375 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1376 path::join(mountTarget, constants().infoMdName));
1377 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001378 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1379 return false;
1380 }
1381
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001382 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001383 mNextId = std::max(mNextId, ifs->mountId + 1);
1384
Alex Buynytskyy04035452020-06-06 20:15:58 -07001385 // Check if marker file present.
1386 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001387 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001388 }
1389
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001390 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001391 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001392 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001393 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001394 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001395 dataLoaderParams.packageName = loader.package_name();
1396 dataLoaderParams.className = loader.class_name();
1397 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001398 }
1399
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001400 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001401 CHECK(ifs->dataLoaderStub);
1402
Songchun Fan3c82a302019-11-29 14:23:45 -08001403 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001404 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001405 while (auto e = ::readdir(d.get())) {
1406 if (e->d_type == DT_REG) {
1407 auto name = std::string_view(e->d_name);
1408 if (name.starts_with(constants().mountpointMdPrefix)) {
1409 bindPoints.emplace_back(name,
1410 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1411 ifs->control,
1412 path::join(mountTarget,
1413 name)));
1414 if (bindPoints.back().second.dest_path().empty() ||
1415 bindPoints.back().second.source_subdir().empty()) {
1416 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001417 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001418 }
1419 }
1420 } else if (e->d_type == DT_DIR) {
1421 if (e->d_name == "."sv || e->d_name == ".."sv) {
1422 continue;
1423 }
1424 auto name = std::string_view(e->d_name);
1425 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001426 int storageId;
1427 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1428 name.data() + name.size(), storageId);
1429 if (res.ec != std::errc{} || *res.ptr != '_') {
1430 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1431 << root;
1432 continue;
1433 }
1434 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001435 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001436 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001437 << " for mount " << root;
1438 continue;
1439 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001440 ifs->storages.insert_or_assign(storageId,
1441 IncFsMount::Storage{
1442 path::join(root, constants().mount, name)});
1443 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001444 }
1445 }
1446 }
1447
1448 if (ifs->storages.empty()) {
1449 LOG(WARNING) << "No valid storages in mount " << root;
1450 return false;
1451 }
1452
1453 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001454 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001455 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001456 for (auto&& bp : bindPoints) {
1457 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1458 std::move(*bp.second.mutable_source_subdir()),
1459 std::move(*bp.second.mutable_dest_path()),
1460 BindKind::Permanent, l);
1461 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001462 }
1463
1464 if (bindCount == 0) {
1465 LOG(WARNING) << "No valid bind points for mount " << root;
1466 deleteStorage(*ifs);
1467 return false;
1468 }
1469
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001470 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001471 mMounts[ifs->mountId] = std::move(ifs);
1472 return true;
1473}
1474
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001475void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001476 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001477 while (mRunning.load(std::memory_order_relaxed)) {
1478 mLooper->pollAll(kTimeoutMsecs);
1479 }
1480}
1481
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001482IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001483 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001484 const DataLoaderStatusListener* statusListener,
1485 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001486 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001487 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1488 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001489 return ifs.dataLoaderStub;
1490}
1491
1492void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001493 const DataLoaderStatusListener* statusListener,
1494 StorageHealthCheckParams&& healthCheckParams,
1495 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001496 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001497 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001498 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001499 }
1500
Songchun Fan3c82a302019-11-29 14:23:45 -08001501 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001502 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001503 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1504 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1505 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001506 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001507
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001508 ifs.dataLoaderStub =
1509 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001510 statusListener, std::move(healthCheckParams), healthListener,
1511 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001512}
1513
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001514template <class Duration>
1515static long elapsedMcs(Duration start, Duration end) {
1516 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1517}
1518
1519// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001520// Lib files should be placed next to the APK file in the following matter:
1521// Example:
1522// /path/to/base.apk
1523// /path/to/lib/arm/first.so
1524// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001525bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1526 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001527 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001528 auto start = Clock::now();
1529
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001530 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001531 if (!ifs) {
1532 LOG(ERROR) << "Invalid storage " << storage;
1533 return false;
1534 }
1535
Songchun Fanc8975312020-07-13 12:14:37 -07001536 const auto targetLibPathRelativeToStorage =
1537 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1538 libDirRelativePath);
1539
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001540 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001541 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1542 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001543 << " errno: " << res;
1544 return false;
1545 }
1546
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001547 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001548 ZipArchiveHandle zipFileHandle;
1549 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001550 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1551 return false;
1552 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001553
1554 // Need a shared pointer: will be passing it into all unpacking jobs.
1555 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001556 void* cookie = nullptr;
Songchun Fan2ff2a482020-09-29 11:45:18 -07001557 const auto libFilePrefix = path::join(constants().libDir, abi) + "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001558 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001559 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1560 return false;
1561 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001562 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001563 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1564
1565 auto openZipTs = Clock::now();
1566
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001567 std::vector<Job> jobQueue;
1568 ZipEntry entry;
1569 std::string_view fileName;
1570 while (!Next(cookie, &entry, &fileName)) {
1571 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001572 continue;
1573 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001574
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001575 if (!extractNativeLibs) {
1576 // ensure the file is properly aligned and unpacked
1577 if (entry.method != kCompressStored) {
1578 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1579 return false;
1580 }
1581 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1582 LOG(WARNING) << "Library " << fileName
1583 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1584 << entry.offset;
1585 return false;
1586 }
1587 continue;
1588 }
1589
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001590 auto startFileTs = Clock::now();
1591
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001592 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001593 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001594 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001595 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001596 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001597 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001598 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1599 << "; skipping extraction, spent "
1600 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1601 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001602 continue;
1603 }
1604
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001605 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001606 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001607 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001608 .signature = {},
1609 // Metadata of the new lib file is its relative path
1610 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1611 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001612 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001613 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1614 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001615 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001616 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001617 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001618 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001619
1620 auto makeFileTs = Clock::now();
1621
Songchun Fanafaf6e92020-03-18 14:12:20 -07001622 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001623 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001624 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001625 LOG(INFO) << "incfs: Extracted " << libName
1626 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001627 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001628 continue;
1629 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001630
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001631 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1632 libFileId, libPath = std::move(targetLibPath),
1633 makeFileTs]() mutable {
1634 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001635 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001636
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001637 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001638 auto prepareJobTs = Clock::now();
1639 LOG(INFO) << "incfs: Processed " << libName << ": "
1640 << elapsedMcs(startFileTs, prepareJobTs)
1641 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1642 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001643 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001644 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001645
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001646 auto processedTs = Clock::now();
1647
1648 if (!jobQueue.empty()) {
1649 {
1650 std::lock_guard lock(mJobMutex);
1651 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001652 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001653 if (existingJobs.empty()) {
1654 existingJobs = std::move(jobQueue);
1655 } else {
1656 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1657 std::move_iterator(jobQueue.end()));
1658 }
1659 }
1660 }
1661 mJobCondition.notify_all();
1662 }
1663
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001664 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001665 auto end = Clock::now();
1666 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1667 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1668 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001669 << " make files: " << elapsedMcs(openZipTs, processedTs)
1670 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001671 }
1672
1673 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001674}
1675
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001676void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1677 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001678 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001679 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001680 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001681 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001682 return;
1683 }
1684
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001685 auto startedTs = Clock::now();
1686
1687 // Write extracted data to new file
1688 // NOTE: don't zero-initialize memory, it may take a while for nothing
1689 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1690 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001691 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001692 return;
1693 }
1694
1695 auto extractFileTs = Clock::now();
1696
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001697 if (setFileContent(ifs, libFileId, debugLibPath,
1698 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001699 return;
1700 }
1701
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001702 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001703 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001704 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1705 << entry.compressed_length << " -> " << entry.uncompressed_length
1706 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001707 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1708 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001709 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001710 }
1711}
1712
1713bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001714 struct WaitPrinter {
1715 const Clock::time_point startTs = Clock::now();
1716 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001717 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001718 const auto endTs = Clock::now();
1719 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1720 << elapsedMcs(startTs, endTs) << "mcs";
1721 }
1722 }
1723 } waitPrinter;
1724
1725 MountId mount;
1726 {
1727 auto ifs = getIfs(storage);
1728 if (!ifs) {
1729 return true;
1730 }
1731 mount = ifs->mountId;
1732 }
1733
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001734 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001735 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001736 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001737 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001738 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001739 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001740}
1741
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001742int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1743 std::string_view debugFilePath,
1744 std::span<const uint8_t> data) const {
1745 auto startTs = Clock::now();
1746
1747 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1748 if (!writeFd.ok()) {
1749 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1750 << " errno: " << writeFd.get();
1751 return writeFd.get();
1752 }
1753
1754 const auto dataLength = data.size();
1755
1756 auto openFileTs = Clock::now();
1757 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1758 std::vector<IncFsDataBlock> instructions(numBlocks);
1759 for (int i = 0; i < numBlocks; i++) {
1760 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1761 instructions[i] = IncFsDataBlock{
1762 .fileFd = writeFd.get(),
1763 .pageIndex = static_cast<IncFsBlockIndex>(i),
1764 .compression = INCFS_COMPRESSION_KIND_NONE,
1765 .kind = INCFS_BLOCK_KIND_DATA,
1766 .dataSize = static_cast<uint32_t>(blockSize),
1767 .data = reinterpret_cast<const char*>(data.data()),
1768 };
1769 data = data.subspan(blockSize);
1770 }
1771 auto prepareInstsTs = Clock::now();
1772
1773 size_t res = mIncFs->writeBlocks(instructions);
1774 if (res != instructions.size()) {
1775 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1776 return res;
1777 }
1778
1779 if (perfLoggingEnabled()) {
1780 auto endTs = Clock::now();
1781 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1782 << " bytes): " << elapsedMcs(startTs, endTs)
1783 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1784 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1785 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1786 }
1787
1788 return 0;
1789}
1790
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001791int IncrementalService::isFileFullyLoaded(StorageId storage, std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001792 std::unique_lock l(mLock);
1793 const auto ifs = getIfsLocked(storage);
1794 if (!ifs) {
1795 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1796 return -EINVAL;
1797 }
1798 const auto storageInfo = ifs->storages.find(storage);
1799 if (storageInfo == ifs->storages.end()) {
1800 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1801 return -EINVAL;
1802 }
1803 l.unlock();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001804 return isFileFullyLoadedFromPath(*ifs, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001805}
1806
1807int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1808 std::string_view filePath) const {
1809 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1810 if (filledBlocks < 0) {
1811 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1812 << filePath << " errno: " << filledBlocks;
1813 return filledBlocks;
1814 }
1815 if (totalBlocks < filledBlocks) {
1816 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1817 return -EINVAL;
1818 }
1819 return totalBlocks - filledBlocks;
1820}
1821
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001822IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
1823 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07001824 std::unique_lock l(mLock);
1825 const auto ifs = getIfsLocked(storage);
1826 if (!ifs) {
1827 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001828 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001829 }
1830 const auto storageInfo = ifs->storages.find(storage);
1831 if (storageInfo == ifs->storages.end()) {
1832 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001833 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001834 }
1835 l.unlock();
1836 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
1837}
1838
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001839IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
1840 const IncFsMount& ifs, std::string_view storagePath) const {
1841 ssize_t totalBlocks = 0, filledBlocks = 0;
Songchun Fan374f7652020-08-20 08:40:29 -07001842 const auto filePaths = mFs->listFilesRecursive(storagePath);
1843 for (const auto& filePath : filePaths) {
1844 const auto [filledBlocksCount, totalBlocksCount] =
1845 mIncFs->countFilledBlocks(ifs.control, filePath);
1846 if (filledBlocksCount < 0) {
1847 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1848 << " errno: " << filledBlocksCount;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001849 return {filledBlocksCount, filledBlocksCount};
Songchun Fan374f7652020-08-20 08:40:29 -07001850 }
1851 totalBlocks += totalBlocksCount;
1852 filledBlocks += filledBlocksCount;
1853 }
1854
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001855 return {filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07001856}
1857
Songchun Fana7098592020-09-03 11:45:53 -07001858bool IncrementalService::updateLoadingProgress(
1859 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1860 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001861 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07001862 // Failed to get progress from incfs, abort.
1863 return false;
1864 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001865 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
1866 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07001867 // Stop updating progress once it is fully loaded
1868 return true;
1869 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001870 addTimedJob(*mProgressUpdateJobQueue, storage,
1871 Constants::progressUpdateInterval /* repeat after 1s */,
Songchun Fana7098592020-09-03 11:45:53 -07001872 [storage, progressListener, this]() {
1873 updateLoadingProgress(storage, progressListener);
1874 });
1875 return true;
1876}
1877
1878bool IncrementalService::registerLoadingProgressListener(
1879 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1880 return updateLoadingProgress(storage, progressListener);
1881}
1882
1883bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
1884 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
1885}
1886
Songchun Fan2570ec02020-10-08 17:22:33 -07001887bool IncrementalService::registerStorageHealthListener(
1888 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
1889 const StorageHealthListener& healthListener) {
1890 DataLoaderStubPtr dataLoaderStub;
1891 {
1892 std::unique_lock l(mLock);
1893 const auto& ifs = getIfsLocked(storage);
1894 if (!ifs) {
1895 return false;
1896 }
1897 dataLoaderStub = ifs->dataLoaderStub;
1898 if (!dataLoaderStub) {
1899 return false;
1900 }
1901 }
1902 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
1903 return true;
1904}
1905
1906void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
1907 StorageHealthCheckParams invalidCheckParams;
1908 invalidCheckParams.blockedTimeoutMs = -1;
1909 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
1910}
1911
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001912bool IncrementalService::perfLoggingEnabled() {
1913 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1914 return enabled;
1915}
1916
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001917void IncrementalService::runJobProcessing() {
1918 for (;;) {
1919 std::unique_lock lock(mJobMutex);
1920 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1921 if (!mRunning) {
1922 return;
1923 }
1924
1925 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001926 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001927 auto queue = std::move(it->second);
1928 mJobQueue.erase(it);
1929 lock.unlock();
1930
1931 for (auto&& job : queue) {
1932 job();
1933 }
1934
1935 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001936 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001937 lock.unlock();
1938 mJobCondition.notify_all();
1939 }
1940}
1941
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001942void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001943 sp<IAppOpsCallback> listener;
1944 {
1945 std::unique_lock lock{mCallbacksLock};
1946 auto& cb = mCallbackRegistered[packageName];
1947 if (cb) {
1948 return;
1949 }
1950 cb = new AppOpsListener(*this, packageName);
1951 listener = cb;
1952 }
1953
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001954 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1955 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001956}
1957
1958bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1959 sp<IAppOpsCallback> listener;
1960 {
1961 std::unique_lock lock{mCallbacksLock};
1962 auto found = mCallbackRegistered.find(packageName);
1963 if (found == mCallbackRegistered.end()) {
1964 return false;
1965 }
1966 listener = found->second;
1967 mCallbackRegistered.erase(found);
1968 }
1969
1970 mAppOpsManager->stopWatchingMode(listener);
1971 return true;
1972}
1973
1974void IncrementalService::onAppOpChanged(const std::string& packageName) {
1975 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001976 return;
1977 }
1978
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001979 std::vector<IfsMountPtr> affected;
1980 {
1981 std::lock_guard l(mLock);
1982 affected.reserve(mMounts.size());
1983 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001984 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001985 affected.push_back(ifs);
1986 }
1987 }
1988 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001989 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001990 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001991 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001992}
1993
Songchun Fana7098592020-09-03 11:45:53 -07001994bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
1995 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001996 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07001997 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001998 }
Songchun Fana7098592020-09-03 11:45:53 -07001999 timedQueue.addJob(id, after, std::move(what));
2000 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002001}
2002
Songchun Fana7098592020-09-03 11:45:53 -07002003bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002004 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002005 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002006 }
Songchun Fana7098592020-09-03 11:45:53 -07002007 timedQueue.removeJobs(id);
2008 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002009}
2010
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002011IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
2012 DataLoaderParamsParcel&& params,
2013 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002014 const DataLoaderStatusListener* statusListener,
2015 StorageHealthCheckParams&& healthCheckParams,
2016 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002017 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002018 : mService(service),
2019 mId(id),
2020 mParams(std::move(params)),
2021 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002022 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
2023 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002024 mHealthPath(std::move(healthPath)),
2025 mHealthCheckParams(std::move(healthCheckParams)) {
2026 if (mHealthListener) {
2027 if (!isHealthParamsValid()) {
2028 mHealthListener = {};
2029 }
2030 } else {
2031 // Disable advanced health check statuses.
2032 mHealthCheckParams.blockedTimeoutMs = -1;
2033 }
2034 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002035}
2036
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002037IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002038 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002039 cleanupResources();
2040 }
2041}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002042
2043void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002044 auto now = Clock::now();
2045 {
2046 std::unique_lock lock(mMutex);
2047 mHealthPath.clear();
2048 unregisterFromPendingReads();
2049 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002050 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002051 }
2052
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002053 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002054
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002055 {
2056 std::unique_lock lock(mMutex);
2057 mParams = {};
2058 mControl = {};
2059 mHealthControl = {};
2060 mHealthListener = {};
2061 mStatusCondition.wait_until(lock, now + 60s, [this] {
2062 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2063 });
2064 mStatusListener = {};
2065 mId = kInvalidStorageId;
2066 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002067}
2068
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002069sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2070 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002071 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002072 if (!status.isOk()) {
2073 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2074 return {};
2075 }
2076 if (!dataloader) {
2077 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2078 return {};
2079 }
2080 return dataloader;
2081}
2082
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002083bool IncrementalService::DataLoaderStub::requestCreate() {
2084 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2085}
2086
2087bool IncrementalService::DataLoaderStub::requestStart() {
2088 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2089}
2090
2091bool IncrementalService::DataLoaderStub::requestDestroy() {
2092 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2093}
2094
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002095bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002096 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002097 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002098 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002099 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002100 return fsmStep();
2101}
2102
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002103void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002104 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002105 mTargetStatus = status;
2106 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002107 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002108 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002109}
2110
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002111bool IncrementalService::DataLoaderStub::bind() {
2112 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002113 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002114 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002115 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002116 return false;
2117 }
2118 return true;
2119}
2120
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002121bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002122 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002123 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002124 return false;
2125 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002126 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002127 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002128 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002129 return false;
2130 }
2131 return true;
2132}
2133
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002134bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002135 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002136 if (!dataloader) {
2137 return false;
2138 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002139 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002140 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002141 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002142 return false;
2143 }
2144 return true;
2145}
2146
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002147bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002148 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002149}
2150
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002151bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002152 if (!isValid()) {
2153 return false;
2154 }
2155
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002156 int currentStatus;
2157 int targetStatus;
2158 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002159 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002160 currentStatus = mCurrentStatus;
2161 targetStatus = mTargetStatus;
2162 }
2163
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002164 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002165
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002166 if (currentStatus == targetStatus) {
2167 return true;
2168 }
2169
2170 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002171 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2172 // Do nothing, this is a reset state.
2173 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002174 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
2175 return destroy();
2176 }
2177 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2178 switch (currentStatus) {
2179 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2180 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2181 return start();
2182 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002183 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002184 }
2185 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2186 switch (currentStatus) {
2187 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002188 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002189 return bind();
2190 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002191 return create();
2192 }
2193 break;
2194 default:
2195 LOG(ERROR) << "Invalid target status: " << targetStatus
2196 << ", current status: " << currentStatus;
2197 break;
2198 }
2199 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002200}
2201
2202binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002203 if (!isValid()) {
2204 return binder::Status::
2205 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2206 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002207 if (id() != mountId) {
2208 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002209 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2210 }
2211
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002212 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002213 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002214 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002215 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002216 if (mCurrentStatus == newStatus) {
2217 return binder::Status::ok();
2218 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002219
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002220 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002221 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002222 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002223
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002224 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002225
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002226 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002227 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2228 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002229 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002230 }
2231
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002232 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002233 << newStatus << " (target " << targetStatus << ")";
2234
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002235 if (listener) {
2236 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002237 }
2238
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002239 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002240
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002241 mStatusCondition.notify_all();
2242
Songchun Fan3c82a302019-11-29 14:23:45 -08002243 return binder::Status::ok();
2244}
2245
Songchun Fan33093982020-09-10 13:12:39 -07002246binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2247 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002248 if (!isValid()) {
2249 return binder::Status::
2250 fromServiceSpecificError(-EINVAL,
2251 "reportStreamHealth came to invalid DataLoaderStub");
2252 }
2253 if (id() != mountId) {
2254 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
2255 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2256 }
2257 {
2258 std::lock_guard lock(mMutex);
2259 mStreamStatus = newStatus;
2260 }
Songchun Fan33093982020-09-10 13:12:39 -07002261 return binder::Status::ok();
2262}
2263
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002264bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2265 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2266 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002267}
2268
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002269void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2270 int healthStatus) {
2271 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2272 if (healthListener) {
2273 healthListener->onHealthStatus(id(), healthStatus);
2274 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002275}
2276
Songchun Fan2570ec02020-10-08 17:22:33 -07002277static int adjustHealthStatus(int healthStatus, int streamStatus) {
2278 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2279 // everything is good; no need to change status
2280 return healthStatus;
2281 }
2282 int newHeathStatus = healthStatus;
2283 switch (streamStatus) {
2284 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2285 // storage is limited and storage not healthy
2286 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2287 break;
2288 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2289 // fall through
2290 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2291 // fall through
2292 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2293 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2294 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2295 }
2296 // pending/blocked status due to transportation issues is not regarded as unhealthy
2297 break;
2298 default:
2299 break;
2300 }
2301 return newHeathStatus;
2302}
2303
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002304void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2305 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002306
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002307 int healthStatusToReport = -1;
2308 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002309
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002310 {
2311 std::unique_lock lock(mMutex);
2312 unregisterFromPendingReads();
2313
2314 healthListener = mHealthListener;
2315
2316 // Healthcheck depends on timestamp of the oldest pending read.
2317 // To get it, we need to re-open a pendingReads FD to get a full list of reads.
Songchun Fan374f7652020-08-20 08:40:29 -07002318 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2319 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002320 const auto now = Clock::now();
2321 const auto kernelTsUs = getOldestPendingReadTs();
2322 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002323 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2324 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002325 mHealthBase = {now, kernelTsUs};
2326 }
2327
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002328 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2329 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002330 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2331 registerForPendingReads();
2332 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2333 lock.unlock();
2334 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002335 return;
2336 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002337
2338 resetHealthControl();
2339
2340 // Always make sure the data loader is started.
2341 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2342
2343 // Skip any further processing if health check params are invalid.
2344 if (!isHealthParamsValid()) {
2345 LOG(DEBUG) << id()
2346 << ": Skip any further processing if health check params are invalid.";
2347 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2348 lock.unlock();
2349 onHealthStatus(healthListener, healthStatusToReport);
2350 // Triggering data loader start. This is a one-time action.
2351 fsmStep();
2352 return;
2353 }
2354
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002355 // Don't schedule timer job less than 500ms in advance.
2356 static constexpr auto kTolerance = 500ms;
2357
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002358 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2359 const auto unhealthyTimeout =
2360 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2361 const auto unhealthyMonitoring =
2362 std::max(1000ms,
2363 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2364
2365 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2366 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002367 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002368
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002369 Milliseconds checkBackAfter;
2370 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002371 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002372 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002373 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002374 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002375 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002376 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002377 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2378 } else {
2379 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002380 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002381 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2382 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002383 // Adjust health status based on stream status
2384 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002385 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002386 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002387 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2388 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002389 }
2390
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002391 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002392 if (healthStatusToReport != -1) {
2393 onHealthStatus(healthListener, healthStatusToReport);
2394 }
2395
2396 fsmStep();
2397}
2398
2399const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2400 if (mHealthPath.empty()) {
2401 resetHealthControl();
2402 return mHealthControl;
2403 }
2404 if (mHealthControl.pendingReads() < 0) {
2405 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2406 }
2407 if (mHealthControl.pendingReads() < 0) {
2408 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2409 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2410 << mHealthControl.logs() << ")";
2411 }
2412 return mHealthControl;
2413}
2414
2415void IncrementalService::DataLoaderStub::resetHealthControl() {
2416 mHealthControl = {};
2417}
2418
2419BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2420 auto result = kMaxBootClockTsUs;
2421
2422 const auto& control = initializeHealthControl();
2423 if (control.pendingReads() < 0) {
2424 return result;
2425 }
2426
Songchun Fan6944f1e2020-11-06 15:24:24 -08002427 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002428 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002429 mLastPendingReads.empty()) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002430 return result;
2431 }
2432
2433 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002434 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002435
Songchun Fan6944f1e2020-11-06 15:24:24 -08002436 for (auto&& pendingRead : mLastPendingReads) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002437 result = std::min(result, pendingRead.bootClockTsUs);
2438 }
2439 return result;
2440}
2441
2442void IncrementalService::DataLoaderStub::registerForPendingReads() {
2443 const auto pendingReadsFd = mHealthControl.pendingReads();
2444 if (pendingReadsFd < 0) {
2445 return;
2446 }
2447
2448 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2449
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002450 mService.mLooper->addFd(
2451 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2452 [](int, int, void* data) -> int {
2453 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002454 self->updateHealthStatus(/*baseline=*/true);
2455 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002456 },
2457 this);
2458 mService.mLooper->wake();
2459}
2460
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002461void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002462 const auto pendingReadsFd = mHealthControl.pendingReads();
2463 if (pendingReadsFd < 0) {
2464 return;
2465 }
2466
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002467 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2468
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002469 mService.mLooper->removeFd(pendingReadsFd);
2470 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002471}
2472
Songchun Fan2570ec02020-10-08 17:22:33 -07002473void IncrementalService::DataLoaderStub::setHealthListener(
2474 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2475 std::lock_guard lock(mMutex);
2476 mHealthCheckParams = std::move(healthCheckParams);
2477 if (healthListener == nullptr) {
2478 // reset listener and params
2479 mHealthListener = {};
2480 } else {
2481 mHealthListener = *healthListener;
2482 }
2483}
2484
Songchun Fan6944f1e2020-11-06 15:24:24 -08002485static std::string toHexString(const RawMetadata& metadata) {
2486 int n = metadata.size();
2487 std::string res(n * 2, '\0');
2488 // Same as incfs::toString(fileId)
2489 static constexpr char kHexChar[] = "0123456789abcdef";
2490 for (int i = 0; i < n; ++i) {
2491 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2492 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2493 }
2494 return res;
2495}
2496
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002497void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002498 dprintf(fd, " dataLoader: {\n");
2499 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2500 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2501 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002502 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002503 dprintf(fd, " health: {\n");
2504 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2505 dprintf(fd, " base: %lldmcs (%lld)\n",
2506 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2507 (long long)mHealthBase.kernelTsUs);
2508 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2509 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2510 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2511 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002512 dprintf(fd, " lastPendingReads: \n");
2513 const auto control = mService.mIncFs->openMount(mHealthPath);
2514 for (auto&& pendingRead : mLastPendingReads) {
2515 dprintf(fd, " fileId: %s\n", mService.mIncFs->toString(pendingRead.id).c_str());
2516 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2517 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2518 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2519 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2520 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002521 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002522 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002523 dprintf(fd, " dataLoaderParams: {\n");
2524 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2525 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2526 dprintf(fd, " className: %s\n", params.className.c_str());
2527 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2528 dprintf(fd, " }\n");
2529 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002530}
2531
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002532void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2533 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002534}
2535
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002536binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2537 bool enableReadLogs, int32_t* _aidl_return) {
2538 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2539 return binder::Status::ok();
2540}
2541
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002542FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2543 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2544}
2545
Songchun Fan3c82a302019-11-29 14:23:45 -08002546} // namespace android::incremental