blob: e3fbeddc3a5fdec49d4750c6a796fc2b0b3cf69d [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 Buynytskyy42d4ba42021-01-12 11:10:03 -080041constexpr const char* kLoaderUsageStats = "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
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -080044constexpr const char* kInteractAcrossUsers = "android.permission.INTERACT_ACROSS_USERS";
45
Songchun Fan3c82a302019-11-29 14:23:45 -080046namespace android::incremental {
47
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070048using content::pm::DataLoaderParamsParcel;
49using content::pm::FileSystemControlParcel;
50using content::pm::IDataLoader;
51
Songchun Fan3c82a302019-11-29 14:23:45 -080052namespace {
53
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070054using IncrementalFileSystemControlParcel = os::incremental::IncrementalFileSystemControlParcel;
Songchun Fan3c82a302019-11-29 14:23:45 -080055
56struct Constants {
57 static constexpr auto backing = "backing_store"sv;
58 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080059 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080060 static constexpr auto storagePrefix = "st"sv;
61 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
62 static constexpr auto infoMdName = ".info"sv;
Alex Buynytskyy04035452020-06-06 20:15:58 -070063 static constexpr auto readLogsDisabledMarkerName = ".readlogs_disabled"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080064 static constexpr auto libDir = "lib"sv;
65 static constexpr auto libSuffix = ".so"sv;
66 static constexpr auto blockSize = 4096;
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -070067 static constexpr auto systemPackage = "android"sv;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -080068
Alex Buynytskyy060c9d62021-02-18 20:55:17 -080069 static constexpr auto userStatusDelay = 100ms;
70
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -080071 static constexpr auto progressUpdateInterval = 1000ms;
72 static constexpr auto perUidTimeoutOffset = progressUpdateInterval * 2;
73 static constexpr auto minPerUidTimeout = progressUpdateInterval * 3;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080074
75 // If DL was up and not crashing for 10mins, we consider it healthy and reset all delays.
76 static constexpr auto healthyDataLoaderUptime = 10min;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -080077
78 // For healthy DLs, we'll retry every ~5secs for ~10min
79 static constexpr auto bindRetryInterval = 5s;
80 static constexpr auto bindGracePeriod = 10min;
81
82 static constexpr auto bindingTimeout = 1min;
83
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080084 // 10s, 100s (~2min), 1000s (~15min), 10000s (~3hrs)
85 static constexpr auto minBindDelay = 10s;
86 static constexpr auto maxBindDelay = 10000s;
87 static constexpr auto bindDelayMultiplier = 10;
88 static constexpr auto bindDelayJitterDivider = 10;
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -070089
90 // Max interval after system invoked the DL when readlog collection can be enabled.
91 static constexpr auto readLogsMaxInterval = 2h;
Songchun Fan3c82a302019-11-29 14:23:45 -080092};
93
94static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070095 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080096 return c;
97}
98
99template <base::LogSeverity level = base::ERROR>
100bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
101 auto cstr = path::c_str(name);
102 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800103 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800104 PLOG(level) << "Can't create directory '" << name << '\'';
105 return false;
106 }
107 struct stat st;
108 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
109 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
110 return false;
111 }
112 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800113 if (::chmod(cstr, mode)) {
114 PLOG(level) << "Changing permission failed for '" << name << '\'';
115 return false;
116 }
117
Songchun Fan3c82a302019-11-29 14:23:45 -0800118 return true;
119}
120
121static std::string toMountKey(std::string_view path) {
122 if (path.empty()) {
123 return "@none";
124 }
125 if (path == "/"sv) {
126 return "@root";
127 }
128 if (path::isAbsolute(path)) {
129 path.remove_prefix(1);
130 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700131 if (path.size() > 16) {
132 path = path.substr(0, 16);
133 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800134 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700135 std::replace_if(
136 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
137 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800138}
139
140static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
141 std::string_view path) {
142 auto mountKey = toMountKey(path);
143 const auto prefixSize = mountKey.size();
144 for (int counter = 0; counter < 1000;
145 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
146 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800147 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800148 return {mountKey, mountRoot};
149 }
150 }
151 return {};
152}
153
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700154template <class Map>
155typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
156 const auto nextIt = map.upper_bound(path);
157 if (nextIt == map.begin()) {
158 return map.end();
159 }
160 const auto suspectIt = std::prev(nextIt);
161 if (!path::startsWith(path, suspectIt->first)) {
162 return map.end();
163 }
164 return suspectIt;
165}
166
167static base::unique_fd dup(base::borrowed_fd fd) {
168 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
169 return base::unique_fd(res);
170}
171
Songchun Fan3c82a302019-11-29 14:23:45 -0800172template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700173static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800174 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800175 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800176 ProtoMessage message;
177 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
178}
179
180static bool isValidMountTarget(std::string_view path) {
181 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
182}
183
184std::string makeBindMdName() {
185 static constexpr auto uuidStringSize = 36;
186
187 uuid_t guid;
188 uuid_generate(guid);
189
190 std::string name;
191 const auto prefixSize = constants().mountpointMdPrefix.size();
192 name.reserve(prefixSize + uuidStringSize);
193
194 name = constants().mountpointMdPrefix;
195 name.resize(prefixSize + uuidStringSize);
196 uuid_unparse(guid, name.data() + prefixSize);
197
198 return name;
199}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700200
201static bool checkReadLogsDisabledMarker(std::string_view root) {
202 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
203 struct stat st;
204 return (::stat(markerPath, &st) == 0);
205}
206
Songchun Fan3c82a302019-11-29 14:23:45 -0800207} // namespace
208
209IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700210 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700211 dataLoaderStub->cleanupResources();
212 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700213 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700214 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800215 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
216 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700217 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800218 incrementalService.mVold->unmountIncFs(target);
219 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700220 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800221 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
222 cleanupFilesystem(root);
223}
224
225auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800226 std::string name;
227 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
228 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
229 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800230 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
231 constants().storagePrefix.data(), id, no);
232 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800233 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800234 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800235 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
236 } else if (err != EEXIST) {
237 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
238 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800239 }
240 }
241 nextStorageDirNo = 0;
242 return storages.end();
243}
244
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700245template <class Func>
246static auto makeCleanup(Func&& f) {
247 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700248 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700249 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
250}
251
252static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
253 return {::opendir(dir), ::closedir};
254}
255
256static auto openDir(std::string_view dir) {
257 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800258}
259
260static int rmDirContent(const char* path) {
261 auto dir = openDir(path);
262 if (!dir) {
263 return -EINVAL;
264 }
265 while (auto entry = ::readdir(dir.get())) {
266 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
267 continue;
268 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700269 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800270 if (entry->d_type == DT_DIR) {
271 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
272 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
273 return err;
274 }
275 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
276 PLOG(WARNING) << "Failed to rmdir " << fullPath;
277 return err;
278 }
279 } else {
280 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
281 PLOG(WARNING) << "Failed to delete " << fullPath;
282 return err;
283 }
284 }
285 }
286 return 0;
287}
288
Songchun Fan3c82a302019-11-29 14:23:45 -0800289void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800290 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800291 ::rmdir(path::join(root, constants().backing).c_str());
292 ::rmdir(path::join(root, constants().mount).c_str());
293 ::rmdir(path::c_str(root));
294}
295
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700296void IncrementalService::IncFsMount::setReadLogsEnabled(bool value) {
297 if (value) {
298 flags |= StorageFlags::ReadLogsEnabled;
299 } else {
300 flags &= ~StorageFlags::ReadLogsEnabled;
301 }
302}
303
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800304IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800305 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800306 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800307 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700308 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700309 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700310 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700311 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700312 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700313 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800314 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800315 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700316 CHECK(mVold) << "Vold service is unavailable";
317 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
318 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
319 CHECK(mJni) << "JNI is unavailable";
320 CHECK(mLooper) << "Looper is unavailable";
321 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700322 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700323 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800324 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700325
326 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700327 mJobProcessor = std::thread([this]() {
328 mJni->initializeForCurrentThread();
329 runJobProcessing();
330 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700331 mCmdLooperThread = std::thread([this]() {
332 mJni->initializeForCurrentThread();
333 runCmdLooper();
334 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700335
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700336 const auto mountedRootNames = adoptMountedInstances();
337 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800338}
339
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700340IncrementalService::~IncrementalService() {
341 {
342 std::lock_guard lock(mJobMutex);
343 mRunning = false;
344 }
345 mJobCondition.notify_all();
346 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700347 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700348 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700349 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700350 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700351 // Ensure that mounts are destroyed while the service is still valid.
352 mBindsByPath.clear();
353 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700354}
Songchun Fan3c82a302019-11-29 14:23:45 -0800355
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700356static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800357 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800358 case IncrementalService::BindKind::Temporary:
359 return "Temporary";
360 case IncrementalService::BindKind::Permanent:
361 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800362 }
363}
364
365void IncrementalService::onDump(int fd) {
366 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
367 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
368
369 std::unique_lock l(mLock);
370
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700371 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800372 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700373 const IncFsMount& mnt = *ifs;
374 dprintf(fd, " [%d]: {\n", id);
375 if (id != mnt.mountId) {
376 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
377 } else {
378 dprintf(fd, " mountId: %d\n", mnt.mountId);
379 dprintf(fd, " root: %s\n", mnt.root.c_str());
380 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
381 if (mnt.dataLoaderStub) {
382 mnt.dataLoaderStub->onDump(fd);
383 } else {
384 dprintf(fd, " dataLoader: null\n");
385 }
386 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
387 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700388 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800389 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str(),
390 /*stopOnFirstIncomplete=*/false)
391 .getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800392 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700393 }
394 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800395
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700396 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
397 for (auto&& [target, bind] : mnt.bindPoints) {
398 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
399 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
400 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
401 dprintf(fd, " kind: %s\n", toString(bind.kind));
402 }
403 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800404 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700405 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800406 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700407 dprintf(fd, "}\n");
408 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800409 for (auto&& [target, mountPairIt] : mBindsByPath) {
410 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700411 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
412 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
413 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
414 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800415 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700416 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800417}
418
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800419bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700420 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800421 return true;
422 }
423
424 // Check all permanent binds.
425 for (auto&& [_, bindPoint] : ifs.bindPoints) {
426 if (bindPoint.kind != BindKind::Permanent) {
427 continue;
428 }
429 const auto progress = getLoadingProgressFromPath(ifs, bindPoint.sourceDir,
430 /*stopOnFirstIncomplete=*/true);
431 if (!progress.isError() && !progress.fullyLoaded()) {
432 LOG(INFO) << "Non system mount: [" << bindPoint.sourceDir
433 << "], partial progress: " << progress.getProgress() * 100 << "%";
434 return true;
435 }
436 }
437
438 return false;
439}
440
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700441void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800442 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700443 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800444 }
445
446 std::vector<IfsMountPtr> mounts;
447 {
448 std::lock_guard l(mLock);
449 mounts.reserve(mMounts.size());
450 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800451 if (ifs->mountId != id) {
452 continue;
453 }
454
455 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800456 mounts.push_back(ifs);
457 }
458 }
459 }
460
Alex Buynytskyy69941662020-04-11 21:40:37 -0700461 if (mounts.empty()) {
462 return;
463 }
464
Songchun Fan3c82a302019-11-29 14:23:45 -0800465 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700466 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800467 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700468 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800469 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800470 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800471}
472
473auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
474 for (;;) {
475 if (mNextId == kMaxStorageId) {
476 mNextId = 0;
477 }
478 auto id = ++mNextId;
479 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
480 if (inserted) {
481 return it;
482 }
483 }
484}
485
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800486StorageId IncrementalService::createStorage(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800487 std::string_view mountPoint, const content::pm::DataLoaderParamsParcel& dataLoaderParams,
488 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800489 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
490 if (!path::isAbsolute(mountPoint)) {
491 LOG(ERROR) << "path is not absolute: " << mountPoint;
492 return kInvalidStorageId;
493 }
494
495 auto mountNorm = path::normalize(mountPoint);
496 {
497 const auto id = findStorageId(mountNorm);
498 if (id != kInvalidStorageId) {
499 if (options & CreateOptions::OpenExisting) {
500 LOG(INFO) << "Opened existing storage " << id;
501 return id;
502 }
503 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
504 return kInvalidStorageId;
505 }
506 }
507
508 if (!(options & CreateOptions::CreateNew)) {
509 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
510 return kInvalidStorageId;
511 }
512
513 if (!path::isEmptyDir(mountNorm)) {
514 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
515 return kInvalidStorageId;
516 }
517 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
518 if (mountRoot.empty()) {
519 LOG(ERROR) << "Bad mount point";
520 return kInvalidStorageId;
521 }
522 // Make sure the code removes all crap it may create while still failing.
523 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
524 auto firstCleanupOnFailure =
525 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
526
527 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800528 const auto backing = path::join(mountRoot, constants().backing);
529 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800530 return kInvalidStorageId;
531 }
532
Songchun Fan3c82a302019-11-29 14:23:45 -0800533 IncFsMount::Control control;
534 {
535 std::lock_guard l(mMountOperationLock);
536 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800537
538 if (auto err = rmDirContent(backing.c_str())) {
539 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
540 return kInvalidStorageId;
541 }
542 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
543 return kInvalidStorageId;
544 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800545 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
546 return kInvalidStorageId;
547 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800548 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800549 if (!status.isOk()) {
550 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
551 return kInvalidStorageId;
552 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800553 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
554 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800555 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
556 return kInvalidStorageId;
557 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800558 int cmd = controlParcel.cmd.release().release();
559 int pendingReads = controlParcel.pendingReads.release().release();
560 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800561 int blocksWritten =
562 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
563 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800564 }
565
566 std::unique_lock l(mLock);
567 const auto mountIt = getStorageSlotLocked();
568 const auto mountId = mountIt->first;
569 l.unlock();
570
571 auto ifs =
572 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
573 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
574 // is the removal of the |ifs|.
575 firstCleanupOnFailure.release();
576
577 auto secondCleanup = [this, &l](auto itPtr) {
578 if (!l.owns_lock()) {
579 l.lock();
580 }
581 mMounts.erase(*itPtr);
582 };
583 auto secondCleanupOnFailure =
584 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
585
586 const auto storageIt = ifs->makeStorage(ifs->mountId);
587 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800588 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800589 return kInvalidStorageId;
590 }
591
592 {
593 metadata::Mount m;
594 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700595 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800596 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
597 m.mutable_loader()->set_class_name(dataLoaderParams.className);
598 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800599 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800600 if (auto err =
601 mIncFs->makeFile(ifs->control,
602 path::join(ifs->root, constants().mount,
603 constants().infoMdName),
604 0777, idFromMetadata(metadata),
605 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800606 LOG(ERROR) << "Saving mount metadata failed: " << -err;
607 return kInvalidStorageId;
608 }
609 }
610
611 const auto bk =
612 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800613 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
614 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800615 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800616 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800617 return kInvalidStorageId;
618 }
619
620 // Done here as well, all data structures are in good state.
621 secondCleanupOnFailure.release();
622
Songchun Fan3c82a302019-11-29 14:23:45 -0800623 mountIt->second = std::move(ifs);
624 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700625
Songchun Fan3c82a302019-11-29 14:23:45 -0800626 LOG(INFO) << "created storage " << mountId;
627 return mountId;
628}
629
630StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
631 StorageId linkedStorage,
632 IncrementalService::CreateOptions options) {
633 if (!isValidMountTarget(mountPoint)) {
634 LOG(ERROR) << "Mount point is invalid or missing";
635 return kInvalidStorageId;
636 }
637
638 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700639 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800640 if (!ifs) {
641 LOG(ERROR) << "Ifs unavailable";
642 return kInvalidStorageId;
643 }
644
645 const auto mountIt = getStorageSlotLocked();
646 const auto storageId = mountIt->first;
647 const auto storageIt = ifs->makeStorage(storageId);
648 if (storageIt == ifs->storages.end()) {
649 LOG(ERROR) << "Can't create a new storage";
650 mMounts.erase(mountIt);
651 return kInvalidStorageId;
652 }
653
654 l.unlock();
655
656 const auto bk =
657 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800658 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
659 std::string(storageIt->second.name), path::normalize(mountPoint),
660 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800661 err < 0) {
662 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700663 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
664 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800665 return kInvalidStorageId;
666 }
667
668 mountIt->second = ifs;
669 return storageId;
670}
671
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700672bool IncrementalService::startLoading(StorageId storageId,
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800673 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
674 const DataLoaderStatusListener& statusListener,
675 StorageHealthCheckParams&& healthCheckParams,
676 const StorageHealthListener& healthListener,
677 const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
678 // Per Uid timeouts.
679 if (!perUidReadTimeouts.empty()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700680 setUidReadTimeouts(storageId, perUidReadTimeouts);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800681 }
682
683 // Re-initialize DataLoader.
684 std::unique_lock l(mLock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700685 const auto ifs = getIfsLocked(storageId);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800686 if (!ifs) {
687 return false;
688 }
689 if (ifs->dataLoaderStub) {
690 ifs->dataLoaderStub->cleanupResources();
691 ifs->dataLoaderStub = {};
692 }
693 l.unlock();
694
695 // DataLoader.
696 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
697 std::move(healthCheckParams), &healthListener);
698 CHECK(dataLoaderStub);
699
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700700 if (dataLoaderStub->isSystemDataLoader()) {
701 // Readlogs from system dataloader (adb) can always be collected.
702 ifs->startLoadingTs = TimePoint::max();
703 } else {
704 // Assign time when installation wants the DL to start streaming.
705 const auto startLoadingTs = mClock->now();
706 ifs->startLoadingTs = startLoadingTs;
707 // Setup a callback to disable the readlogs after max interval.
708 addTimedJob(*mTimedQueue, storageId, Constants::readLogsMaxInterval,
709 [this, storageId, startLoadingTs]() {
710 const auto ifs = getIfs(storageId);
711 if (!ifs) {
712 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
713 << storageId;
714 return;
715 }
716 if (ifs->startLoadingTs != startLoadingTs) {
717 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
718 "installation?): "
719 << storageId;
720 return;
721 }
722 setStorageParams(*ifs, storageId, /*enableReadLogs=*/false);
723 });
724 }
725
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800726 return dataLoaderStub->requestStart();
727}
728
Songchun Fan3c82a302019-11-29 14:23:45 -0800729IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
730 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700731 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800732}
733
734StorageId IncrementalService::findStorageId(std::string_view path) const {
735 std::lock_guard l(mLock);
736 auto it = findStorageLocked(path);
737 if (it == mBindsByPath.end()) {
738 return kInvalidStorageId;
739 }
740 return it->second->second.storage;
741}
742
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800743void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700744 std::unique_lock l(mLock);
745 const auto ifs = getIfsLocked(storageId);
746 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800747 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700748 return;
749 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800750 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700751 return;
752 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800753 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700754 l.unlock();
755
756 const auto metadata = constants().readLogsDisabledMarkerName;
757 if (auto err = mIncFs->makeFile(ifs->control,
758 path::join(ifs->root, constants().mount,
759 constants().readLogsDisabledMarkerName),
760 0777, idFromMetadata(metadata), {})) {
761 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
762 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
763 return;
764 }
765
766 setStorageParams(storageId, /*enableReadLogs=*/false);
767}
768
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700769int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
770 const auto ifs = getIfs(storageId);
771 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700772 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700773 return -EINVAL;
774 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700775 return setStorageParams(*ifs, storageId, enableReadLogs);
776}
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700777
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700778int IncrementalService::setStorageParams(IncFsMount& ifs, StorageId storageId,
779 bool enableReadLogs) {
780 const auto& params = ifs.dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700781 if (enableReadLogs) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700782 if (!ifs.readLogsAllowed()) {
783 LOG(ERROR) << "setStorageParams failed, readlogs disallowed for storageId: "
784 << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700785 return -EPERM;
786 }
787
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800788 // Check loader usage stats permission and apop.
789 if (auto status = mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700790 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700791 !status.isOk()) {
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800792 LOG(ERROR) << " Permission: " << kLoaderUsageStats
793 << " check failed: " << status.toString8();
794 return fromBinderStatus(status);
795 }
796
797 // Check multiuser permission.
798 if (auto status = mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr,
799 params.packageName.c_str());
800 !status.isOk()) {
801 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
802 << " check failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700803 return fromBinderStatus(status);
804 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700805
806 // Check installation time.
807 const auto now = mClock->now();
808 const auto startLoadingTs = ifs.startLoadingTs;
809 if (startLoadingTs <= now && now - startLoadingTs > Constants::readLogsMaxInterval) {
810 LOG(ERROR) << "setStorageParams failed, readlogs can't be enabled at this time, "
811 "storageId: "
812 << storageId;
813 return -EPERM;
814 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700815 }
816
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700817 if (auto status = applyStorageParams(ifs, enableReadLogs); !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700818 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
819 return fromBinderStatus(status);
820 }
821
822 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700823 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700824 }
825
826 return 0;
827}
828
829binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700830 os::incremental::IncrementalFileSystemControlParcel control;
831 control.cmd.reset(dup(ifs.control.cmd()));
832 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700833 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700834 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700835 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700836 }
837
838 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800839 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
840 if (status.isOk()) {
841 // Store enabled state.
842 ifs.setReadLogsEnabled(enableReadLogs);
843 }
844 return status;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700845}
846
Songchun Fan3c82a302019-11-29 14:23:45 -0800847void IncrementalService::deleteStorage(StorageId storageId) {
848 const auto ifs = getIfs(storageId);
849 if (!ifs) {
850 return;
851 }
852 deleteStorage(*ifs);
853}
854
855void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
856 std::unique_lock l(ifs.lock);
857 deleteStorageLocked(ifs, std::move(l));
858}
859
860void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
861 std::unique_lock<std::mutex>&& ifsLock) {
862 const auto storages = std::move(ifs.storages);
863 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
864 const auto bindPoints = ifs.bindPoints;
865 ifsLock.unlock();
866
867 std::lock_guard l(mLock);
868 for (auto&& [id, _] : storages) {
869 if (id != ifs.mountId) {
870 mMounts.erase(id);
871 }
872 }
873 for (auto&& [path, _] : bindPoints) {
874 mBindsByPath.erase(path);
875 }
876 mMounts.erase(ifs.mountId);
877}
878
879StorageId IncrementalService::openStorage(std::string_view pathInMount) {
880 if (!path::isAbsolute(pathInMount)) {
881 return kInvalidStorageId;
882 }
883
884 return findStorageId(path::normalize(pathInMount));
885}
886
Songchun Fan3c82a302019-11-29 14:23:45 -0800887IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
888 std::lock_guard l(mLock);
889 return getIfsLocked(storage);
890}
891
892const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
893 auto it = mMounts.find(storage);
894 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700895 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700896 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800897 }
898 return it->second;
899}
900
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800901int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
902 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800903 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700904 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800905 return -EINVAL;
906 }
907
908 const auto ifs = getIfs(storage);
909 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700910 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800911 return -EINVAL;
912 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800913
Songchun Fan3c82a302019-11-29 14:23:45 -0800914 std::unique_lock l(ifs->lock);
915 const auto storageInfo = ifs->storages.find(storage);
916 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700917 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800918 return -EINVAL;
919 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700920 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700921 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700922 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700923 return -EINVAL;
924 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800925 l.unlock();
926 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800927 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
928 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800929}
930
931int IncrementalService::unbind(StorageId storage, std::string_view target) {
932 if (!path::isAbsolute(target)) {
933 return -EINVAL;
934 }
935
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700936 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800937
938 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
939 // otherwise there's a chance to unmount something completely unrelated
940 const auto norm = path::normalize(target);
941 std::unique_lock l(mLock);
942 const auto storageIt = mBindsByPath.find(norm);
943 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
944 return -EINVAL;
945 }
946 const auto bindIt = storageIt->second;
947 const auto storageId = bindIt->second.storage;
948 const auto ifs = getIfsLocked(storageId);
949 if (!ifs) {
950 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
951 << " is missing";
952 return -EFAULT;
953 }
954 mBindsByPath.erase(storageIt);
955 l.unlock();
956
957 mVold->unmountIncFs(bindIt->first);
958 std::unique_lock l2(ifs->lock);
959 if (ifs->bindPoints.size() <= 1) {
960 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700961 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800962 } else {
963 const std::string savedFile = std::move(bindIt->second.savedFilename);
964 ifs->bindPoints.erase(bindIt);
965 l2.unlock();
966 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800967 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800968 }
969 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700970
Songchun Fan3c82a302019-11-29 14:23:45 -0800971 return 0;
972}
973
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700974std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700975 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700976 std::string_view path) const {
977 if (!path::isAbsolute(path)) {
978 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700979 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700980 auto normPath = path::normalize(path);
981 if (path::startsWith(normPath, storageIt->second.name)) {
982 return normPath;
983 }
984 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700985 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
986 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700987 return {};
988 }
989 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700990}
991
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700992std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700993 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700994 std::unique_lock l(ifs.lock);
995 const auto storageInfo = ifs.storages.find(storage);
996 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800997 return {};
998 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700999 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001000}
1001
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001002int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001003 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001004 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001005 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001006 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001007 LOG(ERROR) << "Internal error: storageId " << storage
1008 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -08001009 return -EINVAL;
1010 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001011 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -07001012 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001013 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -08001014 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001015 if (!data.empty()) {
1016 if (auto err = setFileContent(ifs, id, path, data); err) {
1017 return err;
1018 }
1019 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001020 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001021 }
1022 return -EINVAL;
1023}
1024
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001025int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001026 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001027 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001028 if (normPath.empty()) {
1029 return -EINVAL;
1030 }
1031 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001032 }
1033 return -EINVAL;
1034}
1035
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001036int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001037 const auto ifs = getIfs(storageId);
1038 if (!ifs) {
1039 return -EINVAL;
1040 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001041 return makeDirs(*ifs, storageId, path, mode);
1042}
1043
1044int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1045 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001046 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1047 if (normPath.empty()) {
1048 return -EINVAL;
1049 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001050 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001051}
1052
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001053int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1054 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001055 std::unique_lock l(mLock);
1056 auto ifsSrc = getIfsLocked(sourceStorageId);
1057 if (!ifsSrc) {
1058 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001059 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001060 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1061 return -EINVAL;
1062 }
1063 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001064 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1065 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001066 if (normOldPath.empty() || normNewPath.empty()) {
1067 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1068 return -EINVAL;
1069 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001070 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1071 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1072 << " to " << newPath << "[" << normNewPath << "]";
1073 return err;
1074 }
1075 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001076}
1077
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001078int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001079 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001080 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001081 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001082 }
1083 return -EINVAL;
1084}
1085
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001086int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1087 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001088 std::string&& target, BindKind kind,
1089 std::unique_lock<std::mutex>& mainLock) {
1090 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001091 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001092 return -EINVAL;
1093 }
1094
1095 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001096 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001097 if (kind != BindKind::Temporary) {
1098 metadata::BindPoint bp;
1099 bp.set_storage_id(storage);
1100 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001101 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001102 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001103 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001104 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001105 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001106 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1107 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1108 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001109 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001110 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001111 return int(node);
1112 }
1113 }
1114
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001115 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1116 std::move(target), kind, mainLock);
1117 if (res) {
1118 mIncFs->unlink(ifs.control, metadataFullPath);
1119 }
1120 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001121}
1122
1123int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001124 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001125 std::string&& target, BindKind kind,
1126 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001127 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001128 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001129 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001130 if (!status.isOk()) {
1131 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1132 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1133 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1134 : status.serviceSpecificErrorCode() == 0
1135 ? -EFAULT
1136 : status.serviceSpecificErrorCode()
1137 : -EIO;
1138 }
1139 }
1140
1141 if (!mainLock.owns_lock()) {
1142 mainLock.lock();
1143 }
1144 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001145 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1146 std::move(target), kind);
1147 return 0;
1148}
1149
1150void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1151 std::string&& metadataName, std::string&& source,
1152 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001153 const auto [it, _] =
1154 ifs.bindPoints.insert_or_assign(target,
1155 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001156 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001157 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001158}
1159
1160RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1161 const auto ifs = getIfs(storage);
1162 if (!ifs) {
1163 return {};
1164 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001165 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001166 if (normPath.empty()) {
1167 return {};
1168 }
1169 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001170}
1171
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001172RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001173 const auto ifs = getIfs(storage);
1174 if (!ifs) {
1175 return {};
1176 }
1177 return mIncFs->getMetadata(ifs->control, node);
1178}
1179
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001180void IncrementalService::setUidReadTimeouts(
1181 StorageId storage, const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
1182 using microseconds = std::chrono::microseconds;
1183 using milliseconds = std::chrono::milliseconds;
1184
1185 auto maxPendingTimeUs = microseconds(0);
1186 for (const auto& timeouts : perUidReadTimeouts) {
1187 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1188 }
1189 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001190 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001191 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1192 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001193 return;
1194 }
1195
1196 const auto ifs = getIfs(storage);
1197 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001198 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001199 return;
1200 }
1201
1202 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1203 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1204 return;
1205 }
1206
1207 const auto timeout = std::chrono::duration_cast<milliseconds>(maxPendingTimeUs) -
1208 Constants::perUidTimeoutOffset;
1209 updateUidReadTimeouts(storage, Clock::now() + timeout);
1210}
1211
1212void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1213 const auto ifs = getIfs(storage);
1214 if (!ifs) {
1215 return;
1216 }
1217
1218 mIncFs->setUidReadTimeouts(ifs->control, {});
1219}
1220
1221void IncrementalService::updateUidReadTimeouts(StorageId storage, Clock::time_point timeLimit) {
1222 // Reached maximum timeout.
1223 if (Clock::now() >= timeLimit) {
1224 return clearUidReadTimeouts(storage);
1225 }
1226
1227 // Still loading?
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001228 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/true);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001229 if (progress.isError()) {
1230 // Something is wrong, abort.
1231 return clearUidReadTimeouts(storage);
1232 }
1233
1234 if (progress.started() && progress.fullyLoaded()) {
1235 // Fully loaded, check readLogs collection.
1236 const auto ifs = getIfs(storage);
1237 if (!ifs->readLogsEnabled()) {
1238 return clearUidReadTimeouts(storage);
1239 }
1240 }
1241
1242 const auto timeLeft = timeLimit - Clock::now();
1243 if (timeLeft < Constants::progressUpdateInterval) {
1244 // Don't bother.
1245 return clearUidReadTimeouts(storage);
1246 }
1247
1248 addTimedJob(*mTimedQueue, storage, Constants::progressUpdateInterval,
1249 [this, storage, timeLimit]() { updateUidReadTimeouts(storage, timeLimit); });
1250}
1251
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001252std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1253 std::unordered_set<std::string_view> mountedRootNames;
1254 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1255 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1256 for (auto [source, target] : binds) {
1257 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1258 LOG(INFO) << " " << path::join(root, source);
1259 }
1260
1261 // Ensure it's a kind of a mount that's managed by IncrementalService
1262 if (path::basename(root) != constants().mount ||
1263 path::basename(backingDir) != constants().backing) {
1264 return;
1265 }
1266 const auto expectedRoot = path::dirname(root);
1267 if (path::dirname(backingDir) != expectedRoot) {
1268 return;
1269 }
1270 if (path::dirname(expectedRoot) != mIncrementalDir) {
1271 return;
1272 }
1273 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1274 return;
1275 }
1276
1277 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1278
1279 // make sure we clean up the mount if it happens to be a bad one.
1280 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1281 auto cleanupFiles = makeCleanup([&]() {
1282 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1283 IncFsMount::cleanupFilesystem(expectedRoot);
1284 });
1285 auto cleanupMounts = makeCleanup([&]() {
1286 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1287 for (auto&& [_, target] : binds) {
1288 mVold->unmountIncFs(std::string(target));
1289 }
1290 mVold->unmountIncFs(std::string(root));
1291 });
1292
1293 auto control = mIncFs->openMount(root);
1294 if (!control) {
1295 LOG(INFO) << "failed to open mount " << root;
1296 return;
1297 }
1298
1299 auto mountRecord =
1300 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1301 path::join(root, constants().infoMdName));
1302 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1303 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1304 return;
1305 }
1306
1307 auto mountId = mountRecord.storage().id();
1308 mNextId = std::max(mNextId, mountId + 1);
1309
1310 DataLoaderParamsParcel dataLoaderParams;
1311 {
1312 const auto& loader = mountRecord.loader();
1313 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1314 dataLoaderParams.packageName = loader.package_name();
1315 dataLoaderParams.className = loader.class_name();
1316 dataLoaderParams.arguments = loader.arguments();
1317 }
1318
1319 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1320 std::move(control), *this);
1321 cleanupFiles.release(); // ifs will take care of that now
1322
Alex Buynytskyy04035452020-06-06 20:15:58 -07001323 // Check if marker file present.
1324 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001325 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001326 }
1327
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001328 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1329 auto d = openDir(root);
1330 while (auto e = ::readdir(d.get())) {
1331 if (e->d_type == DT_REG) {
1332 auto name = std::string_view(e->d_name);
1333 if (name.starts_with(constants().mountpointMdPrefix)) {
1334 permanentBindPoints
1335 .emplace_back(name,
1336 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1337 ifs->control,
1338 path::join(root,
1339 name)));
1340 if (permanentBindPoints.back().second.dest_path().empty() ||
1341 permanentBindPoints.back().second.source_subdir().empty()) {
1342 permanentBindPoints.pop_back();
1343 mIncFs->unlink(ifs->control, path::join(root, name));
1344 } else {
1345 LOG(INFO) << "Permanent bind record: '"
1346 << permanentBindPoints.back().second.source_subdir() << "'->'"
1347 << permanentBindPoints.back().second.dest_path() << "'";
1348 }
1349 }
1350 } else if (e->d_type == DT_DIR) {
1351 if (e->d_name == "."sv || e->d_name == ".."sv) {
1352 continue;
1353 }
1354 auto name = std::string_view(e->d_name);
1355 if (name.starts_with(constants().storagePrefix)) {
1356 int storageId;
1357 const auto res =
1358 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1359 name.data() + name.size(), storageId);
1360 if (res.ec != std::errc{} || *res.ptr != '_') {
1361 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1362 << "' for mount " << expectedRoot;
1363 continue;
1364 }
1365 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1366 if (!inserted) {
1367 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1368 << " for mount " << expectedRoot;
1369 continue;
1370 }
1371 ifs->storages.insert_or_assign(storageId,
1372 IncFsMount::Storage{path::join(root, name)});
1373 mNextId = std::max(mNextId, storageId + 1);
1374 }
1375 }
1376 }
1377
1378 if (ifs->storages.empty()) {
1379 LOG(WARNING) << "No valid storages in mount " << root;
1380 return;
1381 }
1382
1383 // now match the mounted directories with what we expect to have in the metadata
1384 {
1385 std::unique_lock l(mLock, std::defer_lock);
1386 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1387 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1388 [&, bindRecord = bindRecord](auto&& bind) {
1389 return bind.second == bindRecord.dest_path() &&
1390 path::join(root, bind.first) ==
1391 bindRecord.source_subdir();
1392 });
1393 if (mountedIt != binds.end()) {
1394 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1395 << " to mount " << mountedIt->first;
1396 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1397 std::move(*bindRecord.mutable_source_subdir()),
1398 std::move(*bindRecord.mutable_dest_path()),
1399 BindKind::Permanent);
1400 if (mountedIt != binds.end() - 1) {
1401 std::iter_swap(mountedIt, binds.end() - 1);
1402 }
1403 binds = binds.first(binds.size() - 1);
1404 } else {
1405 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1406 << ", mounting";
1407 // doesn't exist - try mounting back
1408 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1409 std::move(*bindRecord.mutable_source_subdir()),
1410 std::move(*bindRecord.mutable_dest_path()),
1411 BindKind::Permanent, l)) {
1412 mIncFs->unlink(ifs->control, metadataFile);
1413 }
1414 }
1415 }
1416 }
1417
1418 // if anything stays in |binds| those are probably temporary binds; system restarted since
1419 // they were mounted - so let's unmount them all.
1420 for (auto&& [source, target] : binds) {
1421 if (source.empty()) {
1422 continue;
1423 }
1424 mVold->unmountIncFs(std::string(target));
1425 }
1426 cleanupMounts.release(); // ifs now manages everything
1427
1428 if (ifs->bindPoints.empty()) {
1429 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1430 deleteStorage(*ifs);
1431 return;
1432 }
1433
1434 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1435 CHECK(ifs->dataLoaderStub);
1436
1437 mountedRootNames.insert(path::basename(ifs->root));
1438
1439 // not locking here at all: we're still in the constructor, no other calls can happen
1440 mMounts[ifs->mountId] = std::move(ifs);
1441 });
1442
1443 return mountedRootNames;
1444}
1445
1446void IncrementalService::mountExistingImages(
1447 const std::unordered_set<std::string_view>& mountedRootNames) {
1448 auto dir = openDir(mIncrementalDir);
1449 if (!dir) {
1450 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1451 return;
1452 }
1453 while (auto entry = ::readdir(dir.get())) {
1454 if (entry->d_type != DT_DIR) {
1455 continue;
1456 }
1457 std::string_view name = entry->d_name;
1458 if (!name.starts_with(constants().mountKeyPrefix)) {
1459 continue;
1460 }
1461 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001462 continue;
1463 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001464 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001465 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001466 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001467 }
1468 }
1469}
1470
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001471bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001472 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001473 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001474
Songchun Fan3c82a302019-11-29 14:23:45 -08001475 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001476 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001477 if (!status.isOk()) {
1478 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1479 return false;
1480 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001481
1482 int cmd = controlParcel.cmd.release().release();
1483 int pendingReads = controlParcel.pendingReads.release().release();
1484 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001485 int blocksWritten =
1486 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1487 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001488
1489 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1490
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001491 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1492 path::join(mountTarget, constants().infoMdName));
1493 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001494 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1495 return false;
1496 }
1497
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001498 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001499 mNextId = std::max(mNextId, ifs->mountId + 1);
1500
Alex Buynytskyy04035452020-06-06 20:15:58 -07001501 // Check if marker file present.
1502 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001503 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001504 }
1505
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001506 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001507 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001508 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001509 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001510 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001511 dataLoaderParams.packageName = loader.package_name();
1512 dataLoaderParams.className = loader.class_name();
1513 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001514 }
1515
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001516 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001517 CHECK(ifs->dataLoaderStub);
1518
Songchun Fan3c82a302019-11-29 14:23:45 -08001519 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001520 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001521 while (auto e = ::readdir(d.get())) {
1522 if (e->d_type == DT_REG) {
1523 auto name = std::string_view(e->d_name);
1524 if (name.starts_with(constants().mountpointMdPrefix)) {
1525 bindPoints.emplace_back(name,
1526 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1527 ifs->control,
1528 path::join(mountTarget,
1529 name)));
1530 if (bindPoints.back().second.dest_path().empty() ||
1531 bindPoints.back().second.source_subdir().empty()) {
1532 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001533 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001534 }
1535 }
1536 } else if (e->d_type == DT_DIR) {
1537 if (e->d_name == "."sv || e->d_name == ".."sv) {
1538 continue;
1539 }
1540 auto name = std::string_view(e->d_name);
1541 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001542 int storageId;
1543 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1544 name.data() + name.size(), storageId);
1545 if (res.ec != std::errc{} || *res.ptr != '_') {
1546 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1547 << root;
1548 continue;
1549 }
1550 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001551 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001552 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001553 << " for mount " << root;
1554 continue;
1555 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001556 ifs->storages.insert_or_assign(storageId,
1557 IncFsMount::Storage{
1558 path::join(root, constants().mount, name)});
1559 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001560 }
1561 }
1562 }
1563
1564 if (ifs->storages.empty()) {
1565 LOG(WARNING) << "No valid storages in mount " << root;
1566 return false;
1567 }
1568
1569 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001570 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001571 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001572 for (auto&& bp : bindPoints) {
1573 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1574 std::move(*bp.second.mutable_source_subdir()),
1575 std::move(*bp.second.mutable_dest_path()),
1576 BindKind::Permanent, l);
1577 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001578 }
1579
1580 if (bindCount == 0) {
1581 LOG(WARNING) << "No valid bind points for mount " << root;
1582 deleteStorage(*ifs);
1583 return false;
1584 }
1585
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001586 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001587 mMounts[ifs->mountId] = std::move(ifs);
1588 return true;
1589}
1590
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001591void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001592 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001593 while (mRunning.load(std::memory_order_relaxed)) {
1594 mLooper->pollAll(kTimeoutMsecs);
1595 }
1596}
1597
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001598IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001599 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001600 const DataLoaderStatusListener* statusListener,
1601 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001602 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001603 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1604 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001605 return ifs.dataLoaderStub;
1606}
1607
1608void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001609 const DataLoaderStatusListener* statusListener,
1610 StorageHealthCheckParams&& healthCheckParams,
1611 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001612 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001613 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001614 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001615 }
1616
Songchun Fan3c82a302019-11-29 14:23:45 -08001617 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001618 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001619 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1620 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1621 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001622 if (ifs.control.blocksWritten() >= 0) {
1623 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1624 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001625 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001626
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001627 ifs.dataLoaderStub =
1628 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001629 statusListener, std::move(healthCheckParams), healthListener,
1630 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001631}
1632
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001633template <class Duration>
1634static long elapsedMcs(Duration start, Duration end) {
1635 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1636}
1637
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001638template <class Duration>
1639static constexpr auto castToMs(Duration d) {
1640 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1641}
1642
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001643// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001644// Lib files should be placed next to the APK file in the following matter:
1645// Example:
1646// /path/to/base.apk
1647// /path/to/lib/arm/first.so
1648// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001649bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1650 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001651 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001652 auto start = Clock::now();
1653
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001654 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001655 if (!ifs) {
1656 LOG(ERROR) << "Invalid storage " << storage;
1657 return false;
1658 }
1659
Songchun Fanc8975312020-07-13 12:14:37 -07001660 const auto targetLibPathRelativeToStorage =
1661 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1662 libDirRelativePath);
1663
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001664 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001665 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1666 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001667 << " errno: " << res;
1668 return false;
1669 }
1670
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001671 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001672 ZipArchiveHandle zipFileHandle;
1673 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001674 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1675 return false;
1676 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001677
1678 // Need a shared pointer: will be passing it into all unpacking jobs.
1679 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001680 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001681 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001682 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001683 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1684 return false;
1685 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001686 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001687 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1688
1689 auto openZipTs = Clock::now();
1690
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001691 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1692 incfs::FileId sourceId;
1693 if (mapFiles) {
1694 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1695 if (!incfs::isValidFileId(sourceId)) {
1696 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1697 << "', mapping disabled";
1698 mapFiles = false;
1699 }
1700 }
1701
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001702 std::vector<Job> jobQueue;
1703 ZipEntry entry;
1704 std::string_view fileName;
1705 while (!Next(cookie, &entry, &fileName)) {
1706 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001707 continue;
1708 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001709
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001710 const auto entryUncompressed = entry.method == kCompressStored;
1711 const auto entryPageAligned = (entry.offset & (constants().blockSize - 1)) == 0;
1712
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001713 if (!extractNativeLibs) {
1714 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001715 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001716 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1717 return false;
1718 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001719 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001720 LOG(WARNING) << "Library " << fileName
1721 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1722 << entry.offset;
1723 return false;
1724 }
1725 continue;
1726 }
1727
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001728 auto startFileTs = Clock::now();
1729
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001730 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001731 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001732 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001733 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001734 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001735 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001736 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1737 << "; skipping extraction, spent "
1738 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1739 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001740 continue;
1741 }
1742
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001743 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1744 incfs::NewMappedFileParams mappedFileParams = {
1745 .sourceId = sourceId,
1746 .sourceOffset = entry.offset,
1747 .size = entry.uncompressed_length,
1748 };
1749
1750 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1751 mappedFileParams);
1752 res == 0) {
1753 if (perfLoggingEnabled()) {
1754 auto doneTs = Clock::now();
1755 LOG(INFO) << "incfs: Mapped " << libName << ": "
1756 << elapsedMcs(startFileTs, doneTs) << "mcs";
1757 }
1758 continue;
1759 } else {
1760 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1761 << "; falling back to full extraction";
1762 }
1763 }
1764
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001765 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001766 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001767 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001768 .signature = {},
1769 // Metadata of the new lib file is its relative path
1770 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1771 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001772 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001773 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001774 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001775 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001776 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001777 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001778 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001779
1780 auto makeFileTs = Clock::now();
1781
Songchun Fanafaf6e92020-03-18 14:12:20 -07001782 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001783 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001784 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001785 LOG(INFO) << "incfs: Extracted " << libName
1786 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001787 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001788 continue;
1789 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001790
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001791 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1792 libFileId, libPath = std::move(targetLibPath),
1793 makeFileTs]() mutable {
1794 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001795 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001796
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001797 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001798 auto prepareJobTs = Clock::now();
1799 LOG(INFO) << "incfs: Processed " << libName << ": "
1800 << elapsedMcs(startFileTs, prepareJobTs)
1801 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1802 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001803 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001804 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001805
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001806 auto processedTs = Clock::now();
1807
1808 if (!jobQueue.empty()) {
1809 {
1810 std::lock_guard lock(mJobMutex);
1811 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001812 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001813 if (existingJobs.empty()) {
1814 existingJobs = std::move(jobQueue);
1815 } else {
1816 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1817 std::move_iterator(jobQueue.end()));
1818 }
1819 }
1820 }
1821 mJobCondition.notify_all();
1822 }
1823
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001824 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001825 auto end = Clock::now();
1826 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1827 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1828 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001829 << " make files: " << elapsedMcs(openZipTs, processedTs)
1830 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001831 }
1832
1833 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001834}
1835
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001836void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1837 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001838 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001839 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001840 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001841 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001842 return;
1843 }
1844
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001845 auto startedTs = Clock::now();
1846
1847 // Write extracted data to new file
1848 // NOTE: don't zero-initialize memory, it may take a while for nothing
1849 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1850 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001851 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001852 return;
1853 }
1854
1855 auto extractFileTs = Clock::now();
1856
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001857 if (setFileContent(ifs, libFileId, debugLibPath,
1858 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001859 return;
1860 }
1861
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001862 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001863 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001864 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1865 << entry.compressed_length << " -> " << entry.uncompressed_length
1866 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001867 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1868 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001869 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001870 }
1871}
1872
1873bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001874 struct WaitPrinter {
1875 const Clock::time_point startTs = Clock::now();
1876 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001877 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001878 const auto endTs = Clock::now();
1879 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1880 << elapsedMcs(startTs, endTs) << "mcs";
1881 }
1882 }
1883 } waitPrinter;
1884
1885 MountId mount;
1886 {
1887 auto ifs = getIfs(storage);
1888 if (!ifs) {
1889 return true;
1890 }
1891 mount = ifs->mountId;
1892 }
1893
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001894 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001895 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001896 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001897 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001898 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001899 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001900}
1901
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001902int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1903 std::string_view debugFilePath,
1904 std::span<const uint8_t> data) const {
1905 auto startTs = Clock::now();
1906
1907 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1908 if (!writeFd.ok()) {
1909 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1910 << " errno: " << writeFd.get();
1911 return writeFd.get();
1912 }
1913
1914 const auto dataLength = data.size();
1915
1916 auto openFileTs = Clock::now();
1917 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1918 std::vector<IncFsDataBlock> instructions(numBlocks);
1919 for (int i = 0; i < numBlocks; i++) {
1920 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1921 instructions[i] = IncFsDataBlock{
1922 .fileFd = writeFd.get(),
1923 .pageIndex = static_cast<IncFsBlockIndex>(i),
1924 .compression = INCFS_COMPRESSION_KIND_NONE,
1925 .kind = INCFS_BLOCK_KIND_DATA,
1926 .dataSize = static_cast<uint32_t>(blockSize),
1927 .data = reinterpret_cast<const char*>(data.data()),
1928 };
1929 data = data.subspan(blockSize);
1930 }
1931 auto prepareInstsTs = Clock::now();
1932
1933 size_t res = mIncFs->writeBlocks(instructions);
1934 if (res != instructions.size()) {
1935 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1936 return res;
1937 }
1938
1939 if (perfLoggingEnabled()) {
1940 auto endTs = Clock::now();
1941 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1942 << " bytes): " << elapsedMcs(startTs, endTs)
1943 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1944 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1945 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1946 }
1947
1948 return 0;
1949}
1950
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001951int IncrementalService::isFileFullyLoaded(StorageId storage, std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001952 std::unique_lock l(mLock);
1953 const auto ifs = getIfsLocked(storage);
1954 if (!ifs) {
1955 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1956 return -EINVAL;
1957 }
1958 const auto storageInfo = ifs->storages.find(storage);
1959 if (storageInfo == ifs->storages.end()) {
1960 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1961 return -EINVAL;
1962 }
1963 l.unlock();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001964 return isFileFullyLoadedFromPath(*ifs, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001965}
1966
1967int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1968 std::string_view filePath) const {
1969 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1970 if (filledBlocks < 0) {
1971 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1972 << filePath << " errno: " << filledBlocks;
1973 return filledBlocks;
1974 }
1975 if (totalBlocks < filledBlocks) {
1976 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1977 return -EINVAL;
1978 }
1979 return totalBlocks - filledBlocks;
1980}
1981
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001982IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001983 StorageId storage, bool stopOnFirstIncomplete) const {
Songchun Fan374f7652020-08-20 08:40:29 -07001984 std::unique_lock l(mLock);
1985 const auto ifs = getIfsLocked(storage);
1986 if (!ifs) {
1987 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001988 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001989 }
1990 const auto storageInfo = ifs->storages.find(storage);
1991 if (storageInfo == ifs->storages.end()) {
1992 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001993 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001994 }
1995 l.unlock();
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001996 return getLoadingProgressFromPath(*ifs, storageInfo->second.name, stopOnFirstIncomplete);
Songchun Fan374f7652020-08-20 08:40:29 -07001997}
1998
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001999IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002000 const IncFsMount& ifs, std::string_view storagePath,
2001 const bool stopOnFirstIncomplete) const {
2002 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2003 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002004 const auto [filledBlocksCount, totalBlocksCount] =
2005 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002006 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2007 filledBlocksCount == -ENOENT) {
2008 // a kind of a file that's not really being loaded, e.g. a mapped range
2009 // an older IncFS used to return ENOENT in this case, so handle it the same way
2010 return true;
2011 }
Songchun Fan374f7652020-08-20 08:40:29 -07002012 if (filledBlocksCount < 0) {
2013 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
2014 << " errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002015 error = filledBlocksCount;
2016 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002017 }
2018 totalBlocks += totalBlocksCount;
2019 filledBlocks += filledBlocksCount;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08002020 if (stopOnFirstIncomplete && filledBlocks < totalBlocks) {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002021 return false;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08002022 }
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002023 return true;
2024 });
Songchun Fan374f7652020-08-20 08:40:29 -07002025
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002026 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002027}
2028
Songchun Fana7098592020-09-03 11:45:53 -07002029bool IncrementalService::updateLoadingProgress(
2030 StorageId storage, const StorageLoadingProgressListener& progressListener) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08002031 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/false);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002032 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002033 // Failed to get progress from incfs, abort.
2034 return false;
2035 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002036 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2037 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002038 // Stop updating progress once it is fully loaded
2039 return true;
2040 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002041 addTimedJob(*mProgressUpdateJobQueue, storage,
2042 Constants::progressUpdateInterval /* repeat after 1s */,
Songchun Fana7098592020-09-03 11:45:53 -07002043 [storage, progressListener, this]() {
2044 updateLoadingProgress(storage, progressListener);
2045 });
2046 return true;
2047}
2048
2049bool IncrementalService::registerLoadingProgressListener(
2050 StorageId storage, const StorageLoadingProgressListener& progressListener) {
2051 return updateLoadingProgress(storage, progressListener);
2052}
2053
2054bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2055 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2056}
2057
Songchun Fan2570ec02020-10-08 17:22:33 -07002058bool IncrementalService::registerStorageHealthListener(
2059 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
2060 const StorageHealthListener& healthListener) {
2061 DataLoaderStubPtr dataLoaderStub;
2062 {
2063 std::unique_lock l(mLock);
2064 const auto& ifs = getIfsLocked(storage);
2065 if (!ifs) {
2066 return false;
2067 }
2068 dataLoaderStub = ifs->dataLoaderStub;
2069 if (!dataLoaderStub) {
2070 return false;
2071 }
2072 }
2073 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
2074 return true;
2075}
2076
2077void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
2078 StorageHealthCheckParams invalidCheckParams;
2079 invalidCheckParams.blockedTimeoutMs = -1;
2080 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
2081}
2082
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002083bool IncrementalService::perfLoggingEnabled() {
2084 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2085 return enabled;
2086}
2087
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002088void IncrementalService::runJobProcessing() {
2089 for (;;) {
2090 std::unique_lock lock(mJobMutex);
2091 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2092 if (!mRunning) {
2093 return;
2094 }
2095
2096 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002097 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002098 auto queue = std::move(it->second);
2099 mJobQueue.erase(it);
2100 lock.unlock();
2101
2102 for (auto&& job : queue) {
2103 job();
2104 }
2105
2106 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002107 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002108 lock.unlock();
2109 mJobCondition.notify_all();
2110 }
2111}
2112
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002113void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002114 sp<IAppOpsCallback> listener;
2115 {
2116 std::unique_lock lock{mCallbacksLock};
2117 auto& cb = mCallbackRegistered[packageName];
2118 if (cb) {
2119 return;
2120 }
2121 cb = new AppOpsListener(*this, packageName);
2122 listener = cb;
2123 }
2124
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002125 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2126 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002127}
2128
2129bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2130 sp<IAppOpsCallback> listener;
2131 {
2132 std::unique_lock lock{mCallbacksLock};
2133 auto found = mCallbackRegistered.find(packageName);
2134 if (found == mCallbackRegistered.end()) {
2135 return false;
2136 }
2137 listener = found->second;
2138 mCallbackRegistered.erase(found);
2139 }
2140
2141 mAppOpsManager->stopWatchingMode(listener);
2142 return true;
2143}
2144
2145void IncrementalService::onAppOpChanged(const std::string& packageName) {
2146 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002147 return;
2148 }
2149
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002150 std::vector<IfsMountPtr> affected;
2151 {
2152 std::lock_guard l(mLock);
2153 affected.reserve(mMounts.size());
2154 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002155 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002156 affected.push_back(ifs);
2157 }
2158 }
2159 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002160 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002161 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002162 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002163}
2164
Songchun Fana7098592020-09-03 11:45:53 -07002165bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2166 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002167 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002168 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002169 }
Songchun Fana7098592020-09-03 11:45:53 -07002170 timedQueue.addJob(id, after, std::move(what));
2171 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002172}
2173
Songchun Fana7098592020-09-03 11:45:53 -07002174bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002175 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002176 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002177 }
Songchun Fana7098592020-09-03 11:45:53 -07002178 timedQueue.removeJobs(id);
2179 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002180}
2181
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002182void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
2183 const auto duration = getMillsSinceOldestPendingRead(storageId);
2184 if (duration >= 0) {
2185 const auto kMetricsMillisSinceOldestPendingRead =
2186 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2187 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2188 }
2189}
2190
2191long IncrementalService::getMillsSinceOldestPendingRead(StorageId storageId) {
2192 std::unique_lock l(mLock);
2193 const auto ifs = getIfsLocked(storageId);
2194 if (!ifs) {
2195 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, invalid storageId: " << storageId;
2196 return -EINVAL;
2197 }
2198 if (!ifs->dataLoaderStub) {
2199 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, no data loader: " << storageId;
2200 return -EINVAL;
2201 }
2202 return ifs->dataLoaderStub->elapsedMsSinceOldestPendingRead();
2203}
2204
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002205IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
2206 DataLoaderParamsParcel&& params,
2207 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002208 const DataLoaderStatusListener* statusListener,
2209 StorageHealthCheckParams&& healthCheckParams,
2210 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002211 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002212 : mService(service),
2213 mId(id),
2214 mParams(std::move(params)),
2215 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002216 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
2217 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002218 mHealthPath(std::move(healthPath)),
2219 mHealthCheckParams(std::move(healthCheckParams)) {
2220 if (mHealthListener) {
2221 if (!isHealthParamsValid()) {
2222 mHealthListener = {};
2223 }
2224 } else {
2225 // Disable advanced health check statuses.
2226 mHealthCheckParams.blockedTimeoutMs = -1;
2227 }
2228 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002229}
2230
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002231IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002232 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002233 cleanupResources();
2234 }
2235}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002236
2237void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002238 auto now = Clock::now();
2239 {
2240 std::unique_lock lock(mMutex);
2241 mHealthPath.clear();
2242 unregisterFromPendingReads();
2243 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002244 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002245 }
2246
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002247 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002248
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002249 {
2250 std::unique_lock lock(mMutex);
2251 mParams = {};
2252 mControl = {};
2253 mHealthControl = {};
2254 mHealthListener = {};
2255 mStatusCondition.wait_until(lock, now + 60s, [this] {
2256 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2257 });
2258 mStatusListener = {};
2259 mId = kInvalidStorageId;
2260 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002261}
2262
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002263sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2264 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002265 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002266 if (!status.isOk()) {
2267 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2268 return {};
2269 }
2270 if (!dataloader) {
2271 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2272 return {};
2273 }
2274 return dataloader;
2275}
2276
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002277bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2278 return (params().packageName == Constants::systemPackage);
2279}
2280
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002281bool IncrementalService::DataLoaderStub::requestCreate() {
2282 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2283}
2284
2285bool IncrementalService::DataLoaderStub::requestStart() {
2286 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2287}
2288
2289bool IncrementalService::DataLoaderStub::requestDestroy() {
2290 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2291}
2292
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002293bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002294 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002295 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002296 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002297 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002298 return fsmStep();
2299}
2300
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002301void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002302 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002303 mTargetStatus = status;
2304 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002305 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002306 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002307}
2308
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002309std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002310 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002311
2312 const auto now = mService.mClock->now();
2313 const bool healthy = (mPreviousBindDelay == 0ms);
2314
2315 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2316 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2317 LOG(INFO) << "Binding still in progress. "
2318 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
2319 : "Already unhealthy, don't do anything.");
2320 // Binding still in progress.
2321 if (!healthy) {
2322 // Already unhealthy, don't do anything.
2323 return {};
2324 }
2325 // The DL is healthy/freshly bound, ok to retry for a few times.
2326 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2327 // Still within grace period.
2328 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2329 // Retry interval passed, retrying.
2330 mCurrentStatusTs = now;
2331 mPreviousBindDelay = 0ms;
2332 return 0ms;
2333 }
2334 return {};
2335 }
2336 // fallthrough, mark as unhealthy, and retry with delay
2337 }
2338
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002339 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002340 mPreviousBindTs = now;
2341
2342 const auto nonCrashingInterval = std::max(castToMs(now - previousBindTs), 100ms);
2343 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2344 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2345 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002346 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002347 }
2348
2349 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2350 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2351
2352 const auto bindDelayMs =
2353 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2354 maxBindDelayMs)
2355 .count();
2356 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2357 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2358 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002359 return mPreviousBindDelay;
2360}
2361
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002362bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002363 const auto maybeBindDelay = needToBind();
2364 if (!maybeBindDelay) {
2365 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2366 return true;
2367 }
2368 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002369 if (bindDelay > 1s) {
2370 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
2371 << bindDelay.count() / 1000 << "s";
2372 }
2373
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002374 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002375 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2376 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002377 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002378 const bool healthy = (bindDelay == 0ms);
2379 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2380 << (healthy ? ", retrying." : "");
2381
2382 // Internal error, retry for healthy/new DLs.
2383 // Let needToBind migrate it to unhealthy after too many retries.
2384 if (healthy) {
2385 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2386 [this]() { fsmStep(); })) {
2387 // Mark as binding so that we know it's not the DL's fault.
2388 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2389 return true;
2390 }
2391 }
2392
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002393 return false;
2394 }
2395 return true;
2396}
2397
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002398bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002399 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002400 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002401 return false;
2402 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002403 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002404 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002405 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002406 return false;
2407 }
2408 return true;
2409}
2410
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002411bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002412 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002413 if (!dataloader) {
2414 return false;
2415 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002416 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002417 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002418 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002419 return false;
2420 }
2421 return true;
2422}
2423
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002424bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002425 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002426}
2427
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002428bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002429 if (!isValid()) {
2430 return false;
2431 }
2432
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002433 int currentStatus;
2434 int targetStatus;
2435 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002436 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002437 currentStatus = mCurrentStatus;
2438 targetStatus = mTargetStatus;
2439 }
2440
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002441 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002442
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002443 if (currentStatus == targetStatus) {
2444 return true;
2445 }
2446
2447 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002448 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2449 // Do nothing, this is a reset state.
2450 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002451 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002452 switch (currentStatus) {
2453 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2454 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2455 return true;
2456 default:
2457 return destroy();
2458 }
2459 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002460 }
2461 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2462 switch (currentStatus) {
2463 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2464 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2465 return start();
2466 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002467 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002468 }
2469 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2470 switch (currentStatus) {
2471 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002472 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002473 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002474 return bind();
2475 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002476 return create();
2477 }
2478 break;
2479 default:
2480 LOG(ERROR) << "Invalid target status: " << targetStatus
2481 << ", current status: " << currentStatus;
2482 break;
2483 }
2484 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002485}
2486
2487binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002488 if (!isValid()) {
2489 return binder::Status::
2490 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2491 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002492 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002493 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2494 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002495 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2496 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002497 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2498 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2499 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2500 [this, newStatus]() { setCurrentStatus(newStatus); });
2501 return binder::Status::ok();
2502 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002503
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002504 setCurrentStatus(newStatus);
2505 return binder::Status::ok();
2506}
2507
2508void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002509 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002510 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002511 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002512 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002513 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002514 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002515 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002516
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002517 oldStatus = mCurrentStatus;
2518 targetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002519 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002520
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002521 // Change the status.
2522 mCurrentStatus = newStatus;
2523 mCurrentStatusTs = mService.mClock->now();
2524
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002525 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2526 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002527 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2528 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002529 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002530 }
2531
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002532 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002533 << newStatus << " (target " << targetStatus << ")";
2534
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002535 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002536 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002537 }
2538
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002539 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002540
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002541 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002542}
2543
Songchun Fan33093982020-09-10 13:12:39 -07002544binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2545 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002546 if (!isValid()) {
2547 return binder::Status::
2548 fromServiceSpecificError(-EINVAL,
2549 "reportStreamHealth came to invalid DataLoaderStub");
2550 }
2551 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002552 LOG(ERROR) << "reportStreamHealth: mount ID mismatch: expected " << id()
2553 << ", but got: " << mountId;
Songchun Fan2570ec02020-10-08 17:22:33 -07002554 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2555 }
2556 {
2557 std::lock_guard lock(mMutex);
2558 mStreamStatus = newStatus;
2559 }
Songchun Fan33093982020-09-10 13:12:39 -07002560 return binder::Status::ok();
2561}
2562
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002563bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2564 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2565 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002566}
2567
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002568void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2569 int healthStatus) {
2570 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2571 if (healthListener) {
2572 healthListener->onHealthStatus(id(), healthStatus);
2573 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002574}
2575
Songchun Fan2570ec02020-10-08 17:22:33 -07002576static int adjustHealthStatus(int healthStatus, int streamStatus) {
2577 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2578 // everything is good; no need to change status
2579 return healthStatus;
2580 }
2581 int newHeathStatus = healthStatus;
2582 switch (streamStatus) {
2583 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2584 // storage is limited and storage not healthy
2585 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2586 break;
2587 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2588 // fall through
2589 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2590 // fall through
2591 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2592 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2593 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2594 }
2595 // pending/blocked status due to transportation issues is not regarded as unhealthy
2596 break;
2597 default:
2598 break;
2599 }
2600 return newHeathStatus;
2601}
2602
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002603void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2604 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002605
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002606 int healthStatusToReport = -1;
2607 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002608
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002609 {
2610 std::unique_lock lock(mMutex);
2611 unregisterFromPendingReads();
2612
2613 healthListener = mHealthListener;
2614
2615 // Healthcheck depends on timestamp of the oldest pending read.
2616 // 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 -07002617 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2618 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002619 const auto now = Clock::now();
2620 const auto kernelTsUs = getOldestPendingReadTs();
2621 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002622 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2623 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002624 mHealthBase = {now, kernelTsUs};
2625 }
2626
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002627 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2628 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002629 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2630 registerForPendingReads();
2631 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2632 lock.unlock();
2633 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002634 return;
2635 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002636
2637 resetHealthControl();
2638
2639 // Always make sure the data loader is started.
2640 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2641
2642 // Skip any further processing if health check params are invalid.
2643 if (!isHealthParamsValid()) {
2644 LOG(DEBUG) << id()
2645 << ": Skip any further processing if health check params are invalid.";
2646 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2647 lock.unlock();
2648 onHealthStatus(healthListener, healthStatusToReport);
2649 // Triggering data loader start. This is a one-time action.
2650 fsmStep();
2651 return;
2652 }
2653
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002654 // Don't schedule timer job less than 500ms in advance.
2655 static constexpr auto kTolerance = 500ms;
2656
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002657 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2658 const auto unhealthyTimeout =
2659 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2660 const auto unhealthyMonitoring =
2661 std::max(1000ms,
2662 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2663
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002664 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002665
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002666 Milliseconds checkBackAfter;
2667 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002668 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002669 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002670 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002671 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002672 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002673 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002674 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2675 } else {
2676 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002677 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002678 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2679 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002680 // Adjust health status based on stream status
2681 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002682 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002683 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002684 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2685 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002686 }
2687
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002688 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002689 if (healthStatusToReport != -1) {
2690 onHealthStatus(healthListener, healthStatusToReport);
2691 }
2692
2693 fsmStep();
2694}
2695
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002696Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2697 BootClockTsUs kernelTsUs) {
2698 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2699 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2700 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2701}
2702
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002703const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2704 if (mHealthPath.empty()) {
2705 resetHealthControl();
2706 return mHealthControl;
2707 }
2708 if (mHealthControl.pendingReads() < 0) {
2709 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2710 }
2711 if (mHealthControl.pendingReads() < 0) {
2712 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2713 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2714 << mHealthControl.logs() << ")";
2715 }
2716 return mHealthControl;
2717}
2718
2719void IncrementalService::DataLoaderStub::resetHealthControl() {
2720 mHealthControl = {};
2721}
2722
2723BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2724 auto result = kMaxBootClockTsUs;
2725
2726 const auto& control = initializeHealthControl();
2727 if (control.pendingReads() < 0) {
2728 return result;
2729 }
2730
Songchun Fan6944f1e2020-11-06 15:24:24 -08002731 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002732 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002733 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002734 // Clear previous pending reads
2735 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002736 return result;
2737 }
2738
2739 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002740 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002741
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002742 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002743}
2744
2745void IncrementalService::DataLoaderStub::registerForPendingReads() {
2746 const auto pendingReadsFd = mHealthControl.pendingReads();
2747 if (pendingReadsFd < 0) {
2748 return;
2749 }
2750
2751 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2752
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002753 mService.mLooper->addFd(
2754 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2755 [](int, int, void* data) -> int {
2756 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002757 self->updateHealthStatus(/*baseline=*/true);
2758 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002759 },
2760 this);
2761 mService.mLooper->wake();
2762}
2763
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002764BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2765 auto result = kMaxBootClockTsUs;
2766 for (auto&& pendingRead : mLastPendingReads) {
2767 result = std::min(result, pendingRead.bootClockTsUs);
2768 }
2769 return result;
2770}
2771
2772long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
2773 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
2774 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
2775 return 0;
2776 }
2777 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
2778}
2779
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002780void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002781 const auto pendingReadsFd = mHealthControl.pendingReads();
2782 if (pendingReadsFd < 0) {
2783 return;
2784 }
2785
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002786 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2787
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002788 mService.mLooper->removeFd(pendingReadsFd);
2789 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002790}
2791
Songchun Fan2570ec02020-10-08 17:22:33 -07002792void IncrementalService::DataLoaderStub::setHealthListener(
2793 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2794 std::lock_guard lock(mMutex);
2795 mHealthCheckParams = std::move(healthCheckParams);
2796 if (healthListener == nullptr) {
2797 // reset listener and params
2798 mHealthListener = {};
2799 } else {
2800 mHealthListener = *healthListener;
2801 }
2802}
2803
Songchun Fan6944f1e2020-11-06 15:24:24 -08002804static std::string toHexString(const RawMetadata& metadata) {
2805 int n = metadata.size();
2806 std::string res(n * 2, '\0');
2807 // Same as incfs::toString(fileId)
2808 static constexpr char kHexChar[] = "0123456789abcdef";
2809 for (int i = 0; i < n; ++i) {
2810 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2811 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2812 }
2813 return res;
2814}
2815
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002816void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002817 dprintf(fd, " dataLoader: {\n");
2818 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002819 dprintf(fd, " currentStatusTs: %lldmcs\n",
2820 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002821 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2822 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002823 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002824 dprintf(fd, " health: {\n");
2825 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2826 dprintf(fd, " base: %lldmcs (%lld)\n",
2827 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2828 (long long)mHealthBase.kernelTsUs);
2829 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2830 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2831 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2832 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002833 dprintf(fd, " lastPendingReads: \n");
2834 const auto control = mService.mIncFs->openMount(mHealthPath);
2835 for (auto&& pendingRead : mLastPendingReads) {
2836 dprintf(fd, " fileId: %s\n", mService.mIncFs->toString(pendingRead.id).c_str());
2837 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2838 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2839 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2840 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2841 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002842 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
2843 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
2844 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002845 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002846 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002847 dprintf(fd, " dataLoaderParams: {\n");
2848 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2849 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2850 dprintf(fd, " className: %s\n", params.className.c_str());
2851 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2852 dprintf(fd, " }\n");
2853 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002854}
2855
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002856void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2857 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002858}
2859
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002860binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2861 bool enableReadLogs, int32_t* _aidl_return) {
2862 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2863 return binder::Status::ok();
2864}
2865
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002866FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2867 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2868}
2869
Songchun Fan3c82a302019-11-29 14:23:45 -08002870} // namespace android::incremental