blob: a88f2b43b9099d40185dbfcea2dd3f3bc001f5a3 [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
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700477StorageId IncrementalService::createStorage(std::string_view mountPoint,
478 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);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700587 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
588 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
589 m.mutable_loader()->set_arguments(std::move(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,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700664 content::pm::DataLoaderParamsParcel dataLoaderParams,
665 DataLoaderStatusListener statusListener,
666 const StorageHealthCheckParams& healthCheckParams,
667 StorageHealthListener healthListener,
668 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800669 // Per Uid timeouts.
670 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700671 setUidReadTimeouts(storageId, std::move(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.
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700687 auto dataLoaderStub =
688 prepareDataLoader(*ifs, std::move(dataLoaderParams), std::move(statusListener),
689 healthCheckParams, std::move(healthListener));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800690 CHECK(dataLoaderStub);
691
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700692 if (dataLoaderStub->isSystemDataLoader()) {
693 // Readlogs from system dataloader (adb) can always be collected.
694 ifs->startLoadingTs = TimePoint::max();
695 } else {
696 // Assign time when installation wants the DL to start streaming.
697 const auto startLoadingTs = mClock->now();
698 ifs->startLoadingTs = startLoadingTs;
699 // Setup a callback to disable the readlogs after max interval.
700 addTimedJob(*mTimedQueue, storageId, Constants::readLogsMaxInterval,
701 [this, storageId, startLoadingTs]() {
702 const auto ifs = getIfs(storageId);
703 if (!ifs) {
704 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
705 << storageId;
706 return;
707 }
708 if (ifs->startLoadingTs != startLoadingTs) {
709 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
710 "installation?): "
711 << storageId;
712 return;
713 }
714 setStorageParams(*ifs, storageId, /*enableReadLogs=*/false);
715 });
716 }
717
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800718 return dataLoaderStub->requestStart();
719}
720
Songchun Fan3c82a302019-11-29 14:23:45 -0800721IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
722 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700723 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800724}
725
726StorageId IncrementalService::findStorageId(std::string_view path) const {
727 std::lock_guard l(mLock);
728 auto it = findStorageLocked(path);
729 if (it == mBindsByPath.end()) {
730 return kInvalidStorageId;
731 }
732 return it->second->second.storage;
733}
734
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800735void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700736 std::unique_lock l(mLock);
737 const auto ifs = getIfsLocked(storageId);
738 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800739 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700740 return;
741 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800742 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700743 return;
744 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800745 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700746 l.unlock();
747
748 const auto metadata = constants().readLogsDisabledMarkerName;
749 if (auto err = mIncFs->makeFile(ifs->control,
750 path::join(ifs->root, constants().mount,
751 constants().readLogsDisabledMarkerName),
752 0777, idFromMetadata(metadata), {})) {
753 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
754 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
755 return;
756 }
757
758 setStorageParams(storageId, /*enableReadLogs=*/false);
759}
760
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700761int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
762 const auto ifs = getIfs(storageId);
763 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700764 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700765 return -EINVAL;
766 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700767 return setStorageParams(*ifs, storageId, enableReadLogs);
768}
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700769
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700770int IncrementalService::setStorageParams(IncFsMount& ifs, StorageId storageId,
771 bool enableReadLogs) {
772 const auto& params = ifs.dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700773 if (enableReadLogs) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700774 if (!ifs.readLogsAllowed()) {
775 LOG(ERROR) << "setStorageParams failed, readlogs disallowed for storageId: "
776 << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700777 return -EPERM;
778 }
779
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800780 // Check loader usage stats permission and apop.
781 if (auto status = mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700782 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700783 !status.isOk()) {
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800784 LOG(ERROR) << " Permission: " << kLoaderUsageStats
785 << " check failed: " << status.toString8();
786 return fromBinderStatus(status);
787 }
788
789 // Check multiuser permission.
790 if (auto status = mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr,
791 params.packageName.c_str());
792 !status.isOk()) {
793 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
794 << " check failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700795 return fromBinderStatus(status);
796 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700797
798 // Check installation time.
799 const auto now = mClock->now();
800 const auto startLoadingTs = ifs.startLoadingTs;
801 if (startLoadingTs <= now && now - startLoadingTs > Constants::readLogsMaxInterval) {
802 LOG(ERROR) << "setStorageParams failed, readlogs can't be enabled at this time, "
803 "storageId: "
804 << storageId;
805 return -EPERM;
806 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700807 }
808
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700809 if (auto status = applyStorageParams(ifs, enableReadLogs); !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700810 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
811 return fromBinderStatus(status);
812 }
813
814 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700815 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700816 }
817
818 return 0;
819}
820
821binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700822 os::incremental::IncrementalFileSystemControlParcel control;
823 control.cmd.reset(dup(ifs.control.cmd()));
824 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700825 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700826 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700827 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700828 }
829
830 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700831 auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800832 if (status.isOk()) {
833 // Store enabled state.
834 ifs.setReadLogsEnabled(enableReadLogs);
835 }
836 return status;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700837}
838
Songchun Fan3c82a302019-11-29 14:23:45 -0800839void IncrementalService::deleteStorage(StorageId storageId) {
840 const auto ifs = getIfs(storageId);
841 if (!ifs) {
842 return;
843 }
844 deleteStorage(*ifs);
845}
846
847void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
848 std::unique_lock l(ifs.lock);
849 deleteStorageLocked(ifs, std::move(l));
850}
851
852void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
853 std::unique_lock<std::mutex>&& ifsLock) {
854 const auto storages = std::move(ifs.storages);
855 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
856 const auto bindPoints = ifs.bindPoints;
857 ifsLock.unlock();
858
859 std::lock_guard l(mLock);
860 for (auto&& [id, _] : storages) {
861 if (id != ifs.mountId) {
862 mMounts.erase(id);
863 }
864 }
865 for (auto&& [path, _] : bindPoints) {
866 mBindsByPath.erase(path);
867 }
868 mMounts.erase(ifs.mountId);
869}
870
871StorageId IncrementalService::openStorage(std::string_view pathInMount) {
872 if (!path::isAbsolute(pathInMount)) {
873 return kInvalidStorageId;
874 }
875
876 return findStorageId(path::normalize(pathInMount));
877}
878
Songchun Fan3c82a302019-11-29 14:23:45 -0800879IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
880 std::lock_guard l(mLock);
881 return getIfsLocked(storage);
882}
883
884const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
885 auto it = mMounts.find(storage);
886 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700887 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700888 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800889 }
890 return it->second;
891}
892
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800893int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
894 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800895 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700896 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800897 return -EINVAL;
898 }
899
900 const auto ifs = getIfs(storage);
901 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700902 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800903 return -EINVAL;
904 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800905
Songchun Fan3c82a302019-11-29 14:23:45 -0800906 std::unique_lock l(ifs->lock);
907 const auto storageInfo = ifs->storages.find(storage);
908 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700909 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800910 return -EINVAL;
911 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700912 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700913 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700914 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700915 return -EINVAL;
916 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800917 l.unlock();
918 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800919 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
920 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800921}
922
923int IncrementalService::unbind(StorageId storage, std::string_view target) {
924 if (!path::isAbsolute(target)) {
925 return -EINVAL;
926 }
927
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700928 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800929
930 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
931 // otherwise there's a chance to unmount something completely unrelated
932 const auto norm = path::normalize(target);
933 std::unique_lock l(mLock);
934 const auto storageIt = mBindsByPath.find(norm);
935 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
936 return -EINVAL;
937 }
938 const auto bindIt = storageIt->second;
939 const auto storageId = bindIt->second.storage;
940 const auto ifs = getIfsLocked(storageId);
941 if (!ifs) {
942 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
943 << " is missing";
944 return -EFAULT;
945 }
946 mBindsByPath.erase(storageIt);
947 l.unlock();
948
949 mVold->unmountIncFs(bindIt->first);
950 std::unique_lock l2(ifs->lock);
951 if (ifs->bindPoints.size() <= 1) {
952 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700953 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800954 } else {
955 const std::string savedFile = std::move(bindIt->second.savedFilename);
956 ifs->bindPoints.erase(bindIt);
957 l2.unlock();
958 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800959 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800960 }
961 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700962
Songchun Fan3c82a302019-11-29 14:23:45 -0800963 return 0;
964}
965
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700966std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700967 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700968 std::string_view path) const {
969 if (!path::isAbsolute(path)) {
970 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700971 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700972 auto normPath = path::normalize(path);
973 if (path::startsWith(normPath, storageIt->second.name)) {
974 return normPath;
975 }
976 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700977 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
978 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700979 return {};
980 }
981 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700982}
983
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700984std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700985 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700986 std::unique_lock l(ifs.lock);
987 const auto storageInfo = ifs.storages.find(storage);
988 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800989 return {};
990 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700991 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800992}
993
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800994int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700995 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -0700996 const auto ifs = getIfs(storage);
997 if (!ifs) {
998 return -EINVAL;
999 }
1000 if (data.size() > params.size) {
1001 LOG(ERROR) << "Bad data size - bigger than file size";
1002 return -EINVAL;
1003 }
1004 if (!data.empty() && data.size() != params.size) {
1005 // Writing a page is an irreversible operation, and it can't be updated with additional
1006 // data later. Check that the last written page is complete, or we may break the file.
1007 if (!isPageAligned(data.size())) {
1008 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001009 return -EINVAL;
1010 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001011 }
1012 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1013 if (normPath.empty()) {
1014 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1015 return -EINVAL;
1016 }
1017 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1018 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1019 return err;
1020 }
1021 if (params.size > 0) {
1022 // Only v2+ incfs supports automatically trimming file over-reserved sizes
1023 if (mIncFs->features() & incfs::Features::v2) {
1024 if (auto err = mIncFs->reserveSpace(ifs->control, normPath, params.size)) {
1025 if (err != -EOPNOTSUPP) {
1026 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1027 (void)mIncFs->unlink(ifs->control, normPath);
1028 return err;
1029 } else {
1030 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1031 "may run out of disk later";
1032 }
1033 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001034 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001035 if (!data.empty()) {
1036 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001037 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001038 return err;
1039 }
1040 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001041 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001042 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001043}
1044
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001045int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001046 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001047 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001048 if (normPath.empty()) {
1049 return -EINVAL;
1050 }
1051 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001052 }
1053 return -EINVAL;
1054}
1055
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001056int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001057 const auto ifs = getIfs(storageId);
1058 if (!ifs) {
1059 return -EINVAL;
1060 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001061 return makeDirs(*ifs, storageId, path, mode);
1062}
1063
1064int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1065 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001066 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1067 if (normPath.empty()) {
1068 return -EINVAL;
1069 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001070 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001071}
1072
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001073int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1074 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001075 std::unique_lock l(mLock);
1076 auto ifsSrc = getIfsLocked(sourceStorageId);
1077 if (!ifsSrc) {
1078 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001079 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001080 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1081 return -EINVAL;
1082 }
1083 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001084 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1085 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001086 if (normOldPath.empty() || normNewPath.empty()) {
1087 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1088 return -EINVAL;
1089 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001090 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1091 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1092 << " to " << newPath << "[" << normNewPath << "]";
1093 return err;
1094 }
1095 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001096}
1097
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001098int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001099 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001100 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001101 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001102 }
1103 return -EINVAL;
1104}
1105
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001106int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1107 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001108 std::string&& target, BindKind kind,
1109 std::unique_lock<std::mutex>& mainLock) {
1110 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001111 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001112 return -EINVAL;
1113 }
1114
1115 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001116 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001117 if (kind != BindKind::Temporary) {
1118 metadata::BindPoint bp;
1119 bp.set_storage_id(storage);
1120 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001121 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001122 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001123 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001124 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001125 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001126 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1127 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1128 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001129 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001130 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001131 return int(node);
1132 }
1133 }
1134
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001135 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1136 std::move(target), kind, mainLock);
1137 if (res) {
1138 mIncFs->unlink(ifs.control, metadataFullPath);
1139 }
1140 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001141}
1142
1143int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001144 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001145 std::string&& target, BindKind kind,
1146 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001147 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001148 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001149 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001150 if (!status.isOk()) {
1151 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1152 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1153 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1154 : status.serviceSpecificErrorCode() == 0
1155 ? -EFAULT
1156 : status.serviceSpecificErrorCode()
1157 : -EIO;
1158 }
1159 }
1160
1161 if (!mainLock.owns_lock()) {
1162 mainLock.lock();
1163 }
1164 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001165 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1166 std::move(target), kind);
1167 return 0;
1168}
1169
1170void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1171 std::string&& metadataName, std::string&& source,
1172 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001173 const auto [it, _] =
1174 ifs.bindPoints.insert_or_assign(target,
1175 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001176 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001177 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001178}
1179
1180RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1181 const auto ifs = getIfs(storage);
1182 if (!ifs) {
1183 return {};
1184 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001185 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001186 if (normPath.empty()) {
1187 return {};
1188 }
1189 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001190}
1191
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001192RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001193 const auto ifs = getIfs(storage);
1194 if (!ifs) {
1195 return {};
1196 }
1197 return mIncFs->getMetadata(ifs->control, node);
1198}
1199
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001200void IncrementalService::setUidReadTimeouts(StorageId storage,
1201 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001202 using microseconds = std::chrono::microseconds;
1203 using milliseconds = std::chrono::milliseconds;
1204
1205 auto maxPendingTimeUs = microseconds(0);
1206 for (const auto& timeouts : perUidReadTimeouts) {
1207 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1208 }
1209 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001210 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001211 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1212 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001213 return;
1214 }
1215
1216 const auto ifs = getIfs(storage);
1217 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001218 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001219 return;
1220 }
1221
1222 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1223 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1224 return;
1225 }
1226
1227 const auto timeout = std::chrono::duration_cast<milliseconds>(maxPendingTimeUs) -
1228 Constants::perUidTimeoutOffset;
1229 updateUidReadTimeouts(storage, Clock::now() + timeout);
1230}
1231
1232void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1233 const auto ifs = getIfs(storage);
1234 if (!ifs) {
1235 return;
1236 }
1237
1238 mIncFs->setUidReadTimeouts(ifs->control, {});
1239}
1240
1241void IncrementalService::updateUidReadTimeouts(StorageId storage, Clock::time_point timeLimit) {
1242 // Reached maximum timeout.
1243 if (Clock::now() >= timeLimit) {
1244 return clearUidReadTimeouts(storage);
1245 }
1246
1247 // Still loading?
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001248 const auto state = isMountFullyLoaded(storage);
1249 if (int(state) < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001250 // Something is wrong, abort.
1251 return clearUidReadTimeouts(storage);
1252 }
1253
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001254 if (state == incfs::LoadingState::Full) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001255 // Fully loaded, check readLogs collection.
1256 const auto ifs = getIfs(storage);
1257 if (!ifs->readLogsEnabled()) {
1258 return clearUidReadTimeouts(storage);
1259 }
1260 }
1261
1262 const auto timeLeft = timeLimit - Clock::now();
1263 if (timeLeft < Constants::progressUpdateInterval) {
1264 // Don't bother.
1265 return clearUidReadTimeouts(storage);
1266 }
1267
1268 addTimedJob(*mTimedQueue, storage, Constants::progressUpdateInterval,
1269 [this, storage, timeLimit]() { updateUidReadTimeouts(storage, timeLimit); });
1270}
1271
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001272std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1273 std::unordered_set<std::string_view> mountedRootNames;
1274 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1275 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1276 for (auto [source, target] : binds) {
1277 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1278 LOG(INFO) << " " << path::join(root, source);
1279 }
1280
1281 // Ensure it's a kind of a mount that's managed by IncrementalService
1282 if (path::basename(root) != constants().mount ||
1283 path::basename(backingDir) != constants().backing) {
1284 return;
1285 }
1286 const auto expectedRoot = path::dirname(root);
1287 if (path::dirname(backingDir) != expectedRoot) {
1288 return;
1289 }
1290 if (path::dirname(expectedRoot) != mIncrementalDir) {
1291 return;
1292 }
1293 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1294 return;
1295 }
1296
1297 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1298
1299 // make sure we clean up the mount if it happens to be a bad one.
1300 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1301 auto cleanupFiles = makeCleanup([&]() {
1302 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1303 IncFsMount::cleanupFilesystem(expectedRoot);
1304 });
1305 auto cleanupMounts = makeCleanup([&]() {
1306 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1307 for (auto&& [_, target] : binds) {
1308 mVold->unmountIncFs(std::string(target));
1309 }
1310 mVold->unmountIncFs(std::string(root));
1311 });
1312
1313 auto control = mIncFs->openMount(root);
1314 if (!control) {
1315 LOG(INFO) << "failed to open mount " << root;
1316 return;
1317 }
1318
1319 auto mountRecord =
1320 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1321 path::join(root, constants().infoMdName));
1322 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1323 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1324 return;
1325 }
1326
1327 auto mountId = mountRecord.storage().id();
1328 mNextId = std::max(mNextId, mountId + 1);
1329
1330 DataLoaderParamsParcel dataLoaderParams;
1331 {
1332 const auto& loader = mountRecord.loader();
1333 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1334 dataLoaderParams.packageName = loader.package_name();
1335 dataLoaderParams.className = loader.class_name();
1336 dataLoaderParams.arguments = loader.arguments();
1337 }
1338
1339 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1340 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001341 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001342
Alex Buynytskyy04035452020-06-06 20:15:58 -07001343 // Check if marker file present.
1344 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001345 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001346 }
1347
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001348 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1349 auto d = openDir(root);
1350 while (auto e = ::readdir(d.get())) {
1351 if (e->d_type == DT_REG) {
1352 auto name = std::string_view(e->d_name);
1353 if (name.starts_with(constants().mountpointMdPrefix)) {
1354 permanentBindPoints
1355 .emplace_back(name,
1356 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1357 ifs->control,
1358 path::join(root,
1359 name)));
1360 if (permanentBindPoints.back().second.dest_path().empty() ||
1361 permanentBindPoints.back().second.source_subdir().empty()) {
1362 permanentBindPoints.pop_back();
1363 mIncFs->unlink(ifs->control, path::join(root, name));
1364 } else {
1365 LOG(INFO) << "Permanent bind record: '"
1366 << permanentBindPoints.back().second.source_subdir() << "'->'"
1367 << permanentBindPoints.back().second.dest_path() << "'";
1368 }
1369 }
1370 } else if (e->d_type == DT_DIR) {
1371 if (e->d_name == "."sv || e->d_name == ".."sv) {
1372 continue;
1373 }
1374 auto name = std::string_view(e->d_name);
1375 if (name.starts_with(constants().storagePrefix)) {
1376 int storageId;
1377 const auto res =
1378 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1379 name.data() + name.size(), storageId);
1380 if (res.ec != std::errc{} || *res.ptr != '_') {
1381 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1382 << "' for mount " << expectedRoot;
1383 continue;
1384 }
1385 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1386 if (!inserted) {
1387 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1388 << " for mount " << expectedRoot;
1389 continue;
1390 }
1391 ifs->storages.insert_or_assign(storageId,
1392 IncFsMount::Storage{path::join(root, name)});
1393 mNextId = std::max(mNextId, storageId + 1);
1394 }
1395 }
1396 }
1397
1398 if (ifs->storages.empty()) {
1399 LOG(WARNING) << "No valid storages in mount " << root;
1400 return;
1401 }
1402
1403 // now match the mounted directories with what we expect to have in the metadata
1404 {
1405 std::unique_lock l(mLock, std::defer_lock);
1406 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1407 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1408 [&, bindRecord = bindRecord](auto&& bind) {
1409 return bind.second == bindRecord.dest_path() &&
1410 path::join(root, bind.first) ==
1411 bindRecord.source_subdir();
1412 });
1413 if (mountedIt != binds.end()) {
1414 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1415 << " to mount " << mountedIt->first;
1416 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1417 std::move(*bindRecord.mutable_source_subdir()),
1418 std::move(*bindRecord.mutable_dest_path()),
1419 BindKind::Permanent);
1420 if (mountedIt != binds.end() - 1) {
1421 std::iter_swap(mountedIt, binds.end() - 1);
1422 }
1423 binds = binds.first(binds.size() - 1);
1424 } else {
1425 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1426 << ", mounting";
1427 // doesn't exist - try mounting back
1428 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1429 std::move(*bindRecord.mutable_source_subdir()),
1430 std::move(*bindRecord.mutable_dest_path()),
1431 BindKind::Permanent, l)) {
1432 mIncFs->unlink(ifs->control, metadataFile);
1433 }
1434 }
1435 }
1436 }
1437
1438 // if anything stays in |binds| those are probably temporary binds; system restarted since
1439 // they were mounted - so let's unmount them all.
1440 for (auto&& [source, target] : binds) {
1441 if (source.empty()) {
1442 continue;
1443 }
1444 mVold->unmountIncFs(std::string(target));
1445 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001446 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001447
1448 if (ifs->bindPoints.empty()) {
1449 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1450 deleteStorage(*ifs);
1451 return;
1452 }
1453
1454 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1455 CHECK(ifs->dataLoaderStub);
1456
1457 mountedRootNames.insert(path::basename(ifs->root));
1458
1459 // not locking here at all: we're still in the constructor, no other calls can happen
1460 mMounts[ifs->mountId] = std::move(ifs);
1461 });
1462
1463 return mountedRootNames;
1464}
1465
1466void IncrementalService::mountExistingImages(
1467 const std::unordered_set<std::string_view>& mountedRootNames) {
1468 auto dir = openDir(mIncrementalDir);
1469 if (!dir) {
1470 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1471 return;
1472 }
1473 while (auto entry = ::readdir(dir.get())) {
1474 if (entry->d_type != DT_DIR) {
1475 continue;
1476 }
1477 std::string_view name = entry->d_name;
1478 if (!name.starts_with(constants().mountKeyPrefix)) {
1479 continue;
1480 }
1481 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001482 continue;
1483 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001484 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001485 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001486 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001487 }
1488 }
1489}
1490
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001491bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001492 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001493 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001494
Songchun Fan3c82a302019-11-29 14:23:45 -08001495 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001496 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001497 if (!status.isOk()) {
1498 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1499 return false;
1500 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001501
1502 int cmd = controlParcel.cmd.release().release();
1503 int pendingReads = controlParcel.pendingReads.release().release();
1504 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001505 int blocksWritten =
1506 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1507 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001508
1509 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1510
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001511 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1512 path::join(mountTarget, constants().infoMdName));
1513 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001514 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1515 return false;
1516 }
1517
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001518 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001519 mNextId = std::max(mNextId, ifs->mountId + 1);
1520
Alex Buynytskyy04035452020-06-06 20:15:58 -07001521 // Check if marker file present.
1522 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001523 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001524 }
1525
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001526 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001527 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001528 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001529 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001530 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001531 dataLoaderParams.packageName = loader.package_name();
1532 dataLoaderParams.className = loader.class_name();
1533 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001534 }
1535
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001536 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001537 CHECK(ifs->dataLoaderStub);
1538
Songchun Fan3c82a302019-11-29 14:23:45 -08001539 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001540 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001541 while (auto e = ::readdir(d.get())) {
1542 if (e->d_type == DT_REG) {
1543 auto name = std::string_view(e->d_name);
1544 if (name.starts_with(constants().mountpointMdPrefix)) {
1545 bindPoints.emplace_back(name,
1546 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1547 ifs->control,
1548 path::join(mountTarget,
1549 name)));
1550 if (bindPoints.back().second.dest_path().empty() ||
1551 bindPoints.back().second.source_subdir().empty()) {
1552 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001553 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001554 }
1555 }
1556 } else if (e->d_type == DT_DIR) {
1557 if (e->d_name == "."sv || e->d_name == ".."sv) {
1558 continue;
1559 }
1560 auto name = std::string_view(e->d_name);
1561 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001562 int storageId;
1563 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1564 name.data() + name.size(), storageId);
1565 if (res.ec != std::errc{} || *res.ptr != '_') {
1566 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1567 << root;
1568 continue;
1569 }
1570 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001571 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001572 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001573 << " for mount " << root;
1574 continue;
1575 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001576 ifs->storages.insert_or_assign(storageId,
1577 IncFsMount::Storage{
1578 path::join(root, constants().mount, name)});
1579 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001580 }
1581 }
1582 }
1583
1584 if (ifs->storages.empty()) {
1585 LOG(WARNING) << "No valid storages in mount " << root;
1586 return false;
1587 }
1588
1589 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001590 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001591 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001592 for (auto&& bp : bindPoints) {
1593 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1594 std::move(*bp.second.mutable_source_subdir()),
1595 std::move(*bp.second.mutable_dest_path()),
1596 BindKind::Permanent, l);
1597 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001598 }
1599
1600 if (bindCount == 0) {
1601 LOG(WARNING) << "No valid bind points for mount " << root;
1602 deleteStorage(*ifs);
1603 return false;
1604 }
1605
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001606 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001607 mMounts[ifs->mountId] = std::move(ifs);
1608 return true;
1609}
1610
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001611void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001612 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001613 while (mRunning.load(std::memory_order_relaxed)) {
1614 mLooper->pollAll(kTimeoutMsecs);
1615 }
1616}
1617
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001618IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001619 IncFsMount& ifs, DataLoaderParamsParcel&& params, DataLoaderStatusListener&& statusListener,
1620 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001621 std::unique_lock l(ifs.lock);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001622 prepareDataLoaderLocked(ifs, std::move(params), std::move(statusListener), healthCheckParams,
1623 std::move(healthListener));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001624 return ifs.dataLoaderStub;
1625}
1626
1627void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001628 DataLoaderStatusListener&& statusListener,
1629 const StorageHealthCheckParams& healthCheckParams,
1630 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),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001648 std::move(statusListener), healthCheckParams,
1649 std::move(healthListener), 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
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002039bool IncrementalService::updateLoadingProgress(StorageId storage,
2040 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 */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002053 [storage, progressListener = std::move(progressListener), this]() mutable {
2054 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002055 });
2056 return true;
2057}
2058
2059bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002060 StorageId storage, StorageLoadingProgressListener progressListener) {
2061 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002062}
2063
2064bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2065 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2066}
2067
Songchun Fan2570ec02020-10-08 17:22:33 -07002068bool IncrementalService::registerStorageHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002069 StorageId storage, const StorageHealthCheckParams& healthCheckParams,
2070 StorageHealthListener healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002071 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 }
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002083 dataLoaderStub->setHealthListener(healthCheckParams, std::move(healthListener));
Songchun Fan2570ec02020-10-08 17:22:33 -07002084 return true;
2085}
2086
2087void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002088 registerStorageHealthListener(storage, {}, {});
Songchun Fan2570ec02020-10-08 17:22:33 -07002089}
2090
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002091bool IncrementalService::perfLoggingEnabled() {
2092 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2093 return enabled;
2094}
2095
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002096void IncrementalService::runJobProcessing() {
2097 for (;;) {
2098 std::unique_lock lock(mJobMutex);
2099 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2100 if (!mRunning) {
2101 return;
2102 }
2103
2104 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002105 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002106 auto queue = std::move(it->second);
2107 mJobQueue.erase(it);
2108 lock.unlock();
2109
2110 for (auto&& job : queue) {
2111 job();
2112 }
2113
2114 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002115 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002116 lock.unlock();
2117 mJobCondition.notify_all();
2118 }
2119}
2120
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002121void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002122 sp<IAppOpsCallback> listener;
2123 {
2124 std::unique_lock lock{mCallbacksLock};
2125 auto& cb = mCallbackRegistered[packageName];
2126 if (cb) {
2127 return;
2128 }
2129 cb = new AppOpsListener(*this, packageName);
2130 listener = cb;
2131 }
2132
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002133 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2134 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002135}
2136
2137bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2138 sp<IAppOpsCallback> listener;
2139 {
2140 std::unique_lock lock{mCallbacksLock};
2141 auto found = mCallbackRegistered.find(packageName);
2142 if (found == mCallbackRegistered.end()) {
2143 return false;
2144 }
2145 listener = found->second;
2146 mCallbackRegistered.erase(found);
2147 }
2148
2149 mAppOpsManager->stopWatchingMode(listener);
2150 return true;
2151}
2152
2153void IncrementalService::onAppOpChanged(const std::string& packageName) {
2154 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002155 return;
2156 }
2157
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002158 std::vector<IfsMountPtr> affected;
2159 {
2160 std::lock_guard l(mLock);
2161 affected.reserve(mMounts.size());
2162 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002163 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002164 affected.push_back(ifs);
2165 }
2166 }
2167 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002168 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002169 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002170 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002171}
2172
Songchun Fana7098592020-09-03 11:45:53 -07002173bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2174 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002175 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002176 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002177 }
Songchun Fana7098592020-09-03 11:45:53 -07002178 timedQueue.addJob(id, after, std::move(what));
2179 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002180}
2181
Songchun Fana7098592020-09-03 11:45:53 -07002182bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002183 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002184 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002185 }
Songchun Fana7098592020-09-03 11:45:53 -07002186 timedQueue.removeJobs(id);
2187 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002188}
2189
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002190void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
2191 const auto duration = getMillsSinceOldestPendingRead(storageId);
2192 if (duration >= 0) {
2193 const auto kMetricsMillisSinceOldestPendingRead =
2194 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2195 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2196 }
2197}
2198
2199long IncrementalService::getMillsSinceOldestPendingRead(StorageId storageId) {
2200 std::unique_lock l(mLock);
2201 const auto ifs = getIfsLocked(storageId);
2202 if (!ifs) {
2203 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, invalid storageId: " << storageId;
2204 return -EINVAL;
2205 }
2206 if (!ifs->dataLoaderStub) {
2207 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, no data loader: " << storageId;
2208 return -EINVAL;
2209 }
2210 return ifs->dataLoaderStub->elapsedMsSinceOldestPendingRead();
2211}
2212
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002213IncrementalService::DataLoaderStub::DataLoaderStub(
2214 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2215 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2216 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2217 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002218 : mService(service),
2219 mId(id),
2220 mParams(std::move(params)),
2221 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002222 mStatusListener(std::move(statusListener)),
2223 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002224 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002225 mHealthCheckParams(healthCheckParams) {
2226 if (mHealthListener && !isHealthParamsValid()) {
2227 mHealthListener = {};
2228 }
2229 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002230 // Disable advanced health check statuses.
2231 mHealthCheckParams.blockedTimeoutMs = -1;
2232 }
2233 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002234}
2235
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002236IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002237 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002238 cleanupResources();
2239 }
2240}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002241
2242void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002243 auto now = Clock::now();
2244 {
2245 std::unique_lock lock(mMutex);
2246 mHealthPath.clear();
2247 unregisterFromPendingReads();
2248 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002249 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002250 }
2251
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002252 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002253
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002254 {
2255 std::unique_lock lock(mMutex);
2256 mParams = {};
2257 mControl = {};
2258 mHealthControl = {};
2259 mHealthListener = {};
2260 mStatusCondition.wait_until(lock, now + 60s, [this] {
2261 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2262 });
2263 mStatusListener = {};
2264 mId = kInvalidStorageId;
2265 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002266}
2267
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002268sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2269 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002270 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002271 if (!status.isOk()) {
2272 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2273 return {};
2274 }
2275 if (!dataloader) {
2276 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2277 return {};
2278 }
2279 return dataloader;
2280}
2281
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002282bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2283 return (params().packageName == Constants::systemPackage);
2284}
2285
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002286bool IncrementalService::DataLoaderStub::requestCreate() {
2287 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2288}
2289
2290bool IncrementalService::DataLoaderStub::requestStart() {
2291 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2292}
2293
2294bool IncrementalService::DataLoaderStub::requestDestroy() {
2295 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2296}
2297
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002298bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002299 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002300 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002301 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002302 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002303 return fsmStep();
2304}
2305
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002306void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002307 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002308 mTargetStatus = status;
2309 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002310 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002311 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002312}
2313
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002314std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002315 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002316
2317 const auto now = mService.mClock->now();
2318 const bool healthy = (mPreviousBindDelay == 0ms);
2319
2320 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2321 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2322 LOG(INFO) << "Binding still in progress. "
2323 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
2324 : "Already unhealthy, don't do anything.");
2325 // Binding still in progress.
2326 if (!healthy) {
2327 // Already unhealthy, don't do anything.
2328 return {};
2329 }
2330 // The DL is healthy/freshly bound, ok to retry for a few times.
2331 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2332 // Still within grace period.
2333 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2334 // Retry interval passed, retrying.
2335 mCurrentStatusTs = now;
2336 mPreviousBindDelay = 0ms;
2337 return 0ms;
2338 }
2339 return {};
2340 }
2341 // fallthrough, mark as unhealthy, and retry with delay
2342 }
2343
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002344 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002345 mPreviousBindTs = now;
2346
2347 const auto nonCrashingInterval = std::max(castToMs(now - previousBindTs), 100ms);
2348 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2349 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2350 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002351 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002352 }
2353
2354 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2355 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2356
2357 const auto bindDelayMs =
2358 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2359 maxBindDelayMs)
2360 .count();
2361 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2362 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2363 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002364 return mPreviousBindDelay;
2365}
2366
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002367bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002368 const auto maybeBindDelay = needToBind();
2369 if (!maybeBindDelay) {
2370 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2371 return true;
2372 }
2373 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002374 if (bindDelay > 1s) {
2375 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
2376 << bindDelay.count() / 1000 << "s";
2377 }
2378
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002379 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002380 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2381 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002382 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002383 const bool healthy = (bindDelay == 0ms);
2384 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2385 << (healthy ? ", retrying." : "");
2386
2387 // Internal error, retry for healthy/new DLs.
2388 // Let needToBind migrate it to unhealthy after too many retries.
2389 if (healthy) {
2390 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2391 [this]() { fsmStep(); })) {
2392 // Mark as binding so that we know it's not the DL's fault.
2393 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2394 return true;
2395 }
2396 }
2397
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002398 return false;
2399 }
2400 return true;
2401}
2402
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002403bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002404 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002405 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002406 return false;
2407 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002408 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002409 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002410 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002411 return false;
2412 }
2413 return true;
2414}
2415
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002416bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002417 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002418 if (!dataloader) {
2419 return false;
2420 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002421 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002422 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002423 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002424 return false;
2425 }
2426 return true;
2427}
2428
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002429bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002430 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002431}
2432
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002433bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002434 if (!isValid()) {
2435 return false;
2436 }
2437
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002438 int currentStatus;
2439 int targetStatus;
2440 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002441 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002442 currentStatus = mCurrentStatus;
2443 targetStatus = mTargetStatus;
2444 }
2445
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002446 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002447
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002448 if (currentStatus == targetStatus) {
2449 return true;
2450 }
2451
2452 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002453 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2454 // Do nothing, this is a reset state.
2455 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002456 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002457 switch (currentStatus) {
2458 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2459 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2460 return true;
2461 default:
2462 return destroy();
2463 }
2464 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002465 }
2466 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2467 switch (currentStatus) {
2468 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2469 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2470 return start();
2471 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002472 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002473 }
2474 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2475 switch (currentStatus) {
2476 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002477 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002478 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002479 return bind();
2480 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002481 return create();
2482 }
2483 break;
2484 default:
2485 LOG(ERROR) << "Invalid target status: " << targetStatus
2486 << ", current status: " << currentStatus;
2487 break;
2488 }
2489 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002490}
2491
2492binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002493 if (!isValid()) {
2494 return binder::Status::
2495 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2496 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002497 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002498 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2499 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002500 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2501 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002502 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2503 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2504 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2505 [this, newStatus]() { setCurrentStatus(newStatus); });
2506 return binder::Status::ok();
2507 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002508
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002509 setCurrentStatus(newStatus);
2510 return binder::Status::ok();
2511}
2512
2513void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002514 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002515 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002516 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002517 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002518 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002519 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002520 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002521
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002522 oldStatus = mCurrentStatus;
2523 targetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002524 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002525
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002526 // Change the status.
2527 mCurrentStatus = newStatus;
2528 mCurrentStatusTs = mService.mClock->now();
2529
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002530 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2531 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002532 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2533 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002534 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002535 }
2536
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002537 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002538 << newStatus << " (target " << targetStatus << ")";
2539
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002540 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002541 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002542 }
2543
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002544 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002545
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002546 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002547}
2548
Songchun Fan33093982020-09-10 13:12:39 -07002549binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2550 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002551 if (!isValid()) {
2552 return binder::Status::
2553 fromServiceSpecificError(-EINVAL,
2554 "reportStreamHealth came to invalid DataLoaderStub");
2555 }
2556 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002557 LOG(ERROR) << "reportStreamHealth: mount ID mismatch: expected " << id()
2558 << ", but got: " << mountId;
Songchun Fan2570ec02020-10-08 17:22:33 -07002559 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2560 }
2561 {
2562 std::lock_guard lock(mMutex);
2563 mStreamStatus = newStatus;
2564 }
Songchun Fan33093982020-09-10 13:12:39 -07002565 return binder::Status::ok();
2566}
2567
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002568bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2569 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2570 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002571}
2572
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002573void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002574 int healthStatus) {
2575 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2576 if (healthListener) {
2577 healthListener->onHealthStatus(id(), healthStatus);
2578 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002579}
2580
Songchun Fan2570ec02020-10-08 17:22:33 -07002581static int adjustHealthStatus(int healthStatus, int streamStatus) {
2582 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2583 // everything is good; no need to change status
2584 return healthStatus;
2585 }
2586 int newHeathStatus = healthStatus;
2587 switch (streamStatus) {
2588 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2589 // storage is limited and storage not healthy
2590 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2591 break;
2592 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2593 // fall through
2594 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2595 // fall through
2596 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2597 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2598 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2599 }
2600 // pending/blocked status due to transportation issues is not regarded as unhealthy
2601 break;
2602 default:
2603 break;
2604 }
2605 return newHeathStatus;
2606}
2607
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002608void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2609 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002610
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002611 int healthStatusToReport = -1;
2612 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002613
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002614 {
2615 std::unique_lock lock(mMutex);
2616 unregisterFromPendingReads();
2617
2618 healthListener = mHealthListener;
2619
2620 // Healthcheck depends on timestamp of the oldest pending read.
2621 // 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 -07002622 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2623 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002624 const auto now = Clock::now();
2625 const auto kernelTsUs = getOldestPendingReadTs();
2626 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002627 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2628 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002629 mHealthBase = {now, kernelTsUs};
2630 }
2631
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002632 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2633 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002634 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2635 registerForPendingReads();
2636 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2637 lock.unlock();
2638 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002639 return;
2640 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002641
2642 resetHealthControl();
2643
2644 // Always make sure the data loader is started.
2645 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2646
2647 // Skip any further processing if health check params are invalid.
2648 if (!isHealthParamsValid()) {
2649 LOG(DEBUG) << id()
2650 << ": Skip any further processing if health check params are invalid.";
2651 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2652 lock.unlock();
2653 onHealthStatus(healthListener, healthStatusToReport);
2654 // Triggering data loader start. This is a one-time action.
2655 fsmStep();
2656 return;
2657 }
2658
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002659 // Don't schedule timer job less than 500ms in advance.
2660 static constexpr auto kTolerance = 500ms;
2661
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002662 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2663 const auto unhealthyTimeout =
2664 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2665 const auto unhealthyMonitoring =
2666 std::max(1000ms,
2667 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2668
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002669 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002670
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002671 Milliseconds checkBackAfter;
2672 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002673 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002674 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002675 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002676 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002677 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002678 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002679 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2680 } else {
2681 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002682 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002683 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2684 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002685 // Adjust health status based on stream status
2686 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002687 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002688 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002689 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2690 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002691 }
2692
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002693 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002694 if (healthStatusToReport != -1) {
2695 onHealthStatus(healthListener, healthStatusToReport);
2696 }
2697
2698 fsmStep();
2699}
2700
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002701Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2702 BootClockTsUs kernelTsUs) {
2703 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2704 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2705 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2706}
2707
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002708const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2709 if (mHealthPath.empty()) {
2710 resetHealthControl();
2711 return mHealthControl;
2712 }
2713 if (mHealthControl.pendingReads() < 0) {
2714 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2715 }
2716 if (mHealthControl.pendingReads() < 0) {
2717 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2718 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2719 << mHealthControl.logs() << ")";
2720 }
2721 return mHealthControl;
2722}
2723
2724void IncrementalService::DataLoaderStub::resetHealthControl() {
2725 mHealthControl = {};
2726}
2727
2728BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2729 auto result = kMaxBootClockTsUs;
2730
2731 const auto& control = initializeHealthControl();
2732 if (control.pendingReads() < 0) {
2733 return result;
2734 }
2735
Songchun Fan6944f1e2020-11-06 15:24:24 -08002736 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002737 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002738 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002739 // Clear previous pending reads
2740 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002741 return result;
2742 }
2743
2744 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002745 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002746
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002747 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002748}
2749
2750void IncrementalService::DataLoaderStub::registerForPendingReads() {
2751 const auto pendingReadsFd = mHealthControl.pendingReads();
2752 if (pendingReadsFd < 0) {
2753 return;
2754 }
2755
2756 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2757
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002758 mService.mLooper->addFd(
2759 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2760 [](int, int, void* data) -> int {
2761 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002762 self->updateHealthStatus(/*baseline=*/true);
2763 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002764 },
2765 this);
2766 mService.mLooper->wake();
2767}
2768
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002769BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2770 auto result = kMaxBootClockTsUs;
2771 for (auto&& pendingRead : mLastPendingReads) {
2772 result = std::min(result, pendingRead.bootClockTsUs);
2773 }
2774 return result;
2775}
2776
2777long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
2778 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
2779 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
2780 return 0;
2781 }
2782 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
2783}
2784
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002785void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002786 const auto pendingReadsFd = mHealthControl.pendingReads();
2787 if (pendingReadsFd < 0) {
2788 return;
2789 }
2790
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002791 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2792
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002793 mService.mLooper->removeFd(pendingReadsFd);
2794 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002795}
2796
Songchun Fan2570ec02020-10-08 17:22:33 -07002797void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002798 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002799 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002800 mHealthCheckParams = healthCheckParams;
2801 mHealthListener = std::move(healthListener);
2802 if (!mHealthListener) {
2803 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07002804 }
2805}
2806
Songchun Fan6944f1e2020-11-06 15:24:24 -08002807static std::string toHexString(const RawMetadata& metadata) {
2808 int n = metadata.size();
2809 std::string res(n * 2, '\0');
2810 // Same as incfs::toString(fileId)
2811 static constexpr char kHexChar[] = "0123456789abcdef";
2812 for (int i = 0; i < n; ++i) {
2813 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2814 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2815 }
2816 return res;
2817}
2818
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002819void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002820 dprintf(fd, " dataLoader: {\n");
2821 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002822 dprintf(fd, " currentStatusTs: %lldmcs\n",
2823 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002824 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2825 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002826 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002827 dprintf(fd, " health: {\n");
2828 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2829 dprintf(fd, " base: %lldmcs (%lld)\n",
2830 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2831 (long long)mHealthBase.kernelTsUs);
2832 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2833 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2834 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2835 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002836 dprintf(fd, " lastPendingReads: \n");
2837 const auto control = mService.mIncFs->openMount(mHealthPath);
2838 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07002839 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08002840 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2841 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2842 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2843 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2844 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002845 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
2846 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
2847 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002848 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002849 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002850 dprintf(fd, " dataLoaderParams: {\n");
2851 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2852 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2853 dprintf(fd, " className: %s\n", params.className.c_str());
2854 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2855 dprintf(fd, " }\n");
2856 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002857}
2858
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002859void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2860 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002861}
2862
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002863binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2864 bool enableReadLogs, int32_t* _aidl_return) {
2865 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2866 return binder::Status::ok();
2867}
2868
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002869FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2870 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2871}
2872
Songchun Fan3c82a302019-11-29 14:23:45 -08002873} // namespace android::incremental