blob: 958eb15385431336387961d0a9b3c1ef478a93c9 [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>
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700250static auto makeCleanup(Func&& f) requires(!std::is_lvalue_reference_v<Func>) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700251 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
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700256static auto openDir(const char* dir) {
257 struct DirCloser {
258 void operator()(DIR* d) const noexcept { ::closedir(d); }
259 };
260 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700261}
262
263static auto openDir(std::string_view dir) {
264 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800265}
266
267static int rmDirContent(const char* path) {
268 auto dir = openDir(path);
269 if (!dir) {
270 return -EINVAL;
271 }
272 while (auto entry = ::readdir(dir.get())) {
273 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
274 continue;
275 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700276 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800277 if (entry->d_type == DT_DIR) {
278 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
279 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
280 return err;
281 }
282 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
283 PLOG(WARNING) << "Failed to rmdir " << fullPath;
284 return err;
285 }
286 } else {
287 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
288 PLOG(WARNING) << "Failed to delete " << fullPath;
289 return err;
290 }
291 }
292 }
293 return 0;
294}
295
Songchun Fan3c82a302019-11-29 14:23:45 -0800296void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800297 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800298 ::rmdir(path::join(root, constants().backing).c_str());
299 ::rmdir(path::join(root, constants().mount).c_str());
300 ::rmdir(path::c_str(root));
301}
302
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700303void IncrementalService::IncFsMount::setReadLogsEnabled(bool value) {
304 if (value) {
305 flags |= StorageFlags::ReadLogsEnabled;
306 } else {
307 flags &= ~StorageFlags::ReadLogsEnabled;
308 }
309}
310
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800311IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800312 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800313 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800314 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700315 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700316 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700317 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700318 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700319 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700320 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800321 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800322 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700323 CHECK(mVold) << "Vold service is unavailable";
324 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
325 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
326 CHECK(mJni) << "JNI is unavailable";
327 CHECK(mLooper) << "Looper is unavailable";
328 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700329 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700330 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800331 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700332
333 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700334 mJobProcessor = std::thread([this]() {
335 mJni->initializeForCurrentThread();
336 runJobProcessing();
337 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700338 mCmdLooperThread = std::thread([this]() {
339 mJni->initializeForCurrentThread();
340 runCmdLooper();
341 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700342
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700343 const auto mountedRootNames = adoptMountedInstances();
344 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800345}
346
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700347IncrementalService::~IncrementalService() {
348 {
349 std::lock_guard lock(mJobMutex);
350 mRunning = false;
351 }
352 mJobCondition.notify_all();
353 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700354 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700355 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700356 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700357 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700358 // Ensure that mounts are destroyed while the service is still valid.
359 mBindsByPath.clear();
360 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700361}
Songchun Fan3c82a302019-11-29 14:23:45 -0800362
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700363static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800364 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800365 case IncrementalService::BindKind::Temporary:
366 return "Temporary";
367 case IncrementalService::BindKind::Permanent:
368 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800369 }
370}
371
372void IncrementalService::onDump(int fd) {
373 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
374 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
375
376 std::unique_lock l(mLock);
377
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700378 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800379 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700380 const IncFsMount& mnt = *ifs;
381 dprintf(fd, " [%d]: {\n", id);
382 if (id != mnt.mountId) {
383 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
384 } else {
385 dprintf(fd, " mountId: %d\n", mnt.mountId);
386 dprintf(fd, " root: %s\n", mnt.root.c_str());
387 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
388 if (mnt.dataLoaderStub) {
389 mnt.dataLoaderStub->onDump(fd);
390 } else {
391 dprintf(fd, " dataLoader: null\n");
392 }
393 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
394 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700395 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700396 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800397 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700398 }
399 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800400
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700401 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
402 for (auto&& [target, bind] : mnt.bindPoints) {
403 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
404 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
405 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
406 dprintf(fd, " kind: %s\n", toString(bind.kind));
407 }
408 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800409 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700410 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800411 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700412 dprintf(fd, "}\n");
413 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800414 for (auto&& [target, mountPairIt] : mBindsByPath) {
415 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700416 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
417 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
418 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
419 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800420 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700421 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800422}
423
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800424bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700425 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800426 return true;
427 }
428
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700429 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800430}
431
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700432void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800433 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700434 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800435 }
436
437 std::vector<IfsMountPtr> mounts;
438 {
439 std::lock_guard l(mLock);
440 mounts.reserve(mMounts.size());
441 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800442 if (ifs->mountId != id) {
443 continue;
444 }
445
446 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800447 mounts.push_back(ifs);
448 }
449 }
450 }
451
Alex Buynytskyy69941662020-04-11 21:40:37 -0700452 if (mounts.empty()) {
453 return;
454 }
455
Songchun Fan3c82a302019-11-29 14:23:45 -0800456 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700457 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800458 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700459 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800460 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800461 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800462}
463
464auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
465 for (;;) {
466 if (mNextId == kMaxStorageId) {
467 mNextId = 0;
468 }
469 auto id = ++mNextId;
470 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
471 if (inserted) {
472 return it;
473 }
474 }
475}
476
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800477StorageId IncrementalService::createStorage(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800478 std::string_view mountPoint, const content::pm::DataLoaderParamsParcel& dataLoaderParams,
479 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800480 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
481 if (!path::isAbsolute(mountPoint)) {
482 LOG(ERROR) << "path is not absolute: " << mountPoint;
483 return kInvalidStorageId;
484 }
485
486 auto mountNorm = path::normalize(mountPoint);
487 {
488 const auto id = findStorageId(mountNorm);
489 if (id != kInvalidStorageId) {
490 if (options & CreateOptions::OpenExisting) {
491 LOG(INFO) << "Opened existing storage " << id;
492 return id;
493 }
494 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
495 return kInvalidStorageId;
496 }
497 }
498
499 if (!(options & CreateOptions::CreateNew)) {
500 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
501 return kInvalidStorageId;
502 }
503
504 if (!path::isEmptyDir(mountNorm)) {
505 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
506 return kInvalidStorageId;
507 }
508 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
509 if (mountRoot.empty()) {
510 LOG(ERROR) << "Bad mount point";
511 return kInvalidStorageId;
512 }
513 // Make sure the code removes all crap it may create while still failing.
514 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
515 auto firstCleanupOnFailure =
516 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
517
518 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800519 const auto backing = path::join(mountRoot, constants().backing);
520 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800521 return kInvalidStorageId;
522 }
523
Songchun Fan3c82a302019-11-29 14:23:45 -0800524 IncFsMount::Control control;
525 {
526 std::lock_guard l(mMountOperationLock);
527 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800528
529 if (auto err = rmDirContent(backing.c_str())) {
530 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
531 return kInvalidStorageId;
532 }
533 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
534 return kInvalidStorageId;
535 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800536 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
537 return kInvalidStorageId;
538 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800539 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800540 if (!status.isOk()) {
541 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
542 return kInvalidStorageId;
543 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800544 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
545 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800546 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
547 return kInvalidStorageId;
548 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800549 int cmd = controlParcel.cmd.release().release();
550 int pendingReads = controlParcel.pendingReads.release().release();
551 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800552 int blocksWritten =
553 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
554 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800555 }
556
557 std::unique_lock l(mLock);
558 const auto mountIt = getStorageSlotLocked();
559 const auto mountId = mountIt->first;
560 l.unlock();
561
562 auto ifs =
563 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
564 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
565 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700566 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800567
568 auto secondCleanup = [this, &l](auto itPtr) {
569 if (!l.owns_lock()) {
570 l.lock();
571 }
572 mMounts.erase(*itPtr);
573 };
574 auto secondCleanupOnFailure =
575 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
576
577 const auto storageIt = ifs->makeStorage(ifs->mountId);
578 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800579 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800580 return kInvalidStorageId;
581 }
582
583 {
584 metadata::Mount m;
585 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700586 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800587 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
588 m.mutable_loader()->set_class_name(dataLoaderParams.className);
589 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800590 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800591 if (auto err =
592 mIncFs->makeFile(ifs->control,
593 path::join(ifs->root, constants().mount,
594 constants().infoMdName),
595 0777, idFromMetadata(metadata),
596 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800597 LOG(ERROR) << "Saving mount metadata failed: " << -err;
598 return kInvalidStorageId;
599 }
600 }
601
602 const auto bk =
603 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800604 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
605 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800606 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800607 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800608 return kInvalidStorageId;
609 }
610
611 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700612 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800613
Songchun Fan3c82a302019-11-29 14:23:45 -0800614 mountIt->second = std::move(ifs);
615 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700616
Songchun Fan3c82a302019-11-29 14:23:45 -0800617 LOG(INFO) << "created storage " << mountId;
618 return mountId;
619}
620
621StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
622 StorageId linkedStorage,
623 IncrementalService::CreateOptions options) {
624 if (!isValidMountTarget(mountPoint)) {
625 LOG(ERROR) << "Mount point is invalid or missing";
626 return kInvalidStorageId;
627 }
628
629 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700630 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800631 if (!ifs) {
632 LOG(ERROR) << "Ifs unavailable";
633 return kInvalidStorageId;
634 }
635
636 const auto mountIt = getStorageSlotLocked();
637 const auto storageId = mountIt->first;
638 const auto storageIt = ifs->makeStorage(storageId);
639 if (storageIt == ifs->storages.end()) {
640 LOG(ERROR) << "Can't create a new storage";
641 mMounts.erase(mountIt);
642 return kInvalidStorageId;
643 }
644
645 l.unlock();
646
647 const auto bk =
648 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800649 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
650 std::string(storageIt->second.name), path::normalize(mountPoint),
651 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800652 err < 0) {
653 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700654 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
655 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800656 return kInvalidStorageId;
657 }
658
659 mountIt->second = ifs;
660 return storageId;
661}
662
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700663bool IncrementalService::startLoading(StorageId storageId,
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800664 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
665 const DataLoaderStatusListener& statusListener,
666 StorageHealthCheckParams&& healthCheckParams,
667 const StorageHealthListener& healthListener,
668 const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
669 // Per Uid timeouts.
670 if (!perUidReadTimeouts.empty()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700671 setUidReadTimeouts(storageId, perUidReadTimeouts);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800672 }
673
674 // Re-initialize DataLoader.
675 std::unique_lock l(mLock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700676 const auto ifs = getIfsLocked(storageId);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800677 if (!ifs) {
678 return false;
679 }
680 if (ifs->dataLoaderStub) {
681 ifs->dataLoaderStub->cleanupResources();
682 ifs->dataLoaderStub = {};
683 }
684 l.unlock();
685
686 // DataLoader.
687 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
688 std::move(healthCheckParams), &healthListener);
689 CHECK(dataLoaderStub);
690
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700691 if (dataLoaderStub->isSystemDataLoader()) {
692 // Readlogs from system dataloader (adb) can always be collected.
693 ifs->startLoadingTs = TimePoint::max();
694 } else {
695 // Assign time when installation wants the DL to start streaming.
696 const auto startLoadingTs = mClock->now();
697 ifs->startLoadingTs = startLoadingTs;
698 // Setup a callback to disable the readlogs after max interval.
699 addTimedJob(*mTimedQueue, storageId, Constants::readLogsMaxInterval,
700 [this, storageId, startLoadingTs]() {
701 const auto ifs = getIfs(storageId);
702 if (!ifs) {
703 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
704 << storageId;
705 return;
706 }
707 if (ifs->startLoadingTs != startLoadingTs) {
708 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
709 "installation?): "
710 << storageId;
711 return;
712 }
713 setStorageParams(*ifs, storageId, /*enableReadLogs=*/false);
714 });
715 }
716
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800717 return dataLoaderStub->requestStart();
718}
719
Songchun Fan3c82a302019-11-29 14:23:45 -0800720IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
721 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700722 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800723}
724
725StorageId IncrementalService::findStorageId(std::string_view path) const {
726 std::lock_guard l(mLock);
727 auto it = findStorageLocked(path);
728 if (it == mBindsByPath.end()) {
729 return kInvalidStorageId;
730 }
731 return it->second->second.storage;
732}
733
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800734void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700735 std::unique_lock l(mLock);
736 const auto ifs = getIfsLocked(storageId);
737 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800738 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700739 return;
740 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800741 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700742 return;
743 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800744 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700745 l.unlock();
746
747 const auto metadata = constants().readLogsDisabledMarkerName;
748 if (auto err = mIncFs->makeFile(ifs->control,
749 path::join(ifs->root, constants().mount,
750 constants().readLogsDisabledMarkerName),
751 0777, idFromMetadata(metadata), {})) {
752 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
753 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
754 return;
755 }
756
757 setStorageParams(storageId, /*enableReadLogs=*/false);
758}
759
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700760int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
761 const auto ifs = getIfs(storageId);
762 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700763 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700764 return -EINVAL;
765 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700766 return setStorageParams(*ifs, storageId, enableReadLogs);
767}
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700768
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700769int IncrementalService::setStorageParams(IncFsMount& ifs, StorageId storageId,
770 bool enableReadLogs) {
771 const auto& params = ifs.dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700772 if (enableReadLogs) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700773 if (!ifs.readLogsAllowed()) {
774 LOG(ERROR) << "setStorageParams failed, readlogs disallowed for storageId: "
775 << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700776 return -EPERM;
777 }
778
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800779 // Check loader usage stats permission and apop.
780 if (auto status = mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700781 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700782 !status.isOk()) {
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800783 LOG(ERROR) << " Permission: " << kLoaderUsageStats
784 << " check failed: " << status.toString8();
785 return fromBinderStatus(status);
786 }
787
788 // Check multiuser permission.
789 if (auto status = mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr,
790 params.packageName.c_str());
791 !status.isOk()) {
792 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
793 << " check failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700794 return fromBinderStatus(status);
795 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700796
797 // Check installation time.
798 const auto now = mClock->now();
799 const auto startLoadingTs = ifs.startLoadingTs;
800 if (startLoadingTs <= now && now - startLoadingTs > Constants::readLogsMaxInterval) {
801 LOG(ERROR) << "setStorageParams failed, readlogs can't be enabled at this time, "
802 "storageId: "
803 << storageId;
804 return -EPERM;
805 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700806 }
807
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700808 if (auto status = applyStorageParams(ifs, enableReadLogs); !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700809 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
810 return fromBinderStatus(status);
811 }
812
813 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700814 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700815 }
816
817 return 0;
818}
819
820binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700821 os::incremental::IncrementalFileSystemControlParcel control;
822 control.cmd.reset(dup(ifs.control.cmd()));
823 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700824 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700825 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700826 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700827 }
828
829 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700830 auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800831 if (status.isOk()) {
832 // Store enabled state.
833 ifs.setReadLogsEnabled(enableReadLogs);
834 }
835 return status;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700836}
837
Songchun Fan3c82a302019-11-29 14:23:45 -0800838void IncrementalService::deleteStorage(StorageId storageId) {
839 const auto ifs = getIfs(storageId);
840 if (!ifs) {
841 return;
842 }
843 deleteStorage(*ifs);
844}
845
846void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
847 std::unique_lock l(ifs.lock);
848 deleteStorageLocked(ifs, std::move(l));
849}
850
851void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
852 std::unique_lock<std::mutex>&& ifsLock) {
853 const auto storages = std::move(ifs.storages);
854 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
855 const auto bindPoints = ifs.bindPoints;
856 ifsLock.unlock();
857
858 std::lock_guard l(mLock);
859 for (auto&& [id, _] : storages) {
860 if (id != ifs.mountId) {
861 mMounts.erase(id);
862 }
863 }
864 for (auto&& [path, _] : bindPoints) {
865 mBindsByPath.erase(path);
866 }
867 mMounts.erase(ifs.mountId);
868}
869
870StorageId IncrementalService::openStorage(std::string_view pathInMount) {
871 if (!path::isAbsolute(pathInMount)) {
872 return kInvalidStorageId;
873 }
874
875 return findStorageId(path::normalize(pathInMount));
876}
877
Songchun Fan3c82a302019-11-29 14:23:45 -0800878IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
879 std::lock_guard l(mLock);
880 return getIfsLocked(storage);
881}
882
883const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
884 auto it = mMounts.find(storage);
885 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700886 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700887 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800888 }
889 return it->second;
890}
891
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800892int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
893 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800894 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700895 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800896 return -EINVAL;
897 }
898
899 const auto ifs = getIfs(storage);
900 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700901 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800902 return -EINVAL;
903 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800904
Songchun Fan3c82a302019-11-29 14:23:45 -0800905 std::unique_lock l(ifs->lock);
906 const auto storageInfo = ifs->storages.find(storage);
907 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700908 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800909 return -EINVAL;
910 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700911 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700912 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700913 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700914 return -EINVAL;
915 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800916 l.unlock();
917 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800918 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
919 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800920}
921
922int IncrementalService::unbind(StorageId storage, std::string_view target) {
923 if (!path::isAbsolute(target)) {
924 return -EINVAL;
925 }
926
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700927 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800928
929 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
930 // otherwise there's a chance to unmount something completely unrelated
931 const auto norm = path::normalize(target);
932 std::unique_lock l(mLock);
933 const auto storageIt = mBindsByPath.find(norm);
934 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
935 return -EINVAL;
936 }
937 const auto bindIt = storageIt->second;
938 const auto storageId = bindIt->second.storage;
939 const auto ifs = getIfsLocked(storageId);
940 if (!ifs) {
941 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
942 << " is missing";
943 return -EFAULT;
944 }
945 mBindsByPath.erase(storageIt);
946 l.unlock();
947
948 mVold->unmountIncFs(bindIt->first);
949 std::unique_lock l2(ifs->lock);
950 if (ifs->bindPoints.size() <= 1) {
951 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700952 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800953 } else {
954 const std::string savedFile = std::move(bindIt->second.savedFilename);
955 ifs->bindPoints.erase(bindIt);
956 l2.unlock();
957 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800958 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800959 }
960 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700961
Songchun Fan3c82a302019-11-29 14:23:45 -0800962 return 0;
963}
964
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700965std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700966 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700967 std::string_view path) const {
968 if (!path::isAbsolute(path)) {
969 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700970 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700971 auto normPath = path::normalize(path);
972 if (path::startsWith(normPath, storageIt->second.name)) {
973 return normPath;
974 }
975 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700976 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
977 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700978 return {};
979 }
980 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700981}
982
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700983std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700984 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700985 std::unique_lock l(ifs.lock);
986 const auto storageInfo = ifs.storages.find(storage);
987 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800988 return {};
989 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700990 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800991}
992
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800993int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700994 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -0700995 const auto ifs = getIfs(storage);
996 if (!ifs) {
997 return -EINVAL;
998 }
999 if (data.size() > params.size) {
1000 LOG(ERROR) << "Bad data size - bigger than file size";
1001 return -EINVAL;
1002 }
1003 if (!data.empty() && data.size() != params.size) {
1004 // Writing a page is an irreversible operation, and it can't be updated with additional
1005 // data later. Check that the last written page is complete, or we may break the file.
1006 if (!isPageAligned(data.size())) {
1007 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001008 return -EINVAL;
1009 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001010 }
1011 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1012 if (normPath.empty()) {
1013 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1014 return -EINVAL;
1015 }
1016 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1017 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1018 return err;
1019 }
1020 if (params.size > 0) {
1021 // Only v2+ incfs supports automatically trimming file over-reserved sizes
1022 if (mIncFs->features() & incfs::Features::v2) {
1023 if (auto err = mIncFs->reserveSpace(ifs->control, normPath, params.size)) {
1024 if (err != -EOPNOTSUPP) {
1025 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1026 (void)mIncFs->unlink(ifs->control, normPath);
1027 return err;
1028 } else {
1029 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1030 "may run out of disk later";
1031 }
1032 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001033 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001034 if (!data.empty()) {
1035 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001036 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001037 return err;
1038 }
1039 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001040 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001041 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001042}
1043
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001044int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001045 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001046 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001047 if (normPath.empty()) {
1048 return -EINVAL;
1049 }
1050 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001051 }
1052 return -EINVAL;
1053}
1054
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001055int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001056 const auto ifs = getIfs(storageId);
1057 if (!ifs) {
1058 return -EINVAL;
1059 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001060 return makeDirs(*ifs, storageId, path, mode);
1061}
1062
1063int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1064 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001065 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1066 if (normPath.empty()) {
1067 return -EINVAL;
1068 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001069 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001070}
1071
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001072int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1073 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001074 std::unique_lock l(mLock);
1075 auto ifsSrc = getIfsLocked(sourceStorageId);
1076 if (!ifsSrc) {
1077 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001078 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001079 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1080 return -EINVAL;
1081 }
1082 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001083 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1084 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001085 if (normOldPath.empty() || normNewPath.empty()) {
1086 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1087 return -EINVAL;
1088 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001089 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1090 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1091 << " to " << newPath << "[" << normNewPath << "]";
1092 return err;
1093 }
1094 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001095}
1096
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001097int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001098 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001099 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001100 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001101 }
1102 return -EINVAL;
1103}
1104
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001105int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1106 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001107 std::string&& target, BindKind kind,
1108 std::unique_lock<std::mutex>& mainLock) {
1109 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001110 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001111 return -EINVAL;
1112 }
1113
1114 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001115 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001116 if (kind != BindKind::Temporary) {
1117 metadata::BindPoint bp;
1118 bp.set_storage_id(storage);
1119 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001120 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001121 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001122 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001123 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001124 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001125 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1126 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1127 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001128 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001129 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001130 return int(node);
1131 }
1132 }
1133
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001134 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1135 std::move(target), kind, mainLock);
1136 if (res) {
1137 mIncFs->unlink(ifs.control, metadataFullPath);
1138 }
1139 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001140}
1141
1142int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001143 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001144 std::string&& target, BindKind kind,
1145 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001146 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001147 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001148 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001149 if (!status.isOk()) {
1150 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1151 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1152 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1153 : status.serviceSpecificErrorCode() == 0
1154 ? -EFAULT
1155 : status.serviceSpecificErrorCode()
1156 : -EIO;
1157 }
1158 }
1159
1160 if (!mainLock.owns_lock()) {
1161 mainLock.lock();
1162 }
1163 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001164 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1165 std::move(target), kind);
1166 return 0;
1167}
1168
1169void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1170 std::string&& metadataName, std::string&& source,
1171 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001172 const auto [it, _] =
1173 ifs.bindPoints.insert_or_assign(target,
1174 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001175 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001176 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001177}
1178
1179RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1180 const auto ifs = getIfs(storage);
1181 if (!ifs) {
1182 return {};
1183 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001184 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001185 if (normPath.empty()) {
1186 return {};
1187 }
1188 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001189}
1190
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001191RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001192 const auto ifs = getIfs(storage);
1193 if (!ifs) {
1194 return {};
1195 }
1196 return mIncFs->getMetadata(ifs->control, node);
1197}
1198
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001199void IncrementalService::setUidReadTimeouts(
1200 StorageId storage, const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
1201 using microseconds = std::chrono::microseconds;
1202 using milliseconds = std::chrono::milliseconds;
1203
1204 auto maxPendingTimeUs = microseconds(0);
1205 for (const auto& timeouts : perUidReadTimeouts) {
1206 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1207 }
1208 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001209 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001210 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1211 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001212 return;
1213 }
1214
1215 const auto ifs = getIfs(storage);
1216 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001217 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001218 return;
1219 }
1220
1221 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1222 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1223 return;
1224 }
1225
1226 const auto timeout = std::chrono::duration_cast<milliseconds>(maxPendingTimeUs) -
1227 Constants::perUidTimeoutOffset;
1228 updateUidReadTimeouts(storage, Clock::now() + timeout);
1229}
1230
1231void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1232 const auto ifs = getIfs(storage);
1233 if (!ifs) {
1234 return;
1235 }
1236
1237 mIncFs->setUidReadTimeouts(ifs->control, {});
1238}
1239
1240void IncrementalService::updateUidReadTimeouts(StorageId storage, Clock::time_point timeLimit) {
1241 // Reached maximum timeout.
1242 if (Clock::now() >= timeLimit) {
1243 return clearUidReadTimeouts(storage);
1244 }
1245
1246 // Still loading?
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001247 const auto state = isMountFullyLoaded(storage);
1248 if (int(state) < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001249 // Something is wrong, abort.
1250 return clearUidReadTimeouts(storage);
1251 }
1252
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001253 if (state == incfs::LoadingState::Full) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001254 // Fully loaded, check readLogs collection.
1255 const auto ifs = getIfs(storage);
1256 if (!ifs->readLogsEnabled()) {
1257 return clearUidReadTimeouts(storage);
1258 }
1259 }
1260
1261 const auto timeLeft = timeLimit - Clock::now();
1262 if (timeLeft < Constants::progressUpdateInterval) {
1263 // Don't bother.
1264 return clearUidReadTimeouts(storage);
1265 }
1266
1267 addTimedJob(*mTimedQueue, storage, Constants::progressUpdateInterval,
1268 [this, storage, timeLimit]() { updateUidReadTimeouts(storage, timeLimit); });
1269}
1270
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001271std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1272 std::unordered_set<std::string_view> mountedRootNames;
1273 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1274 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1275 for (auto [source, target] : binds) {
1276 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1277 LOG(INFO) << " " << path::join(root, source);
1278 }
1279
1280 // Ensure it's a kind of a mount that's managed by IncrementalService
1281 if (path::basename(root) != constants().mount ||
1282 path::basename(backingDir) != constants().backing) {
1283 return;
1284 }
1285 const auto expectedRoot = path::dirname(root);
1286 if (path::dirname(backingDir) != expectedRoot) {
1287 return;
1288 }
1289 if (path::dirname(expectedRoot) != mIncrementalDir) {
1290 return;
1291 }
1292 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1293 return;
1294 }
1295
1296 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1297
1298 // make sure we clean up the mount if it happens to be a bad one.
1299 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1300 auto cleanupFiles = makeCleanup([&]() {
1301 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1302 IncFsMount::cleanupFilesystem(expectedRoot);
1303 });
1304 auto cleanupMounts = makeCleanup([&]() {
1305 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1306 for (auto&& [_, target] : binds) {
1307 mVold->unmountIncFs(std::string(target));
1308 }
1309 mVold->unmountIncFs(std::string(root));
1310 });
1311
1312 auto control = mIncFs->openMount(root);
1313 if (!control) {
1314 LOG(INFO) << "failed to open mount " << root;
1315 return;
1316 }
1317
1318 auto mountRecord =
1319 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1320 path::join(root, constants().infoMdName));
1321 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1322 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1323 return;
1324 }
1325
1326 auto mountId = mountRecord.storage().id();
1327 mNextId = std::max(mNextId, mountId + 1);
1328
1329 DataLoaderParamsParcel dataLoaderParams;
1330 {
1331 const auto& loader = mountRecord.loader();
1332 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1333 dataLoaderParams.packageName = loader.package_name();
1334 dataLoaderParams.className = loader.class_name();
1335 dataLoaderParams.arguments = loader.arguments();
1336 }
1337
1338 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1339 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001340 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001341
Alex Buynytskyy04035452020-06-06 20:15:58 -07001342 // Check if marker file present.
1343 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001344 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001345 }
1346
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001347 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1348 auto d = openDir(root);
1349 while (auto e = ::readdir(d.get())) {
1350 if (e->d_type == DT_REG) {
1351 auto name = std::string_view(e->d_name);
1352 if (name.starts_with(constants().mountpointMdPrefix)) {
1353 permanentBindPoints
1354 .emplace_back(name,
1355 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1356 ifs->control,
1357 path::join(root,
1358 name)));
1359 if (permanentBindPoints.back().second.dest_path().empty() ||
1360 permanentBindPoints.back().second.source_subdir().empty()) {
1361 permanentBindPoints.pop_back();
1362 mIncFs->unlink(ifs->control, path::join(root, name));
1363 } else {
1364 LOG(INFO) << "Permanent bind record: '"
1365 << permanentBindPoints.back().second.source_subdir() << "'->'"
1366 << permanentBindPoints.back().second.dest_path() << "'";
1367 }
1368 }
1369 } else if (e->d_type == DT_DIR) {
1370 if (e->d_name == "."sv || e->d_name == ".."sv) {
1371 continue;
1372 }
1373 auto name = std::string_view(e->d_name);
1374 if (name.starts_with(constants().storagePrefix)) {
1375 int storageId;
1376 const auto res =
1377 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1378 name.data() + name.size(), storageId);
1379 if (res.ec != std::errc{} || *res.ptr != '_') {
1380 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1381 << "' for mount " << expectedRoot;
1382 continue;
1383 }
1384 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1385 if (!inserted) {
1386 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1387 << " for mount " << expectedRoot;
1388 continue;
1389 }
1390 ifs->storages.insert_or_assign(storageId,
1391 IncFsMount::Storage{path::join(root, name)});
1392 mNextId = std::max(mNextId, storageId + 1);
1393 }
1394 }
1395 }
1396
1397 if (ifs->storages.empty()) {
1398 LOG(WARNING) << "No valid storages in mount " << root;
1399 return;
1400 }
1401
1402 // now match the mounted directories with what we expect to have in the metadata
1403 {
1404 std::unique_lock l(mLock, std::defer_lock);
1405 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1406 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1407 [&, bindRecord = bindRecord](auto&& bind) {
1408 return bind.second == bindRecord.dest_path() &&
1409 path::join(root, bind.first) ==
1410 bindRecord.source_subdir();
1411 });
1412 if (mountedIt != binds.end()) {
1413 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1414 << " to mount " << mountedIt->first;
1415 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1416 std::move(*bindRecord.mutable_source_subdir()),
1417 std::move(*bindRecord.mutable_dest_path()),
1418 BindKind::Permanent);
1419 if (mountedIt != binds.end() - 1) {
1420 std::iter_swap(mountedIt, binds.end() - 1);
1421 }
1422 binds = binds.first(binds.size() - 1);
1423 } else {
1424 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1425 << ", mounting";
1426 // doesn't exist - try mounting back
1427 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1428 std::move(*bindRecord.mutable_source_subdir()),
1429 std::move(*bindRecord.mutable_dest_path()),
1430 BindKind::Permanent, l)) {
1431 mIncFs->unlink(ifs->control, metadataFile);
1432 }
1433 }
1434 }
1435 }
1436
1437 // if anything stays in |binds| those are probably temporary binds; system restarted since
1438 // they were mounted - so let's unmount them all.
1439 for (auto&& [source, target] : binds) {
1440 if (source.empty()) {
1441 continue;
1442 }
1443 mVold->unmountIncFs(std::string(target));
1444 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001445 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001446
1447 if (ifs->bindPoints.empty()) {
1448 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1449 deleteStorage(*ifs);
1450 return;
1451 }
1452
1453 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1454 CHECK(ifs->dataLoaderStub);
1455
1456 mountedRootNames.insert(path::basename(ifs->root));
1457
1458 // not locking here at all: we're still in the constructor, no other calls can happen
1459 mMounts[ifs->mountId] = std::move(ifs);
1460 });
1461
1462 return mountedRootNames;
1463}
1464
1465void IncrementalService::mountExistingImages(
1466 const std::unordered_set<std::string_view>& mountedRootNames) {
1467 auto dir = openDir(mIncrementalDir);
1468 if (!dir) {
1469 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1470 return;
1471 }
1472 while (auto entry = ::readdir(dir.get())) {
1473 if (entry->d_type != DT_DIR) {
1474 continue;
1475 }
1476 std::string_view name = entry->d_name;
1477 if (!name.starts_with(constants().mountKeyPrefix)) {
1478 continue;
1479 }
1480 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001481 continue;
1482 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001483 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001484 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001485 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001486 }
1487 }
1488}
1489
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001490bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001491 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001492 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001493
Songchun Fan3c82a302019-11-29 14:23:45 -08001494 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001495 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001496 if (!status.isOk()) {
1497 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1498 return false;
1499 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001500
1501 int cmd = controlParcel.cmd.release().release();
1502 int pendingReads = controlParcel.pendingReads.release().release();
1503 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001504 int blocksWritten =
1505 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1506 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001507
1508 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1509
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001510 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1511 path::join(mountTarget, constants().infoMdName));
1512 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001513 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1514 return false;
1515 }
1516
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001517 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001518 mNextId = std::max(mNextId, ifs->mountId + 1);
1519
Alex Buynytskyy04035452020-06-06 20:15:58 -07001520 // Check if marker file present.
1521 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001522 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001523 }
1524
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001525 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001526 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001527 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001528 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001529 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001530 dataLoaderParams.packageName = loader.package_name();
1531 dataLoaderParams.className = loader.class_name();
1532 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001533 }
1534
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001535 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001536 CHECK(ifs->dataLoaderStub);
1537
Songchun Fan3c82a302019-11-29 14:23:45 -08001538 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001539 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001540 while (auto e = ::readdir(d.get())) {
1541 if (e->d_type == DT_REG) {
1542 auto name = std::string_view(e->d_name);
1543 if (name.starts_with(constants().mountpointMdPrefix)) {
1544 bindPoints.emplace_back(name,
1545 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1546 ifs->control,
1547 path::join(mountTarget,
1548 name)));
1549 if (bindPoints.back().second.dest_path().empty() ||
1550 bindPoints.back().second.source_subdir().empty()) {
1551 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001552 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001553 }
1554 }
1555 } else if (e->d_type == DT_DIR) {
1556 if (e->d_name == "."sv || e->d_name == ".."sv) {
1557 continue;
1558 }
1559 auto name = std::string_view(e->d_name);
1560 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001561 int storageId;
1562 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1563 name.data() + name.size(), storageId);
1564 if (res.ec != std::errc{} || *res.ptr != '_') {
1565 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1566 << root;
1567 continue;
1568 }
1569 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001570 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001571 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001572 << " for mount " << root;
1573 continue;
1574 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001575 ifs->storages.insert_or_assign(storageId,
1576 IncFsMount::Storage{
1577 path::join(root, constants().mount, name)});
1578 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001579 }
1580 }
1581 }
1582
1583 if (ifs->storages.empty()) {
1584 LOG(WARNING) << "No valid storages in mount " << root;
1585 return false;
1586 }
1587
1588 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001589 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001590 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001591 for (auto&& bp : bindPoints) {
1592 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1593 std::move(*bp.second.mutable_source_subdir()),
1594 std::move(*bp.second.mutable_dest_path()),
1595 BindKind::Permanent, l);
1596 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001597 }
1598
1599 if (bindCount == 0) {
1600 LOG(WARNING) << "No valid bind points for mount " << root;
1601 deleteStorage(*ifs);
1602 return false;
1603 }
1604
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001605 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001606 mMounts[ifs->mountId] = std::move(ifs);
1607 return true;
1608}
1609
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001610void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001611 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001612 while (mRunning.load(std::memory_order_relaxed)) {
1613 mLooper->pollAll(kTimeoutMsecs);
1614 }
1615}
1616
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001617IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001618 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001619 const DataLoaderStatusListener* statusListener,
1620 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001621 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001622 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1623 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001624 return ifs.dataLoaderStub;
1625}
1626
1627void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001628 const DataLoaderStatusListener* statusListener,
1629 StorageHealthCheckParams&& healthCheckParams,
1630 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001631 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001632 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001633 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001634 }
1635
Songchun Fan3c82a302019-11-29 14:23:45 -08001636 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001637 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001638 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1639 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1640 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001641 if (ifs.control.blocksWritten() >= 0) {
1642 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1643 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001644 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001645
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001646 ifs.dataLoaderStub =
1647 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001648 statusListener, std::move(healthCheckParams), healthListener,
1649 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001650}
1651
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001652template <class Duration>
1653static long elapsedMcs(Duration start, Duration end) {
1654 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1655}
1656
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001657template <class Duration>
1658static constexpr auto castToMs(Duration d) {
1659 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1660}
1661
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001662// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001663// Lib files should be placed next to the APK file in the following matter:
1664// Example:
1665// /path/to/base.apk
1666// /path/to/lib/arm/first.so
1667// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001668bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1669 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001670 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001671 auto start = Clock::now();
1672
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001673 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001674 if (!ifs) {
1675 LOG(ERROR) << "Invalid storage " << storage;
1676 return false;
1677 }
1678
Songchun Fanc8975312020-07-13 12:14:37 -07001679 const auto targetLibPathRelativeToStorage =
1680 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1681 libDirRelativePath);
1682
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001683 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001684 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1685 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001686 << " errno: " << res;
1687 return false;
1688 }
1689
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001690 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001691 ZipArchiveHandle zipFileHandle;
1692 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001693 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1694 return false;
1695 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001696
1697 // Need a shared pointer: will be passing it into all unpacking jobs.
1698 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001699 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001700 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001701 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001702 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1703 return false;
1704 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001705 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001706 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1707
1708 auto openZipTs = Clock::now();
1709
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001710 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1711 incfs::FileId sourceId;
1712 if (mapFiles) {
1713 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1714 if (!incfs::isValidFileId(sourceId)) {
1715 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1716 << "', mapping disabled";
1717 mapFiles = false;
1718 }
1719 }
1720
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001721 std::vector<Job> jobQueue;
1722 ZipEntry entry;
1723 std::string_view fileName;
1724 while (!Next(cookie, &entry, &fileName)) {
1725 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001726 continue;
1727 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001728
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001729 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001730 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001731
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001732 if (!extractNativeLibs) {
1733 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001734 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001735 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1736 return false;
1737 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001738 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001739 LOG(WARNING) << "Library " << fileName
1740 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1741 << entry.offset;
1742 return false;
1743 }
1744 continue;
1745 }
1746
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001747 auto startFileTs = Clock::now();
1748
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001749 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001750 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001751 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001752 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001753 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001754 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001755 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1756 << "; skipping extraction, spent "
1757 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1758 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001759 continue;
1760 }
1761
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001762 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1763 incfs::NewMappedFileParams mappedFileParams = {
1764 .sourceId = sourceId,
1765 .sourceOffset = entry.offset,
1766 .size = entry.uncompressed_length,
1767 };
1768
1769 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1770 mappedFileParams);
1771 res == 0) {
1772 if (perfLoggingEnabled()) {
1773 auto doneTs = Clock::now();
1774 LOG(INFO) << "incfs: Mapped " << libName << ": "
1775 << elapsedMcs(startFileTs, doneTs) << "mcs";
1776 }
1777 continue;
1778 } else {
1779 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1780 << "; falling back to full extraction";
1781 }
1782 }
1783
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001784 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001785 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001786 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001787 .signature = {},
1788 // Metadata of the new lib file is its relative path
1789 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1790 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001791 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001792 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001793 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001794 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001795 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001796 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001797 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001798
1799 auto makeFileTs = Clock::now();
1800
Songchun Fanafaf6e92020-03-18 14:12:20 -07001801 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001802 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001803 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001804 LOG(INFO) << "incfs: Extracted " << libName
1805 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001806 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001807 continue;
1808 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001809
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001810 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1811 libFileId, libPath = std::move(targetLibPath),
1812 makeFileTs]() mutable {
1813 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001814 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001815
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001816 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001817 auto prepareJobTs = Clock::now();
1818 LOG(INFO) << "incfs: Processed " << libName << ": "
1819 << elapsedMcs(startFileTs, prepareJobTs)
1820 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1821 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001822 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001823 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001824
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001825 auto processedTs = Clock::now();
1826
1827 if (!jobQueue.empty()) {
1828 {
1829 std::lock_guard lock(mJobMutex);
1830 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001831 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001832 if (existingJobs.empty()) {
1833 existingJobs = std::move(jobQueue);
1834 } else {
1835 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1836 std::move_iterator(jobQueue.end()));
1837 }
1838 }
1839 }
1840 mJobCondition.notify_all();
1841 }
1842
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001843 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001844 auto end = Clock::now();
1845 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1846 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1847 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001848 << " make files: " << elapsedMcs(openZipTs, processedTs)
1849 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001850 }
1851
1852 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001853}
1854
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001855void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1856 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001857 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001858 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001859 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001860 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001861 return;
1862 }
1863
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001864 auto startedTs = Clock::now();
1865
1866 // Write extracted data to new file
1867 // NOTE: don't zero-initialize memory, it may take a while for nothing
1868 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1869 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001870 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001871 return;
1872 }
1873
1874 auto extractFileTs = Clock::now();
1875
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001876 if (setFileContent(ifs, libFileId, debugLibPath,
1877 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001878 return;
1879 }
1880
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001881 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001882 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001883 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1884 << entry.compressed_length << " -> " << entry.uncompressed_length
1885 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001886 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1887 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001888 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001889 }
1890}
1891
1892bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001893 struct WaitPrinter {
1894 const Clock::time_point startTs = Clock::now();
1895 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001896 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001897 const auto endTs = Clock::now();
1898 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1899 << elapsedMcs(startTs, endTs) << "mcs";
1900 }
1901 }
1902 } waitPrinter;
1903
1904 MountId mount;
1905 {
1906 auto ifs = getIfs(storage);
1907 if (!ifs) {
1908 return true;
1909 }
1910 mount = ifs->mountId;
1911 }
1912
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001913 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001914 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001915 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001916 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001917 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001918 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001919}
1920
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001921int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1922 std::string_view debugFilePath,
1923 std::span<const uint8_t> data) const {
1924 auto startTs = Clock::now();
1925
1926 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1927 if (!writeFd.ok()) {
1928 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1929 << " errno: " << writeFd.get();
1930 return writeFd.get();
1931 }
1932
1933 const auto dataLength = data.size();
1934
1935 auto openFileTs = Clock::now();
1936 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1937 std::vector<IncFsDataBlock> instructions(numBlocks);
1938 for (int i = 0; i < numBlocks; i++) {
1939 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1940 instructions[i] = IncFsDataBlock{
1941 .fileFd = writeFd.get(),
1942 .pageIndex = static_cast<IncFsBlockIndex>(i),
1943 .compression = INCFS_COMPRESSION_KIND_NONE,
1944 .kind = INCFS_BLOCK_KIND_DATA,
1945 .dataSize = static_cast<uint32_t>(blockSize),
1946 .data = reinterpret_cast<const char*>(data.data()),
1947 };
1948 data = data.subspan(blockSize);
1949 }
1950 auto prepareInstsTs = Clock::now();
1951
1952 size_t res = mIncFs->writeBlocks(instructions);
1953 if (res != instructions.size()) {
1954 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1955 return res;
1956 }
1957
1958 if (perfLoggingEnabled()) {
1959 auto endTs = Clock::now();
1960 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1961 << " bytes): " << elapsedMcs(startTs, endTs)
1962 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1963 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1964 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1965 }
1966
1967 return 0;
1968}
1969
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07001970incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
1971 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001972 std::unique_lock l(mLock);
1973 const auto ifs = getIfsLocked(storage);
1974 if (!ifs) {
1975 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07001976 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001977 }
1978 const auto storageInfo = ifs->storages.find(storage);
1979 if (storageInfo == ifs->storages.end()) {
1980 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07001981 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001982 }
1983 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07001984 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001985}
1986
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07001987incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
1988 const auto ifs = getIfs(storage);
1989 if (!ifs) {
1990 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
1991 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001992 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07001993 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001994}
1995
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001996IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001997 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07001998 std::unique_lock l(mLock);
1999 const auto ifs = getIfsLocked(storage);
2000 if (!ifs) {
2001 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002002 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002003 }
2004 const auto storageInfo = ifs->storages.find(storage);
2005 if (storageInfo == ifs->storages.end()) {
2006 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002007 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002008 }
2009 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002010 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002011}
2012
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002013IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002014 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002015 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2016 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002017 const auto [filledBlocksCount, totalBlocksCount] =
2018 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002019 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2020 filledBlocksCount == -ENOENT) {
2021 // a kind of a file that's not really being loaded, e.g. a mapped range
2022 // an older IncFS used to return ENOENT in this case, so handle it the same way
2023 return true;
2024 }
Songchun Fan374f7652020-08-20 08:40:29 -07002025 if (filledBlocksCount < 0) {
2026 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002027 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002028 error = filledBlocksCount;
2029 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002030 }
2031 totalBlocks += totalBlocksCount;
2032 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002033 return true;
2034 });
Songchun Fan374f7652020-08-20 08:40:29 -07002035
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002036 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002037}
2038
Songchun Fana7098592020-09-03 11:45:53 -07002039bool IncrementalService::updateLoadingProgress(
2040 StorageId storage, const StorageLoadingProgressListener& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002041 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002042 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002043 // Failed to get progress from incfs, abort.
2044 return false;
2045 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002046 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2047 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002048 // Stop updating progress once it is fully loaded
2049 return true;
2050 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002051 addTimedJob(*mProgressUpdateJobQueue, storage,
2052 Constants::progressUpdateInterval /* repeat after 1s */,
Songchun Fana7098592020-09-03 11:45:53 -07002053 [storage, progressListener, this]() {
2054 updateLoadingProgress(storage, progressListener);
2055 });
2056 return true;
2057}
2058
2059bool IncrementalService::registerLoadingProgressListener(
2060 StorageId storage, const StorageLoadingProgressListener& progressListener) {
2061 return updateLoadingProgress(storage, progressListener);
2062}
2063
2064bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2065 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2066}
2067
Songchun Fan2570ec02020-10-08 17:22:33 -07002068bool IncrementalService::registerStorageHealthListener(
2069 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
2070 const StorageHealthListener& healthListener) {
2071 DataLoaderStubPtr dataLoaderStub;
2072 {
2073 std::unique_lock l(mLock);
2074 const auto& ifs = getIfsLocked(storage);
2075 if (!ifs) {
2076 return false;
2077 }
2078 dataLoaderStub = ifs->dataLoaderStub;
2079 if (!dataLoaderStub) {
2080 return false;
2081 }
2082 }
2083 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
2084 return true;
2085}
2086
2087void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
2088 StorageHealthCheckParams invalidCheckParams;
2089 invalidCheckParams.blockedTimeoutMs = -1;
2090 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
2091}
2092
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002093bool IncrementalService::perfLoggingEnabled() {
2094 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2095 return enabled;
2096}
2097
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002098void IncrementalService::runJobProcessing() {
2099 for (;;) {
2100 std::unique_lock lock(mJobMutex);
2101 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2102 if (!mRunning) {
2103 return;
2104 }
2105
2106 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002107 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002108 auto queue = std::move(it->second);
2109 mJobQueue.erase(it);
2110 lock.unlock();
2111
2112 for (auto&& job : queue) {
2113 job();
2114 }
2115
2116 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002117 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002118 lock.unlock();
2119 mJobCondition.notify_all();
2120 }
2121}
2122
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002123void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002124 sp<IAppOpsCallback> listener;
2125 {
2126 std::unique_lock lock{mCallbacksLock};
2127 auto& cb = mCallbackRegistered[packageName];
2128 if (cb) {
2129 return;
2130 }
2131 cb = new AppOpsListener(*this, packageName);
2132 listener = cb;
2133 }
2134
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002135 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2136 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002137}
2138
2139bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2140 sp<IAppOpsCallback> listener;
2141 {
2142 std::unique_lock lock{mCallbacksLock};
2143 auto found = mCallbackRegistered.find(packageName);
2144 if (found == mCallbackRegistered.end()) {
2145 return false;
2146 }
2147 listener = found->second;
2148 mCallbackRegistered.erase(found);
2149 }
2150
2151 mAppOpsManager->stopWatchingMode(listener);
2152 return true;
2153}
2154
2155void IncrementalService::onAppOpChanged(const std::string& packageName) {
2156 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002157 return;
2158 }
2159
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002160 std::vector<IfsMountPtr> affected;
2161 {
2162 std::lock_guard l(mLock);
2163 affected.reserve(mMounts.size());
2164 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002165 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002166 affected.push_back(ifs);
2167 }
2168 }
2169 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002170 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002171 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002172 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002173}
2174
Songchun Fana7098592020-09-03 11:45:53 -07002175bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2176 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002177 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002178 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002179 }
Songchun Fana7098592020-09-03 11:45:53 -07002180 timedQueue.addJob(id, after, std::move(what));
2181 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002182}
2183
Songchun Fana7098592020-09-03 11:45:53 -07002184bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002185 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002186 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002187 }
Songchun Fana7098592020-09-03 11:45:53 -07002188 timedQueue.removeJobs(id);
2189 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002190}
2191
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002192void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
2193 const auto duration = getMillsSinceOldestPendingRead(storageId);
2194 if (duration >= 0) {
2195 const auto kMetricsMillisSinceOldestPendingRead =
2196 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2197 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2198 }
2199}
2200
2201long IncrementalService::getMillsSinceOldestPendingRead(StorageId storageId) {
2202 std::unique_lock l(mLock);
2203 const auto ifs = getIfsLocked(storageId);
2204 if (!ifs) {
2205 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, invalid storageId: " << storageId;
2206 return -EINVAL;
2207 }
2208 if (!ifs->dataLoaderStub) {
2209 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, no data loader: " << storageId;
2210 return -EINVAL;
2211 }
2212 return ifs->dataLoaderStub->elapsedMsSinceOldestPendingRead();
2213}
2214
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002215IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
2216 DataLoaderParamsParcel&& params,
2217 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002218 const DataLoaderStatusListener* statusListener,
2219 StorageHealthCheckParams&& healthCheckParams,
2220 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002221 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002222 : mService(service),
2223 mId(id),
2224 mParams(std::move(params)),
2225 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002226 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
2227 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002228 mHealthPath(std::move(healthPath)),
2229 mHealthCheckParams(std::move(healthCheckParams)) {
2230 if (mHealthListener) {
2231 if (!isHealthParamsValid()) {
2232 mHealthListener = {};
2233 }
2234 } else {
2235 // Disable advanced health check statuses.
2236 mHealthCheckParams.blockedTimeoutMs = -1;
2237 }
2238 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002239}
2240
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002241IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002242 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002243 cleanupResources();
2244 }
2245}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002246
2247void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002248 auto now = Clock::now();
2249 {
2250 std::unique_lock lock(mMutex);
2251 mHealthPath.clear();
2252 unregisterFromPendingReads();
2253 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002254 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002255 }
2256
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002257 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002258
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002259 {
2260 std::unique_lock lock(mMutex);
2261 mParams = {};
2262 mControl = {};
2263 mHealthControl = {};
2264 mHealthListener = {};
2265 mStatusCondition.wait_until(lock, now + 60s, [this] {
2266 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2267 });
2268 mStatusListener = {};
2269 mId = kInvalidStorageId;
2270 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002271}
2272
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002273sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2274 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002275 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002276 if (!status.isOk()) {
2277 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2278 return {};
2279 }
2280 if (!dataloader) {
2281 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2282 return {};
2283 }
2284 return dataloader;
2285}
2286
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002287bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2288 return (params().packageName == Constants::systemPackage);
2289}
2290
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002291bool IncrementalService::DataLoaderStub::requestCreate() {
2292 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2293}
2294
2295bool IncrementalService::DataLoaderStub::requestStart() {
2296 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2297}
2298
2299bool IncrementalService::DataLoaderStub::requestDestroy() {
2300 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2301}
2302
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002303bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002304 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002305 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002306 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002307 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002308 return fsmStep();
2309}
2310
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002311void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002312 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002313 mTargetStatus = status;
2314 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002315 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002316 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002317}
2318
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002319std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002320 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002321
2322 const auto now = mService.mClock->now();
2323 const bool healthy = (mPreviousBindDelay == 0ms);
2324
2325 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2326 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2327 LOG(INFO) << "Binding still in progress. "
2328 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
2329 : "Already unhealthy, don't do anything.");
2330 // Binding still in progress.
2331 if (!healthy) {
2332 // Already unhealthy, don't do anything.
2333 return {};
2334 }
2335 // The DL is healthy/freshly bound, ok to retry for a few times.
2336 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2337 // Still within grace period.
2338 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2339 // Retry interval passed, retrying.
2340 mCurrentStatusTs = now;
2341 mPreviousBindDelay = 0ms;
2342 return 0ms;
2343 }
2344 return {};
2345 }
2346 // fallthrough, mark as unhealthy, and retry with delay
2347 }
2348
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002349 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002350 mPreviousBindTs = now;
2351
2352 const auto nonCrashingInterval = std::max(castToMs(now - previousBindTs), 100ms);
2353 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2354 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2355 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002356 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002357 }
2358
2359 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2360 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2361
2362 const auto bindDelayMs =
2363 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2364 maxBindDelayMs)
2365 .count();
2366 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2367 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2368 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002369 return mPreviousBindDelay;
2370}
2371
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002372bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002373 const auto maybeBindDelay = needToBind();
2374 if (!maybeBindDelay) {
2375 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2376 return true;
2377 }
2378 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002379 if (bindDelay > 1s) {
2380 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
2381 << bindDelay.count() / 1000 << "s";
2382 }
2383
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002384 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002385 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2386 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002387 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002388 const bool healthy = (bindDelay == 0ms);
2389 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2390 << (healthy ? ", retrying." : "");
2391
2392 // Internal error, retry for healthy/new DLs.
2393 // Let needToBind migrate it to unhealthy after too many retries.
2394 if (healthy) {
2395 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2396 [this]() { fsmStep(); })) {
2397 // Mark as binding so that we know it's not the DL's fault.
2398 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2399 return true;
2400 }
2401 }
2402
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002403 return false;
2404 }
2405 return true;
2406}
2407
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002408bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002409 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002410 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002411 return false;
2412 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002413 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002414 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002415 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002416 return false;
2417 }
2418 return true;
2419}
2420
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002421bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002422 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002423 if (!dataloader) {
2424 return false;
2425 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002426 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002427 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002428 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002429 return false;
2430 }
2431 return true;
2432}
2433
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002434bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002435 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002436}
2437
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002438bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002439 if (!isValid()) {
2440 return false;
2441 }
2442
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002443 int currentStatus;
2444 int targetStatus;
2445 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002446 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002447 currentStatus = mCurrentStatus;
2448 targetStatus = mTargetStatus;
2449 }
2450
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002451 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002452
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002453 if (currentStatus == targetStatus) {
2454 return true;
2455 }
2456
2457 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002458 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2459 // Do nothing, this is a reset state.
2460 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002461 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002462 switch (currentStatus) {
2463 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2464 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2465 return true;
2466 default:
2467 return destroy();
2468 }
2469 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002470 }
2471 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2472 switch (currentStatus) {
2473 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2474 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2475 return start();
2476 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002477 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002478 }
2479 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2480 switch (currentStatus) {
2481 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002482 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002483 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002484 return bind();
2485 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002486 return create();
2487 }
2488 break;
2489 default:
2490 LOG(ERROR) << "Invalid target status: " << targetStatus
2491 << ", current status: " << currentStatus;
2492 break;
2493 }
2494 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002495}
2496
2497binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002498 if (!isValid()) {
2499 return binder::Status::
2500 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2501 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002502 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002503 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2504 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002505 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2506 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002507 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2508 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2509 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2510 [this, newStatus]() { setCurrentStatus(newStatus); });
2511 return binder::Status::ok();
2512 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002513
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002514 setCurrentStatus(newStatus);
2515 return binder::Status::ok();
2516}
2517
2518void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002519 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002520 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002521 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002522 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002523 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002524 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002525 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002526
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002527 oldStatus = mCurrentStatus;
2528 targetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002529 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002530
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002531 // Change the status.
2532 mCurrentStatus = newStatus;
2533 mCurrentStatusTs = mService.mClock->now();
2534
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002535 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2536 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002537 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2538 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002539 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002540 }
2541
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002542 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002543 << newStatus << " (target " << targetStatus << ")";
2544
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002545 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002546 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002547 }
2548
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002549 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002550
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002551 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002552}
2553
Songchun Fan33093982020-09-10 13:12:39 -07002554binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2555 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002556 if (!isValid()) {
2557 return binder::Status::
2558 fromServiceSpecificError(-EINVAL,
2559 "reportStreamHealth came to invalid DataLoaderStub");
2560 }
2561 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002562 LOG(ERROR) << "reportStreamHealth: mount ID mismatch: expected " << id()
2563 << ", but got: " << mountId;
Songchun Fan2570ec02020-10-08 17:22:33 -07002564 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2565 }
2566 {
2567 std::lock_guard lock(mMutex);
2568 mStreamStatus = newStatus;
2569 }
Songchun Fan33093982020-09-10 13:12:39 -07002570 return binder::Status::ok();
2571}
2572
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002573bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2574 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2575 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002576}
2577
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002578void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002579 int healthStatus) {
2580 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2581 if (healthListener) {
2582 healthListener->onHealthStatus(id(), healthStatus);
2583 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002584}
2585
Songchun Fan2570ec02020-10-08 17:22:33 -07002586static int adjustHealthStatus(int healthStatus, int streamStatus) {
2587 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2588 // everything is good; no need to change status
2589 return healthStatus;
2590 }
2591 int newHeathStatus = healthStatus;
2592 switch (streamStatus) {
2593 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2594 // storage is limited and storage not healthy
2595 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2596 break;
2597 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2598 // fall through
2599 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2600 // fall through
2601 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2602 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2603 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2604 }
2605 // pending/blocked status due to transportation issues is not regarded as unhealthy
2606 break;
2607 default:
2608 break;
2609 }
2610 return newHeathStatus;
2611}
2612
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002613void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2614 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002615
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002616 int healthStatusToReport = -1;
2617 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002618
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002619 {
2620 std::unique_lock lock(mMutex);
2621 unregisterFromPendingReads();
2622
2623 healthListener = mHealthListener;
2624
2625 // Healthcheck depends on timestamp of the oldest pending read.
2626 // 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 -07002627 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2628 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002629 const auto now = Clock::now();
2630 const auto kernelTsUs = getOldestPendingReadTs();
2631 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002632 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2633 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002634 mHealthBase = {now, kernelTsUs};
2635 }
2636
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002637 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2638 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002639 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2640 registerForPendingReads();
2641 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2642 lock.unlock();
2643 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002644 return;
2645 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002646
2647 resetHealthControl();
2648
2649 // Always make sure the data loader is started.
2650 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2651
2652 // Skip any further processing if health check params are invalid.
2653 if (!isHealthParamsValid()) {
2654 LOG(DEBUG) << id()
2655 << ": Skip any further processing if health check params are invalid.";
2656 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2657 lock.unlock();
2658 onHealthStatus(healthListener, healthStatusToReport);
2659 // Triggering data loader start. This is a one-time action.
2660 fsmStep();
2661 return;
2662 }
2663
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002664 // Don't schedule timer job less than 500ms in advance.
2665 static constexpr auto kTolerance = 500ms;
2666
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002667 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2668 const auto unhealthyTimeout =
2669 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2670 const auto unhealthyMonitoring =
2671 std::max(1000ms,
2672 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2673
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002674 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002675
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002676 Milliseconds checkBackAfter;
2677 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002678 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002679 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002680 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002681 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002682 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002683 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002684 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2685 } else {
2686 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002687 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002688 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2689 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002690 // Adjust health status based on stream status
2691 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002692 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002693 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002694 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2695 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002696 }
2697
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002698 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002699 if (healthStatusToReport != -1) {
2700 onHealthStatus(healthListener, healthStatusToReport);
2701 }
2702
2703 fsmStep();
2704}
2705
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002706Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2707 BootClockTsUs kernelTsUs) {
2708 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2709 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2710 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2711}
2712
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002713const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2714 if (mHealthPath.empty()) {
2715 resetHealthControl();
2716 return mHealthControl;
2717 }
2718 if (mHealthControl.pendingReads() < 0) {
2719 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2720 }
2721 if (mHealthControl.pendingReads() < 0) {
2722 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2723 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2724 << mHealthControl.logs() << ")";
2725 }
2726 return mHealthControl;
2727}
2728
2729void IncrementalService::DataLoaderStub::resetHealthControl() {
2730 mHealthControl = {};
2731}
2732
2733BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2734 auto result = kMaxBootClockTsUs;
2735
2736 const auto& control = initializeHealthControl();
2737 if (control.pendingReads() < 0) {
2738 return result;
2739 }
2740
Songchun Fan6944f1e2020-11-06 15:24:24 -08002741 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002742 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002743 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002744 // Clear previous pending reads
2745 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002746 return result;
2747 }
2748
2749 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002750 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002751
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002752 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002753}
2754
2755void IncrementalService::DataLoaderStub::registerForPendingReads() {
2756 const auto pendingReadsFd = mHealthControl.pendingReads();
2757 if (pendingReadsFd < 0) {
2758 return;
2759 }
2760
2761 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2762
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002763 mService.mLooper->addFd(
2764 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2765 [](int, int, void* data) -> int {
2766 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002767 self->updateHealthStatus(/*baseline=*/true);
2768 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002769 },
2770 this);
2771 mService.mLooper->wake();
2772}
2773
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002774BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2775 auto result = kMaxBootClockTsUs;
2776 for (auto&& pendingRead : mLastPendingReads) {
2777 result = std::min(result, pendingRead.bootClockTsUs);
2778 }
2779 return result;
2780}
2781
2782long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
2783 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
2784 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
2785 return 0;
2786 }
2787 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
2788}
2789
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002790void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002791 const auto pendingReadsFd = mHealthControl.pendingReads();
2792 if (pendingReadsFd < 0) {
2793 return;
2794 }
2795
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002796 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2797
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002798 mService.mLooper->removeFd(pendingReadsFd);
2799 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002800}
2801
Songchun Fan2570ec02020-10-08 17:22:33 -07002802void IncrementalService::DataLoaderStub::setHealthListener(
2803 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2804 std::lock_guard lock(mMutex);
2805 mHealthCheckParams = std::move(healthCheckParams);
2806 if (healthListener == nullptr) {
2807 // reset listener and params
2808 mHealthListener = {};
2809 } else {
2810 mHealthListener = *healthListener;
2811 }
2812}
2813
Songchun Fan6944f1e2020-11-06 15:24:24 -08002814static std::string toHexString(const RawMetadata& metadata) {
2815 int n = metadata.size();
2816 std::string res(n * 2, '\0');
2817 // Same as incfs::toString(fileId)
2818 static constexpr char kHexChar[] = "0123456789abcdef";
2819 for (int i = 0; i < n; ++i) {
2820 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2821 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2822 }
2823 return res;
2824}
2825
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002826void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002827 dprintf(fd, " dataLoader: {\n");
2828 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002829 dprintf(fd, " currentStatusTs: %lldmcs\n",
2830 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002831 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2832 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002833 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002834 dprintf(fd, " health: {\n");
2835 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2836 dprintf(fd, " base: %lldmcs (%lld)\n",
2837 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2838 (long long)mHealthBase.kernelTsUs);
2839 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2840 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2841 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2842 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002843 dprintf(fd, " lastPendingReads: \n");
2844 const auto control = mService.mIncFs->openMount(mHealthPath);
2845 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07002846 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08002847 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2848 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2849 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2850 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2851 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002852 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
2853 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
2854 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002855 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002856 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002857 dprintf(fd, " dataLoaderParams: {\n");
2858 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2859 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2860 dprintf(fd, " className: %s\n", params.className.c_str());
2861 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2862 dprintf(fd, " }\n");
2863 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002864}
2865
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002866void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2867 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002868}
2869
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002870binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2871 bool enableReadLogs, int32_t* _aidl_return) {
2872 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2873 return binder::Status::ok();
2874}
2875
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002876FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2877 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2878}
2879
Songchun Fan3c82a302019-11-29 14:23:45 -08002880} // namespace android::incremental