blob: db70d44d37f64e56d091179de6215f6c9777e5fa [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
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -070099static bool isPageAligned(IncFsSize s) {
100 return (s & (Constants::blockSize - 1)) == 0;
101}
102
Songchun Fan3c82a302019-11-29 14:23:45 -0800103template <base::LogSeverity level = base::ERROR>
104bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
105 auto cstr = path::c_str(name);
106 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800107 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800108 PLOG(level) << "Can't create directory '" << name << '\'';
109 return false;
110 }
111 struct stat st;
112 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
113 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
114 return false;
115 }
116 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800117 if (::chmod(cstr, mode)) {
118 PLOG(level) << "Changing permission failed for '" << name << '\'';
119 return false;
120 }
121
Songchun Fan3c82a302019-11-29 14:23:45 -0800122 return true;
123}
124
125static std::string toMountKey(std::string_view path) {
126 if (path.empty()) {
127 return "@none";
128 }
129 if (path == "/"sv) {
130 return "@root";
131 }
132 if (path::isAbsolute(path)) {
133 path.remove_prefix(1);
134 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700135 if (path.size() > 16) {
136 path = path.substr(0, 16);
137 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800138 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700139 std::replace_if(
140 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
141 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800142}
143
144static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
145 std::string_view path) {
146 auto mountKey = toMountKey(path);
147 const auto prefixSize = mountKey.size();
148 for (int counter = 0; counter < 1000;
149 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
150 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800151 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800152 return {mountKey, mountRoot};
153 }
154 }
155 return {};
156}
157
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700158template <class Map>
159typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
160 const auto nextIt = map.upper_bound(path);
161 if (nextIt == map.begin()) {
162 return map.end();
163 }
164 const auto suspectIt = std::prev(nextIt);
165 if (!path::startsWith(path, suspectIt->first)) {
166 return map.end();
167 }
168 return suspectIt;
169}
170
171static base::unique_fd dup(base::borrowed_fd fd) {
172 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
173 return base::unique_fd(res);
174}
175
Songchun Fan3c82a302019-11-29 14:23:45 -0800176template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700177static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800178 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800179 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800180 ProtoMessage message;
181 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
182}
183
184static bool isValidMountTarget(std::string_view path) {
185 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
186}
187
188std::string makeBindMdName() {
189 static constexpr auto uuidStringSize = 36;
190
191 uuid_t guid;
192 uuid_generate(guid);
193
194 std::string name;
195 const auto prefixSize = constants().mountpointMdPrefix.size();
196 name.reserve(prefixSize + uuidStringSize);
197
198 name = constants().mountpointMdPrefix;
199 name.resize(prefixSize + uuidStringSize);
200 uuid_unparse(guid, name.data() + prefixSize);
201
202 return name;
203}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700204
205static bool checkReadLogsDisabledMarker(std::string_view root) {
206 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
207 struct stat st;
208 return (::stat(markerPath, &st) == 0);
209}
210
Songchun Fan3c82a302019-11-29 14:23:45 -0800211} // namespace
212
213IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700214 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700215 dataLoaderStub->cleanupResources();
216 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700217 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700218 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800219 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
220 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700221 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800222 incrementalService.mVold->unmountIncFs(target);
223 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700224 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800225 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
226 cleanupFilesystem(root);
227}
228
229auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800230 std::string name;
231 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
232 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
233 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800234 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
235 constants().storagePrefix.data(), id, no);
236 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800237 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800238 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800239 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
240 } else if (err != EEXIST) {
241 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
242 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800243 }
244 }
245 nextStorageDirNo = 0;
246 return storages.end();
247}
248
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700249template <class Func>
250static auto makeCleanup(Func&& f) {
251 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700252 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700253 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
254}
255
256static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
257 return {::opendir(dir), ::closedir};
258}
259
260static auto openDir(std::string_view dir) {
261 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800262}
263
264static int rmDirContent(const char* path) {
265 auto dir = openDir(path);
266 if (!dir) {
267 return -EINVAL;
268 }
269 while (auto entry = ::readdir(dir.get())) {
270 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
271 continue;
272 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700273 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800274 if (entry->d_type == DT_DIR) {
275 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
276 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
277 return err;
278 }
279 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
280 PLOG(WARNING) << "Failed to rmdir " << fullPath;
281 return err;
282 }
283 } else {
284 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
285 PLOG(WARNING) << "Failed to delete " << fullPath;
286 return err;
287 }
288 }
289 }
290 return 0;
291}
292
Songchun Fan3c82a302019-11-29 14:23:45 -0800293void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800294 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800295 ::rmdir(path::join(root, constants().backing).c_str());
296 ::rmdir(path::join(root, constants().mount).c_str());
297 ::rmdir(path::c_str(root));
298}
299
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700300void IncrementalService::IncFsMount::setReadLogsEnabled(bool value) {
301 if (value) {
302 flags |= StorageFlags::ReadLogsEnabled;
303 } else {
304 flags &= ~StorageFlags::ReadLogsEnabled;
305 }
306}
307
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800308IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800309 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800310 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800311 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700312 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700313 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700314 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700315 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700316 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700317 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800318 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800319 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700320 CHECK(mVold) << "Vold service is unavailable";
321 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
322 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
323 CHECK(mJni) << "JNI is unavailable";
324 CHECK(mLooper) << "Looper is unavailable";
325 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700326 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700327 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800328 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700329
330 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700331 mJobProcessor = std::thread([this]() {
332 mJni->initializeForCurrentThread();
333 runJobProcessing();
334 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700335 mCmdLooperThread = std::thread([this]() {
336 mJni->initializeForCurrentThread();
337 runCmdLooper();
338 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700339
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700340 const auto mountedRootNames = adoptMountedInstances();
341 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800342}
343
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700344IncrementalService::~IncrementalService() {
345 {
346 std::lock_guard lock(mJobMutex);
347 mRunning = false;
348 }
349 mJobCondition.notify_all();
350 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700351 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700352 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700353 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700354 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700355 // Ensure that mounts are destroyed while the service is still valid.
356 mBindsByPath.clear();
357 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700358}
Songchun Fan3c82a302019-11-29 14:23:45 -0800359
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700360static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800361 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800362 case IncrementalService::BindKind::Temporary:
363 return "Temporary";
364 case IncrementalService::BindKind::Permanent:
365 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800366 }
367}
368
369void IncrementalService::onDump(int fd) {
370 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
371 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
372
373 std::unique_lock l(mLock);
374
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700375 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800376 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700377 const IncFsMount& mnt = *ifs;
378 dprintf(fd, " [%d]: {\n", id);
379 if (id != mnt.mountId) {
380 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
381 } else {
382 dprintf(fd, " mountId: %d\n", mnt.mountId);
383 dprintf(fd, " root: %s\n", mnt.root.c_str());
384 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
385 if (mnt.dataLoaderStub) {
386 mnt.dataLoaderStub->onDump(fd);
387 } else {
388 dprintf(fd, " dataLoader: null\n");
389 }
390 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
391 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700392 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800393 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str(),
394 /*stopOnFirstIncomplete=*/false)
395 .getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800396 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700397 }
398 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800399
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700400 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
401 for (auto&& [target, bind] : mnt.bindPoints) {
402 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
403 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
404 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
405 dprintf(fd, " kind: %s\n", toString(bind.kind));
406 }
407 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800408 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700409 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800410 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700411 dprintf(fd, "}\n");
412 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800413 for (auto&& [target, mountPairIt] : mBindsByPath) {
414 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700415 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
416 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
417 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
418 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800419 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700420 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800421}
422
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800423bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700424 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800425 return true;
426 }
427
428 // Check all permanent binds.
429 for (auto&& [_, bindPoint] : ifs.bindPoints) {
430 if (bindPoint.kind != BindKind::Permanent) {
431 continue;
432 }
433 const auto progress = getLoadingProgressFromPath(ifs, bindPoint.sourceDir,
434 /*stopOnFirstIncomplete=*/true);
435 if (!progress.isError() && !progress.fullyLoaded()) {
436 LOG(INFO) << "Non system mount: [" << bindPoint.sourceDir
437 << "], partial progress: " << progress.getProgress() * 100 << "%";
438 return true;
439 }
440 }
441
442 return false;
443}
444
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700445void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800446 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700447 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800448 }
449
450 std::vector<IfsMountPtr> mounts;
451 {
452 std::lock_guard l(mLock);
453 mounts.reserve(mMounts.size());
454 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800455 if (ifs->mountId != id) {
456 continue;
457 }
458
459 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800460 mounts.push_back(ifs);
461 }
462 }
463 }
464
Alex Buynytskyy69941662020-04-11 21:40:37 -0700465 if (mounts.empty()) {
466 return;
467 }
468
Songchun Fan3c82a302019-11-29 14:23:45 -0800469 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700470 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800471 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700472 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800473 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800474 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800475}
476
477auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
478 for (;;) {
479 if (mNextId == kMaxStorageId) {
480 mNextId = 0;
481 }
482 auto id = ++mNextId;
483 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
484 if (inserted) {
485 return it;
486 }
487 }
488}
489
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800490StorageId IncrementalService::createStorage(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800491 std::string_view mountPoint, const content::pm::DataLoaderParamsParcel& dataLoaderParams,
492 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800493 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
494 if (!path::isAbsolute(mountPoint)) {
495 LOG(ERROR) << "path is not absolute: " << mountPoint;
496 return kInvalidStorageId;
497 }
498
499 auto mountNorm = path::normalize(mountPoint);
500 {
501 const auto id = findStorageId(mountNorm);
502 if (id != kInvalidStorageId) {
503 if (options & CreateOptions::OpenExisting) {
504 LOG(INFO) << "Opened existing storage " << id;
505 return id;
506 }
507 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
508 return kInvalidStorageId;
509 }
510 }
511
512 if (!(options & CreateOptions::CreateNew)) {
513 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
514 return kInvalidStorageId;
515 }
516
517 if (!path::isEmptyDir(mountNorm)) {
518 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
519 return kInvalidStorageId;
520 }
521 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
522 if (mountRoot.empty()) {
523 LOG(ERROR) << "Bad mount point";
524 return kInvalidStorageId;
525 }
526 // Make sure the code removes all crap it may create while still failing.
527 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
528 auto firstCleanupOnFailure =
529 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
530
531 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800532 const auto backing = path::join(mountRoot, constants().backing);
533 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800534 return kInvalidStorageId;
535 }
536
Songchun Fan3c82a302019-11-29 14:23:45 -0800537 IncFsMount::Control control;
538 {
539 std::lock_guard l(mMountOperationLock);
540 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800541
542 if (auto err = rmDirContent(backing.c_str())) {
543 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
544 return kInvalidStorageId;
545 }
546 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
547 return kInvalidStorageId;
548 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800549 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
550 return kInvalidStorageId;
551 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800552 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800553 if (!status.isOk()) {
554 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
555 return kInvalidStorageId;
556 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800557 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
558 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800559 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
560 return kInvalidStorageId;
561 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800562 int cmd = controlParcel.cmd.release().release();
563 int pendingReads = controlParcel.pendingReads.release().release();
564 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800565 int blocksWritten =
566 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
567 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800568 }
569
570 std::unique_lock l(mLock);
571 const auto mountIt = getStorageSlotLocked();
572 const auto mountId = mountIt->first;
573 l.unlock();
574
575 auto ifs =
576 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
577 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
578 // is the removal of the |ifs|.
579 firstCleanupOnFailure.release();
580
581 auto secondCleanup = [this, &l](auto itPtr) {
582 if (!l.owns_lock()) {
583 l.lock();
584 }
585 mMounts.erase(*itPtr);
586 };
587 auto secondCleanupOnFailure =
588 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
589
590 const auto storageIt = ifs->makeStorage(ifs->mountId);
591 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800592 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800593 return kInvalidStorageId;
594 }
595
596 {
597 metadata::Mount m;
598 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700599 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800600 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
601 m.mutable_loader()->set_class_name(dataLoaderParams.className);
602 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800603 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800604 if (auto err =
605 mIncFs->makeFile(ifs->control,
606 path::join(ifs->root, constants().mount,
607 constants().infoMdName),
608 0777, idFromMetadata(metadata),
609 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800610 LOG(ERROR) << "Saving mount metadata failed: " << -err;
611 return kInvalidStorageId;
612 }
613 }
614
615 const auto bk =
616 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800617 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
618 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800619 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800620 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800621 return kInvalidStorageId;
622 }
623
624 // Done here as well, all data structures are in good state.
625 secondCleanupOnFailure.release();
626
Songchun Fan3c82a302019-11-29 14:23:45 -0800627 mountIt->second = std::move(ifs);
628 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700629
Songchun Fan3c82a302019-11-29 14:23:45 -0800630 LOG(INFO) << "created storage " << mountId;
631 return mountId;
632}
633
634StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
635 StorageId linkedStorage,
636 IncrementalService::CreateOptions options) {
637 if (!isValidMountTarget(mountPoint)) {
638 LOG(ERROR) << "Mount point is invalid or missing";
639 return kInvalidStorageId;
640 }
641
642 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700643 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800644 if (!ifs) {
645 LOG(ERROR) << "Ifs unavailable";
646 return kInvalidStorageId;
647 }
648
649 const auto mountIt = getStorageSlotLocked();
650 const auto storageId = mountIt->first;
651 const auto storageIt = ifs->makeStorage(storageId);
652 if (storageIt == ifs->storages.end()) {
653 LOG(ERROR) << "Can't create a new storage";
654 mMounts.erase(mountIt);
655 return kInvalidStorageId;
656 }
657
658 l.unlock();
659
660 const auto bk =
661 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800662 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
663 std::string(storageIt->second.name), path::normalize(mountPoint),
664 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800665 err < 0) {
666 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700667 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
668 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800669 return kInvalidStorageId;
670 }
671
672 mountIt->second = ifs;
673 return storageId;
674}
675
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700676bool IncrementalService::startLoading(StorageId storageId,
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800677 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
678 const DataLoaderStatusListener& statusListener,
679 StorageHealthCheckParams&& healthCheckParams,
680 const StorageHealthListener& healthListener,
681 const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
682 // Per Uid timeouts.
683 if (!perUidReadTimeouts.empty()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700684 setUidReadTimeouts(storageId, perUidReadTimeouts);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800685 }
686
687 // Re-initialize DataLoader.
688 std::unique_lock l(mLock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700689 const auto ifs = getIfsLocked(storageId);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800690 if (!ifs) {
691 return false;
692 }
693 if (ifs->dataLoaderStub) {
694 ifs->dataLoaderStub->cleanupResources();
695 ifs->dataLoaderStub = {};
696 }
697 l.unlock();
698
699 // DataLoader.
700 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
701 std::move(healthCheckParams), &healthListener);
702 CHECK(dataLoaderStub);
703
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700704 if (dataLoaderStub->isSystemDataLoader()) {
705 // Readlogs from system dataloader (adb) can always be collected.
706 ifs->startLoadingTs = TimePoint::max();
707 } else {
708 // Assign time when installation wants the DL to start streaming.
709 const auto startLoadingTs = mClock->now();
710 ifs->startLoadingTs = startLoadingTs;
711 // Setup a callback to disable the readlogs after max interval.
712 addTimedJob(*mTimedQueue, storageId, Constants::readLogsMaxInterval,
713 [this, storageId, startLoadingTs]() {
714 const auto ifs = getIfs(storageId);
715 if (!ifs) {
716 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
717 << storageId;
718 return;
719 }
720 if (ifs->startLoadingTs != startLoadingTs) {
721 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
722 "installation?): "
723 << storageId;
724 return;
725 }
726 setStorageParams(*ifs, storageId, /*enableReadLogs=*/false);
727 });
728 }
729
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800730 return dataLoaderStub->requestStart();
731}
732
Songchun Fan3c82a302019-11-29 14:23:45 -0800733IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
734 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700735 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800736}
737
738StorageId IncrementalService::findStorageId(std::string_view path) const {
739 std::lock_guard l(mLock);
740 auto it = findStorageLocked(path);
741 if (it == mBindsByPath.end()) {
742 return kInvalidStorageId;
743 }
744 return it->second->second.storage;
745}
746
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800747void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700748 std::unique_lock l(mLock);
749 const auto ifs = getIfsLocked(storageId);
750 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800751 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700752 return;
753 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800754 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700755 return;
756 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800757 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700758 l.unlock();
759
760 const auto metadata = constants().readLogsDisabledMarkerName;
761 if (auto err = mIncFs->makeFile(ifs->control,
762 path::join(ifs->root, constants().mount,
763 constants().readLogsDisabledMarkerName),
764 0777, idFromMetadata(metadata), {})) {
765 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
766 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
767 return;
768 }
769
770 setStorageParams(storageId, /*enableReadLogs=*/false);
771}
772
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700773int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
774 const auto ifs = getIfs(storageId);
775 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700776 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700777 return -EINVAL;
778 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700779 return setStorageParams(*ifs, storageId, enableReadLogs);
780}
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700781
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700782int IncrementalService::setStorageParams(IncFsMount& ifs, StorageId storageId,
783 bool enableReadLogs) {
784 const auto& params = ifs.dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700785 if (enableReadLogs) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700786 if (!ifs.readLogsAllowed()) {
787 LOG(ERROR) << "setStorageParams failed, readlogs disallowed for storageId: "
788 << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700789 return -EPERM;
790 }
791
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800792 // Check loader usage stats permission and apop.
793 if (auto status = mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700794 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700795 !status.isOk()) {
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800796 LOG(ERROR) << " Permission: " << kLoaderUsageStats
797 << " check failed: " << status.toString8();
798 return fromBinderStatus(status);
799 }
800
801 // Check multiuser permission.
802 if (auto status = mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr,
803 params.packageName.c_str());
804 !status.isOk()) {
805 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
806 << " check failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700807 return fromBinderStatus(status);
808 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700809
810 // Check installation time.
811 const auto now = mClock->now();
812 const auto startLoadingTs = ifs.startLoadingTs;
813 if (startLoadingTs <= now && now - startLoadingTs > Constants::readLogsMaxInterval) {
814 LOG(ERROR) << "setStorageParams failed, readlogs can't be enabled at this time, "
815 "storageId: "
816 << storageId;
817 return -EPERM;
818 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700819 }
820
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700821 if (auto status = applyStorageParams(ifs, enableReadLogs); !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700822 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
823 return fromBinderStatus(status);
824 }
825
826 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700827 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700828 }
829
830 return 0;
831}
832
833binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700834 os::incremental::IncrementalFileSystemControlParcel control;
835 control.cmd.reset(dup(ifs.control.cmd()));
836 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700837 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700838 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700839 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700840 }
841
842 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800843 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
844 if (status.isOk()) {
845 // Store enabled state.
846 ifs.setReadLogsEnabled(enableReadLogs);
847 }
848 return status;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700849}
850
Songchun Fan3c82a302019-11-29 14:23:45 -0800851void IncrementalService::deleteStorage(StorageId storageId) {
852 const auto ifs = getIfs(storageId);
853 if (!ifs) {
854 return;
855 }
856 deleteStorage(*ifs);
857}
858
859void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
860 std::unique_lock l(ifs.lock);
861 deleteStorageLocked(ifs, std::move(l));
862}
863
864void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
865 std::unique_lock<std::mutex>&& ifsLock) {
866 const auto storages = std::move(ifs.storages);
867 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
868 const auto bindPoints = ifs.bindPoints;
869 ifsLock.unlock();
870
871 std::lock_guard l(mLock);
872 for (auto&& [id, _] : storages) {
873 if (id != ifs.mountId) {
874 mMounts.erase(id);
875 }
876 }
877 for (auto&& [path, _] : bindPoints) {
878 mBindsByPath.erase(path);
879 }
880 mMounts.erase(ifs.mountId);
881}
882
883StorageId IncrementalService::openStorage(std::string_view pathInMount) {
884 if (!path::isAbsolute(pathInMount)) {
885 return kInvalidStorageId;
886 }
887
888 return findStorageId(path::normalize(pathInMount));
889}
890
Songchun Fan3c82a302019-11-29 14:23:45 -0800891IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
892 std::lock_guard l(mLock);
893 return getIfsLocked(storage);
894}
895
896const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
897 auto it = mMounts.find(storage);
898 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700899 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700900 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800901 }
902 return it->second;
903}
904
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800905int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
906 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800907 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700908 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800909 return -EINVAL;
910 }
911
912 const auto ifs = getIfs(storage);
913 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700914 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800915 return -EINVAL;
916 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800917
Songchun Fan3c82a302019-11-29 14:23:45 -0800918 std::unique_lock l(ifs->lock);
919 const auto storageInfo = ifs->storages.find(storage);
920 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700921 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800922 return -EINVAL;
923 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700924 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700925 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700926 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700927 return -EINVAL;
928 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800929 l.unlock();
930 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800931 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
932 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800933}
934
935int IncrementalService::unbind(StorageId storage, std::string_view target) {
936 if (!path::isAbsolute(target)) {
937 return -EINVAL;
938 }
939
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700940 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800941
942 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
943 // otherwise there's a chance to unmount something completely unrelated
944 const auto norm = path::normalize(target);
945 std::unique_lock l(mLock);
946 const auto storageIt = mBindsByPath.find(norm);
947 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
948 return -EINVAL;
949 }
950 const auto bindIt = storageIt->second;
951 const auto storageId = bindIt->second.storage;
952 const auto ifs = getIfsLocked(storageId);
953 if (!ifs) {
954 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
955 << " is missing";
956 return -EFAULT;
957 }
958 mBindsByPath.erase(storageIt);
959 l.unlock();
960
961 mVold->unmountIncFs(bindIt->first);
962 std::unique_lock l2(ifs->lock);
963 if (ifs->bindPoints.size() <= 1) {
964 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700965 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800966 } else {
967 const std::string savedFile = std::move(bindIt->second.savedFilename);
968 ifs->bindPoints.erase(bindIt);
969 l2.unlock();
970 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800971 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800972 }
973 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700974
Songchun Fan3c82a302019-11-29 14:23:45 -0800975 return 0;
976}
977
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700978std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700979 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700980 std::string_view path) const {
981 if (!path::isAbsolute(path)) {
982 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700983 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700984 auto normPath = path::normalize(path);
985 if (path::startsWith(normPath, storageIt->second.name)) {
986 return normPath;
987 }
988 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700989 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
990 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700991 return {};
992 }
993 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700994}
995
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700996std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700997 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700998 std::unique_lock l(ifs.lock);
999 const auto storageInfo = ifs.storages.find(storage);
1000 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001001 return {};
1002 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001003 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001004}
1005
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001006int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001007 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001008 const auto ifs = getIfs(storage);
1009 if (!ifs) {
1010 return -EINVAL;
1011 }
1012 if (data.size() > params.size) {
1013 LOG(ERROR) << "Bad data size - bigger than file size";
1014 return -EINVAL;
1015 }
1016 if (!data.empty() && data.size() != params.size) {
1017 // Writing a page is an irreversible operation, and it can't be updated with additional
1018 // data later. Check that the last written page is complete, or we may break the file.
1019 if (!isPageAligned(data.size())) {
1020 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001021 return -EINVAL;
1022 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001023 }
1024 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1025 if (normPath.empty()) {
1026 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1027 return -EINVAL;
1028 }
1029 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1030 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1031 return err;
1032 }
1033 if (params.size > 0) {
1034 // Only v2+ incfs supports automatically trimming file over-reserved sizes
1035 if (mIncFs->features() & incfs::Features::v2) {
1036 if (auto err = mIncFs->reserveSpace(ifs->control, normPath, params.size)) {
1037 if (err != -EOPNOTSUPP) {
1038 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1039 (void)mIncFs->unlink(ifs->control, normPath);
1040 return err;
1041 } else {
1042 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1043 "may run out of disk later";
1044 }
1045 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001046 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001047 if (!data.empty()) {
1048 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001049 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001050 return err;
1051 }
1052 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001053 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001054 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001055}
1056
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001057int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001058 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001059 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001060 if (normPath.empty()) {
1061 return -EINVAL;
1062 }
1063 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001064 }
1065 return -EINVAL;
1066}
1067
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001068int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001069 const auto ifs = getIfs(storageId);
1070 if (!ifs) {
1071 return -EINVAL;
1072 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001073 return makeDirs(*ifs, storageId, path, mode);
1074}
1075
1076int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1077 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001078 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1079 if (normPath.empty()) {
1080 return -EINVAL;
1081 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001082 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001083}
1084
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001085int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1086 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001087 std::unique_lock l(mLock);
1088 auto ifsSrc = getIfsLocked(sourceStorageId);
1089 if (!ifsSrc) {
1090 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001091 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001092 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1093 return -EINVAL;
1094 }
1095 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001096 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1097 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001098 if (normOldPath.empty() || normNewPath.empty()) {
1099 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1100 return -EINVAL;
1101 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001102 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1103 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1104 << " to " << newPath << "[" << normNewPath << "]";
1105 return err;
1106 }
1107 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001108}
1109
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001110int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001111 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001112 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001113 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001114 }
1115 return -EINVAL;
1116}
1117
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001118int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1119 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001120 std::string&& target, BindKind kind,
1121 std::unique_lock<std::mutex>& mainLock) {
1122 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001123 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001124 return -EINVAL;
1125 }
1126
1127 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001128 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001129 if (kind != BindKind::Temporary) {
1130 metadata::BindPoint bp;
1131 bp.set_storage_id(storage);
1132 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001133 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001134 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001135 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001136 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001137 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001138 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1139 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1140 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001141 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001142 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001143 return int(node);
1144 }
1145 }
1146
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001147 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1148 std::move(target), kind, mainLock);
1149 if (res) {
1150 mIncFs->unlink(ifs.control, metadataFullPath);
1151 }
1152 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001153}
1154
1155int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001156 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001157 std::string&& target, BindKind kind,
1158 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001159 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001160 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001161 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001162 if (!status.isOk()) {
1163 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1164 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1165 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1166 : status.serviceSpecificErrorCode() == 0
1167 ? -EFAULT
1168 : status.serviceSpecificErrorCode()
1169 : -EIO;
1170 }
1171 }
1172
1173 if (!mainLock.owns_lock()) {
1174 mainLock.lock();
1175 }
1176 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001177 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1178 std::move(target), kind);
1179 return 0;
1180}
1181
1182void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1183 std::string&& metadataName, std::string&& source,
1184 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001185 const auto [it, _] =
1186 ifs.bindPoints.insert_or_assign(target,
1187 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001188 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001189 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001190}
1191
1192RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1193 const auto ifs = getIfs(storage);
1194 if (!ifs) {
1195 return {};
1196 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001197 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001198 if (normPath.empty()) {
1199 return {};
1200 }
1201 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001202}
1203
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001204RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001205 const auto ifs = getIfs(storage);
1206 if (!ifs) {
1207 return {};
1208 }
1209 return mIncFs->getMetadata(ifs->control, node);
1210}
1211
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001212void IncrementalService::setUidReadTimeouts(
1213 StorageId storage, const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
1214 using microseconds = std::chrono::microseconds;
1215 using milliseconds = std::chrono::milliseconds;
1216
1217 auto maxPendingTimeUs = microseconds(0);
1218 for (const auto& timeouts : perUidReadTimeouts) {
1219 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1220 }
1221 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001222 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001223 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1224 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001225 return;
1226 }
1227
1228 const auto ifs = getIfs(storage);
1229 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001230 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001231 return;
1232 }
1233
1234 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1235 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1236 return;
1237 }
1238
1239 const auto timeout = std::chrono::duration_cast<milliseconds>(maxPendingTimeUs) -
1240 Constants::perUidTimeoutOffset;
1241 updateUidReadTimeouts(storage, Clock::now() + timeout);
1242}
1243
1244void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1245 const auto ifs = getIfs(storage);
1246 if (!ifs) {
1247 return;
1248 }
1249
1250 mIncFs->setUidReadTimeouts(ifs->control, {});
1251}
1252
1253void IncrementalService::updateUidReadTimeouts(StorageId storage, Clock::time_point timeLimit) {
1254 // Reached maximum timeout.
1255 if (Clock::now() >= timeLimit) {
1256 return clearUidReadTimeouts(storage);
1257 }
1258
1259 // Still loading?
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001260 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/true);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001261 if (progress.isError()) {
1262 // Something is wrong, abort.
1263 return clearUidReadTimeouts(storage);
1264 }
1265
1266 if (progress.started() && progress.fullyLoaded()) {
1267 // Fully loaded, check readLogs collection.
1268 const auto ifs = getIfs(storage);
1269 if (!ifs->readLogsEnabled()) {
1270 return clearUidReadTimeouts(storage);
1271 }
1272 }
1273
1274 const auto timeLeft = timeLimit - Clock::now();
1275 if (timeLeft < Constants::progressUpdateInterval) {
1276 // Don't bother.
1277 return clearUidReadTimeouts(storage);
1278 }
1279
1280 addTimedJob(*mTimedQueue, storage, Constants::progressUpdateInterval,
1281 [this, storage, timeLimit]() { updateUidReadTimeouts(storage, timeLimit); });
1282}
1283
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001284std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1285 std::unordered_set<std::string_view> mountedRootNames;
1286 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1287 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1288 for (auto [source, target] : binds) {
1289 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1290 LOG(INFO) << " " << path::join(root, source);
1291 }
1292
1293 // Ensure it's a kind of a mount that's managed by IncrementalService
1294 if (path::basename(root) != constants().mount ||
1295 path::basename(backingDir) != constants().backing) {
1296 return;
1297 }
1298 const auto expectedRoot = path::dirname(root);
1299 if (path::dirname(backingDir) != expectedRoot) {
1300 return;
1301 }
1302 if (path::dirname(expectedRoot) != mIncrementalDir) {
1303 return;
1304 }
1305 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1306 return;
1307 }
1308
1309 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1310
1311 // make sure we clean up the mount if it happens to be a bad one.
1312 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1313 auto cleanupFiles = makeCleanup([&]() {
1314 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1315 IncFsMount::cleanupFilesystem(expectedRoot);
1316 });
1317 auto cleanupMounts = makeCleanup([&]() {
1318 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1319 for (auto&& [_, target] : binds) {
1320 mVold->unmountIncFs(std::string(target));
1321 }
1322 mVold->unmountIncFs(std::string(root));
1323 });
1324
1325 auto control = mIncFs->openMount(root);
1326 if (!control) {
1327 LOG(INFO) << "failed to open mount " << root;
1328 return;
1329 }
1330
1331 auto mountRecord =
1332 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1333 path::join(root, constants().infoMdName));
1334 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1335 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1336 return;
1337 }
1338
1339 auto mountId = mountRecord.storage().id();
1340 mNextId = std::max(mNextId, mountId + 1);
1341
1342 DataLoaderParamsParcel dataLoaderParams;
1343 {
1344 const auto& loader = mountRecord.loader();
1345 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1346 dataLoaderParams.packageName = loader.package_name();
1347 dataLoaderParams.className = loader.class_name();
1348 dataLoaderParams.arguments = loader.arguments();
1349 }
1350
1351 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1352 std::move(control), *this);
1353 cleanupFiles.release(); // ifs will take care of that now
1354
Alex Buynytskyy04035452020-06-06 20:15:58 -07001355 // Check if marker file present.
1356 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001357 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001358 }
1359
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001360 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1361 auto d = openDir(root);
1362 while (auto e = ::readdir(d.get())) {
1363 if (e->d_type == DT_REG) {
1364 auto name = std::string_view(e->d_name);
1365 if (name.starts_with(constants().mountpointMdPrefix)) {
1366 permanentBindPoints
1367 .emplace_back(name,
1368 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1369 ifs->control,
1370 path::join(root,
1371 name)));
1372 if (permanentBindPoints.back().second.dest_path().empty() ||
1373 permanentBindPoints.back().second.source_subdir().empty()) {
1374 permanentBindPoints.pop_back();
1375 mIncFs->unlink(ifs->control, path::join(root, name));
1376 } else {
1377 LOG(INFO) << "Permanent bind record: '"
1378 << permanentBindPoints.back().second.source_subdir() << "'->'"
1379 << permanentBindPoints.back().second.dest_path() << "'";
1380 }
1381 }
1382 } else if (e->d_type == DT_DIR) {
1383 if (e->d_name == "."sv || e->d_name == ".."sv) {
1384 continue;
1385 }
1386 auto name = std::string_view(e->d_name);
1387 if (name.starts_with(constants().storagePrefix)) {
1388 int storageId;
1389 const auto res =
1390 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1391 name.data() + name.size(), storageId);
1392 if (res.ec != std::errc{} || *res.ptr != '_') {
1393 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1394 << "' for mount " << expectedRoot;
1395 continue;
1396 }
1397 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1398 if (!inserted) {
1399 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1400 << " for mount " << expectedRoot;
1401 continue;
1402 }
1403 ifs->storages.insert_or_assign(storageId,
1404 IncFsMount::Storage{path::join(root, name)});
1405 mNextId = std::max(mNextId, storageId + 1);
1406 }
1407 }
1408 }
1409
1410 if (ifs->storages.empty()) {
1411 LOG(WARNING) << "No valid storages in mount " << root;
1412 return;
1413 }
1414
1415 // now match the mounted directories with what we expect to have in the metadata
1416 {
1417 std::unique_lock l(mLock, std::defer_lock);
1418 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1419 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1420 [&, bindRecord = bindRecord](auto&& bind) {
1421 return bind.second == bindRecord.dest_path() &&
1422 path::join(root, bind.first) ==
1423 bindRecord.source_subdir();
1424 });
1425 if (mountedIt != binds.end()) {
1426 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1427 << " to mount " << mountedIt->first;
1428 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1429 std::move(*bindRecord.mutable_source_subdir()),
1430 std::move(*bindRecord.mutable_dest_path()),
1431 BindKind::Permanent);
1432 if (mountedIt != binds.end() - 1) {
1433 std::iter_swap(mountedIt, binds.end() - 1);
1434 }
1435 binds = binds.first(binds.size() - 1);
1436 } else {
1437 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1438 << ", mounting";
1439 // doesn't exist - try mounting back
1440 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1441 std::move(*bindRecord.mutable_source_subdir()),
1442 std::move(*bindRecord.mutable_dest_path()),
1443 BindKind::Permanent, l)) {
1444 mIncFs->unlink(ifs->control, metadataFile);
1445 }
1446 }
1447 }
1448 }
1449
1450 // if anything stays in |binds| those are probably temporary binds; system restarted since
1451 // they were mounted - so let's unmount them all.
1452 for (auto&& [source, target] : binds) {
1453 if (source.empty()) {
1454 continue;
1455 }
1456 mVold->unmountIncFs(std::string(target));
1457 }
1458 cleanupMounts.release(); // ifs now manages everything
1459
1460 if (ifs->bindPoints.empty()) {
1461 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1462 deleteStorage(*ifs);
1463 return;
1464 }
1465
1466 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1467 CHECK(ifs->dataLoaderStub);
1468
1469 mountedRootNames.insert(path::basename(ifs->root));
1470
1471 // not locking here at all: we're still in the constructor, no other calls can happen
1472 mMounts[ifs->mountId] = std::move(ifs);
1473 });
1474
1475 return mountedRootNames;
1476}
1477
1478void IncrementalService::mountExistingImages(
1479 const std::unordered_set<std::string_view>& mountedRootNames) {
1480 auto dir = openDir(mIncrementalDir);
1481 if (!dir) {
1482 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1483 return;
1484 }
1485 while (auto entry = ::readdir(dir.get())) {
1486 if (entry->d_type != DT_DIR) {
1487 continue;
1488 }
1489 std::string_view name = entry->d_name;
1490 if (!name.starts_with(constants().mountKeyPrefix)) {
1491 continue;
1492 }
1493 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001494 continue;
1495 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001496 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001497 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001498 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001499 }
1500 }
1501}
1502
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001503bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001504 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001505 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001506
Songchun Fan3c82a302019-11-29 14:23:45 -08001507 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001508 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001509 if (!status.isOk()) {
1510 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1511 return false;
1512 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001513
1514 int cmd = controlParcel.cmd.release().release();
1515 int pendingReads = controlParcel.pendingReads.release().release();
1516 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001517 int blocksWritten =
1518 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1519 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001520
1521 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1522
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001523 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1524 path::join(mountTarget, constants().infoMdName));
1525 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001526 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1527 return false;
1528 }
1529
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001530 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001531 mNextId = std::max(mNextId, ifs->mountId + 1);
1532
Alex Buynytskyy04035452020-06-06 20:15:58 -07001533 // Check if marker file present.
1534 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001535 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001536 }
1537
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001538 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001539 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001540 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001541 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001542 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001543 dataLoaderParams.packageName = loader.package_name();
1544 dataLoaderParams.className = loader.class_name();
1545 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001546 }
1547
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001548 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001549 CHECK(ifs->dataLoaderStub);
1550
Songchun Fan3c82a302019-11-29 14:23:45 -08001551 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001552 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001553 while (auto e = ::readdir(d.get())) {
1554 if (e->d_type == DT_REG) {
1555 auto name = std::string_view(e->d_name);
1556 if (name.starts_with(constants().mountpointMdPrefix)) {
1557 bindPoints.emplace_back(name,
1558 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1559 ifs->control,
1560 path::join(mountTarget,
1561 name)));
1562 if (bindPoints.back().second.dest_path().empty() ||
1563 bindPoints.back().second.source_subdir().empty()) {
1564 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001565 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001566 }
1567 }
1568 } else if (e->d_type == DT_DIR) {
1569 if (e->d_name == "."sv || e->d_name == ".."sv) {
1570 continue;
1571 }
1572 auto name = std::string_view(e->d_name);
1573 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001574 int storageId;
1575 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1576 name.data() + name.size(), storageId);
1577 if (res.ec != std::errc{} || *res.ptr != '_') {
1578 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1579 << root;
1580 continue;
1581 }
1582 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001583 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001584 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001585 << " for mount " << root;
1586 continue;
1587 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001588 ifs->storages.insert_or_assign(storageId,
1589 IncFsMount::Storage{
1590 path::join(root, constants().mount, name)});
1591 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001592 }
1593 }
1594 }
1595
1596 if (ifs->storages.empty()) {
1597 LOG(WARNING) << "No valid storages in mount " << root;
1598 return false;
1599 }
1600
1601 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001602 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001603 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001604 for (auto&& bp : bindPoints) {
1605 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1606 std::move(*bp.second.mutable_source_subdir()),
1607 std::move(*bp.second.mutable_dest_path()),
1608 BindKind::Permanent, l);
1609 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001610 }
1611
1612 if (bindCount == 0) {
1613 LOG(WARNING) << "No valid bind points for mount " << root;
1614 deleteStorage(*ifs);
1615 return false;
1616 }
1617
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001618 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001619 mMounts[ifs->mountId] = std::move(ifs);
1620 return true;
1621}
1622
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001623void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001624 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001625 while (mRunning.load(std::memory_order_relaxed)) {
1626 mLooper->pollAll(kTimeoutMsecs);
1627 }
1628}
1629
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001630IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001631 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001632 const DataLoaderStatusListener* statusListener,
1633 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001634 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001635 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1636 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001637 return ifs.dataLoaderStub;
1638}
1639
1640void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001641 const DataLoaderStatusListener* statusListener,
1642 StorageHealthCheckParams&& healthCheckParams,
1643 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001644 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001645 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001646 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001647 }
1648
Songchun Fan3c82a302019-11-29 14:23:45 -08001649 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001650 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001651 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1652 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1653 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001654 if (ifs.control.blocksWritten() >= 0) {
1655 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1656 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001657 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001658
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001659 ifs.dataLoaderStub =
1660 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001661 statusListener, std::move(healthCheckParams), healthListener,
1662 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001663}
1664
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001665template <class Duration>
1666static long elapsedMcs(Duration start, Duration end) {
1667 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1668}
1669
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001670template <class Duration>
1671static constexpr auto castToMs(Duration d) {
1672 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1673}
1674
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001675// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001676// Lib files should be placed next to the APK file in the following matter:
1677// Example:
1678// /path/to/base.apk
1679// /path/to/lib/arm/first.so
1680// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001681bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1682 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001683 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001684 auto start = Clock::now();
1685
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001686 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001687 if (!ifs) {
1688 LOG(ERROR) << "Invalid storage " << storage;
1689 return false;
1690 }
1691
Songchun Fanc8975312020-07-13 12:14:37 -07001692 const auto targetLibPathRelativeToStorage =
1693 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1694 libDirRelativePath);
1695
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001696 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001697 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1698 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001699 << " errno: " << res;
1700 return false;
1701 }
1702
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001703 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001704 ZipArchiveHandle zipFileHandle;
1705 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001706 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1707 return false;
1708 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001709
1710 // Need a shared pointer: will be passing it into all unpacking jobs.
1711 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001712 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001713 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001714 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001715 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1716 return false;
1717 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001718 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001719 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1720
1721 auto openZipTs = Clock::now();
1722
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001723 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1724 incfs::FileId sourceId;
1725 if (mapFiles) {
1726 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1727 if (!incfs::isValidFileId(sourceId)) {
1728 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1729 << "', mapping disabled";
1730 mapFiles = false;
1731 }
1732 }
1733
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001734 std::vector<Job> jobQueue;
1735 ZipEntry entry;
1736 std::string_view fileName;
1737 while (!Next(cookie, &entry, &fileName)) {
1738 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001739 continue;
1740 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001741
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001742 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001743 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001744
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001745 if (!extractNativeLibs) {
1746 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001747 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001748 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1749 return false;
1750 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001751 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001752 LOG(WARNING) << "Library " << fileName
1753 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1754 << entry.offset;
1755 return false;
1756 }
1757 continue;
1758 }
1759
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001760 auto startFileTs = Clock::now();
1761
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001762 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001763 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001764 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001765 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001766 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001767 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001768 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1769 << "; skipping extraction, spent "
1770 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1771 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001772 continue;
1773 }
1774
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001775 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1776 incfs::NewMappedFileParams mappedFileParams = {
1777 .sourceId = sourceId,
1778 .sourceOffset = entry.offset,
1779 .size = entry.uncompressed_length,
1780 };
1781
1782 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1783 mappedFileParams);
1784 res == 0) {
1785 if (perfLoggingEnabled()) {
1786 auto doneTs = Clock::now();
1787 LOG(INFO) << "incfs: Mapped " << libName << ": "
1788 << elapsedMcs(startFileTs, doneTs) << "mcs";
1789 }
1790 continue;
1791 } else {
1792 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1793 << "; falling back to full extraction";
1794 }
1795 }
1796
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001797 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001798 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001799 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001800 .signature = {},
1801 // Metadata of the new lib file is its relative path
1802 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1803 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001804 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001805 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001806 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001807 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001808 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001809 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001810 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001811
1812 auto makeFileTs = Clock::now();
1813
Songchun Fanafaf6e92020-03-18 14:12:20 -07001814 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001815 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001816 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001817 LOG(INFO) << "incfs: Extracted " << libName
1818 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001819 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001820 continue;
1821 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001822
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001823 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1824 libFileId, libPath = std::move(targetLibPath),
1825 makeFileTs]() mutable {
1826 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001827 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001828
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001829 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001830 auto prepareJobTs = Clock::now();
1831 LOG(INFO) << "incfs: Processed " << libName << ": "
1832 << elapsedMcs(startFileTs, prepareJobTs)
1833 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1834 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001835 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001836 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001837
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001838 auto processedTs = Clock::now();
1839
1840 if (!jobQueue.empty()) {
1841 {
1842 std::lock_guard lock(mJobMutex);
1843 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001844 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001845 if (existingJobs.empty()) {
1846 existingJobs = std::move(jobQueue);
1847 } else {
1848 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1849 std::move_iterator(jobQueue.end()));
1850 }
1851 }
1852 }
1853 mJobCondition.notify_all();
1854 }
1855
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001856 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001857 auto end = Clock::now();
1858 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1859 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1860 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001861 << " make files: " << elapsedMcs(openZipTs, processedTs)
1862 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001863 }
1864
1865 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001866}
1867
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001868void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1869 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001870 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001871 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001872 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001873 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001874 return;
1875 }
1876
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001877 auto startedTs = Clock::now();
1878
1879 // Write extracted data to new file
1880 // NOTE: don't zero-initialize memory, it may take a while for nothing
1881 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1882 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001883 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001884 return;
1885 }
1886
1887 auto extractFileTs = Clock::now();
1888
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001889 if (setFileContent(ifs, libFileId, debugLibPath,
1890 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001891 return;
1892 }
1893
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001894 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001895 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001896 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1897 << entry.compressed_length << " -> " << entry.uncompressed_length
1898 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001899 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1900 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001901 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001902 }
1903}
1904
1905bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001906 struct WaitPrinter {
1907 const Clock::time_point startTs = Clock::now();
1908 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001909 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001910 const auto endTs = Clock::now();
1911 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1912 << elapsedMcs(startTs, endTs) << "mcs";
1913 }
1914 }
1915 } waitPrinter;
1916
1917 MountId mount;
1918 {
1919 auto ifs = getIfs(storage);
1920 if (!ifs) {
1921 return true;
1922 }
1923 mount = ifs->mountId;
1924 }
1925
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001926 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001927 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001928 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001929 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001930 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001931 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001932}
1933
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001934int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1935 std::string_view debugFilePath,
1936 std::span<const uint8_t> data) const {
1937 auto startTs = Clock::now();
1938
1939 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1940 if (!writeFd.ok()) {
1941 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1942 << " errno: " << writeFd.get();
1943 return writeFd.get();
1944 }
1945
1946 const auto dataLength = data.size();
1947
1948 auto openFileTs = Clock::now();
1949 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1950 std::vector<IncFsDataBlock> instructions(numBlocks);
1951 for (int i = 0; i < numBlocks; i++) {
1952 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1953 instructions[i] = IncFsDataBlock{
1954 .fileFd = writeFd.get(),
1955 .pageIndex = static_cast<IncFsBlockIndex>(i),
1956 .compression = INCFS_COMPRESSION_KIND_NONE,
1957 .kind = INCFS_BLOCK_KIND_DATA,
1958 .dataSize = static_cast<uint32_t>(blockSize),
1959 .data = reinterpret_cast<const char*>(data.data()),
1960 };
1961 data = data.subspan(blockSize);
1962 }
1963 auto prepareInstsTs = Clock::now();
1964
1965 size_t res = mIncFs->writeBlocks(instructions);
1966 if (res != instructions.size()) {
1967 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1968 return res;
1969 }
1970
1971 if (perfLoggingEnabled()) {
1972 auto endTs = Clock::now();
1973 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1974 << " bytes): " << elapsedMcs(startTs, endTs)
1975 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1976 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1977 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1978 }
1979
1980 return 0;
1981}
1982
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001983int IncrementalService::isFileFullyLoaded(StorageId storage, std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001984 std::unique_lock l(mLock);
1985 const auto ifs = getIfsLocked(storage);
1986 if (!ifs) {
1987 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1988 return -EINVAL;
1989 }
1990 const auto storageInfo = ifs->storages.find(storage);
1991 if (storageInfo == ifs->storages.end()) {
1992 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1993 return -EINVAL;
1994 }
1995 l.unlock();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001996 return isFileFullyLoadedFromPath(*ifs, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001997}
1998
1999int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
2000 std::string_view filePath) const {
2001 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
2002 if (filledBlocks < 0) {
2003 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
2004 << filePath << " errno: " << filledBlocks;
2005 return filledBlocks;
2006 }
2007 if (totalBlocks < filledBlocks) {
2008 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
2009 return -EINVAL;
2010 }
2011 return totalBlocks - filledBlocks;
2012}
2013
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002014IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08002015 StorageId storage, bool stopOnFirstIncomplete) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002016 std::unique_lock l(mLock);
2017 const auto ifs = getIfsLocked(storage);
2018 if (!ifs) {
2019 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002020 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002021 }
2022 const auto storageInfo = ifs->storages.find(storage);
2023 if (storageInfo == ifs->storages.end()) {
2024 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002025 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002026 }
2027 l.unlock();
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08002028 return getLoadingProgressFromPath(*ifs, storageInfo->second.name, stopOnFirstIncomplete);
Songchun Fan374f7652020-08-20 08:40:29 -07002029}
2030
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002031IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002032 const IncFsMount& ifs, std::string_view storagePath,
2033 const bool stopOnFirstIncomplete) const {
2034 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2035 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002036 const auto [filledBlocksCount, totalBlocksCount] =
2037 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002038 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2039 filledBlocksCount == -ENOENT) {
2040 // a kind of a file that's not really being loaded, e.g. a mapped range
2041 // an older IncFS used to return ENOENT in this case, so handle it the same way
2042 return true;
2043 }
Songchun Fan374f7652020-08-20 08:40:29 -07002044 if (filledBlocksCount < 0) {
2045 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
2046 << " errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002047 error = filledBlocksCount;
2048 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002049 }
2050 totalBlocks += totalBlocksCount;
2051 filledBlocks += filledBlocksCount;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08002052 if (stopOnFirstIncomplete && filledBlocks < totalBlocks) {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002053 return false;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08002054 }
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002055 return true;
2056 });
Songchun Fan374f7652020-08-20 08:40:29 -07002057
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002058 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002059}
2060
Songchun Fana7098592020-09-03 11:45:53 -07002061bool IncrementalService::updateLoadingProgress(
2062 StorageId storage, const StorageLoadingProgressListener& progressListener) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08002063 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/false);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002064 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002065 // Failed to get progress from incfs, abort.
2066 return false;
2067 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002068 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2069 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002070 // Stop updating progress once it is fully loaded
2071 return true;
2072 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002073 addTimedJob(*mProgressUpdateJobQueue, storage,
2074 Constants::progressUpdateInterval /* repeat after 1s */,
Songchun Fana7098592020-09-03 11:45:53 -07002075 [storage, progressListener, this]() {
2076 updateLoadingProgress(storage, progressListener);
2077 });
2078 return true;
2079}
2080
2081bool IncrementalService::registerLoadingProgressListener(
2082 StorageId storage, const StorageLoadingProgressListener& progressListener) {
2083 return updateLoadingProgress(storage, progressListener);
2084}
2085
2086bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2087 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2088}
2089
Songchun Fan2570ec02020-10-08 17:22:33 -07002090bool IncrementalService::registerStorageHealthListener(
2091 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
2092 const StorageHealthListener& healthListener) {
2093 DataLoaderStubPtr dataLoaderStub;
2094 {
2095 std::unique_lock l(mLock);
2096 const auto& ifs = getIfsLocked(storage);
2097 if (!ifs) {
2098 return false;
2099 }
2100 dataLoaderStub = ifs->dataLoaderStub;
2101 if (!dataLoaderStub) {
2102 return false;
2103 }
2104 }
2105 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
2106 return true;
2107}
2108
2109void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
2110 StorageHealthCheckParams invalidCheckParams;
2111 invalidCheckParams.blockedTimeoutMs = -1;
2112 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
2113}
2114
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002115bool IncrementalService::perfLoggingEnabled() {
2116 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2117 return enabled;
2118}
2119
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002120void IncrementalService::runJobProcessing() {
2121 for (;;) {
2122 std::unique_lock lock(mJobMutex);
2123 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2124 if (!mRunning) {
2125 return;
2126 }
2127
2128 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002129 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002130 auto queue = std::move(it->second);
2131 mJobQueue.erase(it);
2132 lock.unlock();
2133
2134 for (auto&& job : queue) {
2135 job();
2136 }
2137
2138 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002139 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002140 lock.unlock();
2141 mJobCondition.notify_all();
2142 }
2143}
2144
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002145void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002146 sp<IAppOpsCallback> listener;
2147 {
2148 std::unique_lock lock{mCallbacksLock};
2149 auto& cb = mCallbackRegistered[packageName];
2150 if (cb) {
2151 return;
2152 }
2153 cb = new AppOpsListener(*this, packageName);
2154 listener = cb;
2155 }
2156
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002157 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2158 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002159}
2160
2161bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2162 sp<IAppOpsCallback> listener;
2163 {
2164 std::unique_lock lock{mCallbacksLock};
2165 auto found = mCallbackRegistered.find(packageName);
2166 if (found == mCallbackRegistered.end()) {
2167 return false;
2168 }
2169 listener = found->second;
2170 mCallbackRegistered.erase(found);
2171 }
2172
2173 mAppOpsManager->stopWatchingMode(listener);
2174 return true;
2175}
2176
2177void IncrementalService::onAppOpChanged(const std::string& packageName) {
2178 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002179 return;
2180 }
2181
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002182 std::vector<IfsMountPtr> affected;
2183 {
2184 std::lock_guard l(mLock);
2185 affected.reserve(mMounts.size());
2186 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002187 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002188 affected.push_back(ifs);
2189 }
2190 }
2191 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002192 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002193 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002194 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002195}
2196
Songchun Fana7098592020-09-03 11:45:53 -07002197bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2198 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002199 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002200 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002201 }
Songchun Fana7098592020-09-03 11:45:53 -07002202 timedQueue.addJob(id, after, std::move(what));
2203 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002204}
2205
Songchun Fana7098592020-09-03 11:45:53 -07002206bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002207 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002208 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002209 }
Songchun Fana7098592020-09-03 11:45:53 -07002210 timedQueue.removeJobs(id);
2211 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002212}
2213
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002214void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
2215 const auto duration = getMillsSinceOldestPendingRead(storageId);
2216 if (duration >= 0) {
2217 const auto kMetricsMillisSinceOldestPendingRead =
2218 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2219 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2220 }
2221}
2222
2223long IncrementalService::getMillsSinceOldestPendingRead(StorageId storageId) {
2224 std::unique_lock l(mLock);
2225 const auto ifs = getIfsLocked(storageId);
2226 if (!ifs) {
2227 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, invalid storageId: " << storageId;
2228 return -EINVAL;
2229 }
2230 if (!ifs->dataLoaderStub) {
2231 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, no data loader: " << storageId;
2232 return -EINVAL;
2233 }
2234 return ifs->dataLoaderStub->elapsedMsSinceOldestPendingRead();
2235}
2236
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002237IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
2238 DataLoaderParamsParcel&& params,
2239 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002240 const DataLoaderStatusListener* statusListener,
2241 StorageHealthCheckParams&& healthCheckParams,
2242 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002243 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002244 : mService(service),
2245 mId(id),
2246 mParams(std::move(params)),
2247 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002248 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
2249 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002250 mHealthPath(std::move(healthPath)),
2251 mHealthCheckParams(std::move(healthCheckParams)) {
2252 if (mHealthListener) {
2253 if (!isHealthParamsValid()) {
2254 mHealthListener = {};
2255 }
2256 } else {
2257 // Disable advanced health check statuses.
2258 mHealthCheckParams.blockedTimeoutMs = -1;
2259 }
2260 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002261}
2262
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002263IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002264 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002265 cleanupResources();
2266 }
2267}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002268
2269void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002270 auto now = Clock::now();
2271 {
2272 std::unique_lock lock(mMutex);
2273 mHealthPath.clear();
2274 unregisterFromPendingReads();
2275 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002276 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002277 }
2278
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002279 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002280
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002281 {
2282 std::unique_lock lock(mMutex);
2283 mParams = {};
2284 mControl = {};
2285 mHealthControl = {};
2286 mHealthListener = {};
2287 mStatusCondition.wait_until(lock, now + 60s, [this] {
2288 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2289 });
2290 mStatusListener = {};
2291 mId = kInvalidStorageId;
2292 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002293}
2294
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002295sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2296 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002297 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002298 if (!status.isOk()) {
2299 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2300 return {};
2301 }
2302 if (!dataloader) {
2303 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2304 return {};
2305 }
2306 return dataloader;
2307}
2308
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002309bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2310 return (params().packageName == Constants::systemPackage);
2311}
2312
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002313bool IncrementalService::DataLoaderStub::requestCreate() {
2314 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2315}
2316
2317bool IncrementalService::DataLoaderStub::requestStart() {
2318 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2319}
2320
2321bool IncrementalService::DataLoaderStub::requestDestroy() {
2322 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2323}
2324
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002325bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002326 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002327 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002328 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002329 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002330 return fsmStep();
2331}
2332
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002333void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002334 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002335 mTargetStatus = status;
2336 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002337 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002338 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002339}
2340
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002341std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002342 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002343
2344 const auto now = mService.mClock->now();
2345 const bool healthy = (mPreviousBindDelay == 0ms);
2346
2347 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2348 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2349 LOG(INFO) << "Binding still in progress. "
2350 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
2351 : "Already unhealthy, don't do anything.");
2352 // Binding still in progress.
2353 if (!healthy) {
2354 // Already unhealthy, don't do anything.
2355 return {};
2356 }
2357 // The DL is healthy/freshly bound, ok to retry for a few times.
2358 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2359 // Still within grace period.
2360 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2361 // Retry interval passed, retrying.
2362 mCurrentStatusTs = now;
2363 mPreviousBindDelay = 0ms;
2364 return 0ms;
2365 }
2366 return {};
2367 }
2368 // fallthrough, mark as unhealthy, and retry with delay
2369 }
2370
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002371 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002372 mPreviousBindTs = now;
2373
2374 const auto nonCrashingInterval = std::max(castToMs(now - previousBindTs), 100ms);
2375 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2376 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2377 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002378 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002379 }
2380
2381 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2382 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2383
2384 const auto bindDelayMs =
2385 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2386 maxBindDelayMs)
2387 .count();
2388 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2389 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2390 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002391 return mPreviousBindDelay;
2392}
2393
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002394bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002395 const auto maybeBindDelay = needToBind();
2396 if (!maybeBindDelay) {
2397 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2398 return true;
2399 }
2400 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002401 if (bindDelay > 1s) {
2402 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
2403 << bindDelay.count() / 1000 << "s";
2404 }
2405
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002406 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002407 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2408 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002409 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002410 const bool healthy = (bindDelay == 0ms);
2411 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2412 << (healthy ? ", retrying." : "");
2413
2414 // Internal error, retry for healthy/new DLs.
2415 // Let needToBind migrate it to unhealthy after too many retries.
2416 if (healthy) {
2417 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2418 [this]() { fsmStep(); })) {
2419 // Mark as binding so that we know it's not the DL's fault.
2420 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2421 return true;
2422 }
2423 }
2424
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002425 return false;
2426 }
2427 return true;
2428}
2429
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002430bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002431 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002432 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002433 return false;
2434 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002435 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002436 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002437 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002438 return false;
2439 }
2440 return true;
2441}
2442
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002443bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002444 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002445 if (!dataloader) {
2446 return false;
2447 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002448 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002449 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002450 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002451 return false;
2452 }
2453 return true;
2454}
2455
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002456bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002457 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002458}
2459
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002460bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002461 if (!isValid()) {
2462 return false;
2463 }
2464
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002465 int currentStatus;
2466 int targetStatus;
2467 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002468 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002469 currentStatus = mCurrentStatus;
2470 targetStatus = mTargetStatus;
2471 }
2472
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002473 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002474
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002475 if (currentStatus == targetStatus) {
2476 return true;
2477 }
2478
2479 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002480 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2481 // Do nothing, this is a reset state.
2482 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002483 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002484 switch (currentStatus) {
2485 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2486 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2487 return true;
2488 default:
2489 return destroy();
2490 }
2491 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002492 }
2493 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2494 switch (currentStatus) {
2495 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2496 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2497 return start();
2498 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002499 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002500 }
2501 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2502 switch (currentStatus) {
2503 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002504 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002505 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002506 return bind();
2507 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002508 return create();
2509 }
2510 break;
2511 default:
2512 LOG(ERROR) << "Invalid target status: " << targetStatus
2513 << ", current status: " << currentStatus;
2514 break;
2515 }
2516 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002517}
2518
2519binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002520 if (!isValid()) {
2521 return binder::Status::
2522 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2523 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002524 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002525 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2526 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002527 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2528 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002529 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2530 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2531 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2532 [this, newStatus]() { setCurrentStatus(newStatus); });
2533 return binder::Status::ok();
2534 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002535
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002536 setCurrentStatus(newStatus);
2537 return binder::Status::ok();
2538}
2539
2540void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002541 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002542 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002543 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002544 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002545 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002546 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002547 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002548
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002549 oldStatus = mCurrentStatus;
2550 targetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002551 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002552
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002553 // Change the status.
2554 mCurrentStatus = newStatus;
2555 mCurrentStatusTs = mService.mClock->now();
2556
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002557 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2558 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002559 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2560 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002561 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002562 }
2563
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002564 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002565 << newStatus << " (target " << targetStatus << ")";
2566
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002567 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002568 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002569 }
2570
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002571 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002572
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002573 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002574}
2575
Songchun Fan33093982020-09-10 13:12:39 -07002576binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2577 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002578 if (!isValid()) {
2579 return binder::Status::
2580 fromServiceSpecificError(-EINVAL,
2581 "reportStreamHealth came to invalid DataLoaderStub");
2582 }
2583 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002584 LOG(ERROR) << "reportStreamHealth: mount ID mismatch: expected " << id()
2585 << ", but got: " << mountId;
Songchun Fan2570ec02020-10-08 17:22:33 -07002586 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2587 }
2588 {
2589 std::lock_guard lock(mMutex);
2590 mStreamStatus = newStatus;
2591 }
Songchun Fan33093982020-09-10 13:12:39 -07002592 return binder::Status::ok();
2593}
2594
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002595bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2596 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2597 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002598}
2599
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002600void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2601 int healthStatus) {
2602 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2603 if (healthListener) {
2604 healthListener->onHealthStatus(id(), healthStatus);
2605 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002606}
2607
Songchun Fan2570ec02020-10-08 17:22:33 -07002608static int adjustHealthStatus(int healthStatus, int streamStatus) {
2609 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2610 // everything is good; no need to change status
2611 return healthStatus;
2612 }
2613 int newHeathStatus = healthStatus;
2614 switch (streamStatus) {
2615 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2616 // storage is limited and storage not healthy
2617 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2618 break;
2619 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2620 // fall through
2621 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2622 // fall through
2623 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2624 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2625 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2626 }
2627 // pending/blocked status due to transportation issues is not regarded as unhealthy
2628 break;
2629 default:
2630 break;
2631 }
2632 return newHeathStatus;
2633}
2634
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002635void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2636 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002637
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002638 int healthStatusToReport = -1;
2639 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002640
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002641 {
2642 std::unique_lock lock(mMutex);
2643 unregisterFromPendingReads();
2644
2645 healthListener = mHealthListener;
2646
2647 // Healthcheck depends on timestamp of the oldest pending read.
2648 // 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 -07002649 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2650 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002651 const auto now = Clock::now();
2652 const auto kernelTsUs = getOldestPendingReadTs();
2653 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002654 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2655 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002656 mHealthBase = {now, kernelTsUs};
2657 }
2658
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002659 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2660 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002661 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2662 registerForPendingReads();
2663 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2664 lock.unlock();
2665 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002666 return;
2667 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002668
2669 resetHealthControl();
2670
2671 // Always make sure the data loader is started.
2672 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2673
2674 // Skip any further processing if health check params are invalid.
2675 if (!isHealthParamsValid()) {
2676 LOG(DEBUG) << id()
2677 << ": Skip any further processing if health check params are invalid.";
2678 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2679 lock.unlock();
2680 onHealthStatus(healthListener, healthStatusToReport);
2681 // Triggering data loader start. This is a one-time action.
2682 fsmStep();
2683 return;
2684 }
2685
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002686 // Don't schedule timer job less than 500ms in advance.
2687 static constexpr auto kTolerance = 500ms;
2688
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002689 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2690 const auto unhealthyTimeout =
2691 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2692 const auto unhealthyMonitoring =
2693 std::max(1000ms,
2694 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2695
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002696 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002697
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002698 Milliseconds checkBackAfter;
2699 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002700 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002701 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002702 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002703 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002704 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002705 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002706 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2707 } else {
2708 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002709 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002710 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2711 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002712 // Adjust health status based on stream status
2713 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002714 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002715 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002716 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2717 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002718 }
2719
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002720 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002721 if (healthStatusToReport != -1) {
2722 onHealthStatus(healthListener, healthStatusToReport);
2723 }
2724
2725 fsmStep();
2726}
2727
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002728Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2729 BootClockTsUs kernelTsUs) {
2730 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2731 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2732 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2733}
2734
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002735const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2736 if (mHealthPath.empty()) {
2737 resetHealthControl();
2738 return mHealthControl;
2739 }
2740 if (mHealthControl.pendingReads() < 0) {
2741 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2742 }
2743 if (mHealthControl.pendingReads() < 0) {
2744 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2745 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2746 << mHealthControl.logs() << ")";
2747 }
2748 return mHealthControl;
2749}
2750
2751void IncrementalService::DataLoaderStub::resetHealthControl() {
2752 mHealthControl = {};
2753}
2754
2755BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2756 auto result = kMaxBootClockTsUs;
2757
2758 const auto& control = initializeHealthControl();
2759 if (control.pendingReads() < 0) {
2760 return result;
2761 }
2762
Songchun Fan6944f1e2020-11-06 15:24:24 -08002763 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002764 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002765 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002766 // Clear previous pending reads
2767 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002768 return result;
2769 }
2770
2771 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002772 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002773
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002774 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002775}
2776
2777void IncrementalService::DataLoaderStub::registerForPendingReads() {
2778 const auto pendingReadsFd = mHealthControl.pendingReads();
2779 if (pendingReadsFd < 0) {
2780 return;
2781 }
2782
2783 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2784
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002785 mService.mLooper->addFd(
2786 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2787 [](int, int, void* data) -> int {
2788 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002789 self->updateHealthStatus(/*baseline=*/true);
2790 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002791 },
2792 this);
2793 mService.mLooper->wake();
2794}
2795
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002796BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2797 auto result = kMaxBootClockTsUs;
2798 for (auto&& pendingRead : mLastPendingReads) {
2799 result = std::min(result, pendingRead.bootClockTsUs);
2800 }
2801 return result;
2802}
2803
2804long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
2805 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
2806 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
2807 return 0;
2808 }
2809 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
2810}
2811
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002812void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002813 const auto pendingReadsFd = mHealthControl.pendingReads();
2814 if (pendingReadsFd < 0) {
2815 return;
2816 }
2817
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002818 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2819
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002820 mService.mLooper->removeFd(pendingReadsFd);
2821 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002822}
2823
Songchun Fan2570ec02020-10-08 17:22:33 -07002824void IncrementalService::DataLoaderStub::setHealthListener(
2825 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2826 std::lock_guard lock(mMutex);
2827 mHealthCheckParams = std::move(healthCheckParams);
2828 if (healthListener == nullptr) {
2829 // reset listener and params
2830 mHealthListener = {};
2831 } else {
2832 mHealthListener = *healthListener;
2833 }
2834}
2835
Songchun Fan6944f1e2020-11-06 15:24:24 -08002836static std::string toHexString(const RawMetadata& metadata) {
2837 int n = metadata.size();
2838 std::string res(n * 2, '\0');
2839 // Same as incfs::toString(fileId)
2840 static constexpr char kHexChar[] = "0123456789abcdef";
2841 for (int i = 0; i < n; ++i) {
2842 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2843 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2844 }
2845 return res;
2846}
2847
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002848void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002849 dprintf(fd, " dataLoader: {\n");
2850 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002851 dprintf(fd, " currentStatusTs: %lldmcs\n",
2852 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002853 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2854 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002855 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002856 dprintf(fd, " health: {\n");
2857 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2858 dprintf(fd, " base: %lldmcs (%lld)\n",
2859 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2860 (long long)mHealthBase.kernelTsUs);
2861 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2862 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2863 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2864 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002865 dprintf(fd, " lastPendingReads: \n");
2866 const auto control = mService.mIncFs->openMount(mHealthPath);
2867 for (auto&& pendingRead : mLastPendingReads) {
2868 dprintf(fd, " fileId: %s\n", mService.mIncFs->toString(pendingRead.id).c_str());
2869 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2870 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2871 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2872 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2873 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002874 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
2875 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
2876 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002877 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002878 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002879 dprintf(fd, " dataLoaderParams: {\n");
2880 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2881 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2882 dprintf(fd, " className: %s\n", params.className.c_str());
2883 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2884 dprintf(fd, " }\n");
2885 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002886}
2887
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002888void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2889 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002890}
2891
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002892binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2893 bool enableReadLogs, int32_t* _aidl_return) {
2894 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2895 return binder::Status::ok();
2896}
2897
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002898FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2899 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2900}
2901
Songchun Fan3c82a302019-11-29 14:23:45 -08002902} // namespace android::incremental