blob: 932e99783c8392c6e881c489ccbcc4e0d9290084 [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) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700380 std::unique_lock ll(ifs->lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700381 const IncFsMount& mnt = *ifs;
382 dprintf(fd, " [%d]: {\n", id);
383 if (id != mnt.mountId) {
384 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
385 } else {
386 dprintf(fd, " mountId: %d\n", mnt.mountId);
387 dprintf(fd, " root: %s\n", mnt.root.c_str());
388 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
389 if (mnt.dataLoaderStub) {
390 mnt.dataLoaderStub->onDump(fd);
391 } else {
392 dprintf(fd, " dataLoader: null\n");
393 }
394 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
395 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700396 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700397 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800398 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700399 }
400 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800401
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700402 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
403 for (auto&& [target, bind] : mnt.bindPoints) {
404 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
405 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
406 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
407 dprintf(fd, " kind: %s\n", toString(bind.kind));
408 }
409 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800410 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700411 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800412 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700413 dprintf(fd, "}\n");
414 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800415 for (auto&& [target, mountPairIt] : mBindsByPath) {
416 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700417 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
418 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
419 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
420 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800421 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700422 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800423}
424
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800425bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700426 if (!ifs.dataLoaderStub) {
427 return false;
428 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700429 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800430 return true;
431 }
432
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700433 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800434}
435
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700436void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800437 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700438 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800439 }
440
441 std::vector<IfsMountPtr> mounts;
442 {
443 std::lock_guard l(mLock);
444 mounts.reserve(mMounts.size());
445 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700446 std::unique_lock ll(ifs->lock);
447
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800448 if (ifs->mountId != id) {
449 continue;
450 }
451
452 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800453 mounts.push_back(ifs);
454 }
455 }
456 }
457
Alex Buynytskyy69941662020-04-11 21:40:37 -0700458 if (mounts.empty()) {
459 return;
460 }
461
Songchun Fan3c82a302019-11-29 14:23:45 -0800462 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700463 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800464 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700465 std::unique_lock l(ifs->lock);
466 if (ifs->dataLoaderStub) {
467 ifs->dataLoaderStub->requestStart();
468 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800469 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800470 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800471}
472
473auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
474 for (;;) {
475 if (mNextId == kMaxStorageId) {
476 mNextId = 0;
477 }
478 auto id = ++mNextId;
479 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
480 if (inserted) {
481 return it;
482 }
483 }
484}
485
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700486StorageId IncrementalService::createStorage(std::string_view mountPoint,
487 content::pm::DataLoaderParamsParcel dataLoaderParams,
488 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800489 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
490 if (!path::isAbsolute(mountPoint)) {
491 LOG(ERROR) << "path is not absolute: " << mountPoint;
492 return kInvalidStorageId;
493 }
494
495 auto mountNorm = path::normalize(mountPoint);
496 {
497 const auto id = findStorageId(mountNorm);
498 if (id != kInvalidStorageId) {
499 if (options & CreateOptions::OpenExisting) {
500 LOG(INFO) << "Opened existing storage " << id;
501 return id;
502 }
503 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
504 return kInvalidStorageId;
505 }
506 }
507
508 if (!(options & CreateOptions::CreateNew)) {
509 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
510 return kInvalidStorageId;
511 }
512
513 if (!path::isEmptyDir(mountNorm)) {
514 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
515 return kInvalidStorageId;
516 }
517 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
518 if (mountRoot.empty()) {
519 LOG(ERROR) << "Bad mount point";
520 return kInvalidStorageId;
521 }
522 // Make sure the code removes all crap it may create while still failing.
523 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
524 auto firstCleanupOnFailure =
525 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
526
527 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800528 const auto backing = path::join(mountRoot, constants().backing);
529 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800530 return kInvalidStorageId;
531 }
532
Songchun Fan3c82a302019-11-29 14:23:45 -0800533 IncFsMount::Control control;
534 {
535 std::lock_guard l(mMountOperationLock);
536 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800537
538 if (auto err = rmDirContent(backing.c_str())) {
539 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
540 return kInvalidStorageId;
541 }
542 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
543 return kInvalidStorageId;
544 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800545 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
546 return kInvalidStorageId;
547 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800548 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800549 if (!status.isOk()) {
550 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
551 return kInvalidStorageId;
552 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800553 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
554 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800555 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
556 return kInvalidStorageId;
557 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800558 int cmd = controlParcel.cmd.release().release();
559 int pendingReads = controlParcel.pendingReads.release().release();
560 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800561 int blocksWritten =
562 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
563 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800564 }
565
566 std::unique_lock l(mLock);
567 const auto mountIt = getStorageSlotLocked();
568 const auto mountId = mountIt->first;
569 l.unlock();
570
571 auto ifs =
572 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
573 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
574 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700575 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800576
577 auto secondCleanup = [this, &l](auto itPtr) {
578 if (!l.owns_lock()) {
579 l.lock();
580 }
581 mMounts.erase(*itPtr);
582 };
583 auto secondCleanupOnFailure =
584 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
585
586 const auto storageIt = ifs->makeStorage(ifs->mountId);
587 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800588 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800589 return kInvalidStorageId;
590 }
591
592 {
593 metadata::Mount m;
594 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700595 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700596 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
597 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
598 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800599 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800600 if (auto err =
601 mIncFs->makeFile(ifs->control,
602 path::join(ifs->root, constants().mount,
603 constants().infoMdName),
604 0777, idFromMetadata(metadata),
605 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800606 LOG(ERROR) << "Saving mount metadata failed: " << -err;
607 return kInvalidStorageId;
608 }
609 }
610
611 const auto bk =
612 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800613 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
614 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800615 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800616 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800617 return kInvalidStorageId;
618 }
619
620 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700621 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800622
Songchun Fan3c82a302019-11-29 14:23:45 -0800623 mountIt->second = std::move(ifs);
624 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700625
Songchun Fan3c82a302019-11-29 14:23:45 -0800626 LOG(INFO) << "created storage " << mountId;
627 return mountId;
628}
629
630StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
631 StorageId linkedStorage,
632 IncrementalService::CreateOptions options) {
633 if (!isValidMountTarget(mountPoint)) {
634 LOG(ERROR) << "Mount point is invalid or missing";
635 return kInvalidStorageId;
636 }
637
638 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700639 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800640 if (!ifs) {
641 LOG(ERROR) << "Ifs unavailable";
642 return kInvalidStorageId;
643 }
644
645 const auto mountIt = getStorageSlotLocked();
646 const auto storageId = mountIt->first;
647 const auto storageIt = ifs->makeStorage(storageId);
648 if (storageIt == ifs->storages.end()) {
649 LOG(ERROR) << "Can't create a new storage";
650 mMounts.erase(mountIt);
651 return kInvalidStorageId;
652 }
653
654 l.unlock();
655
656 const auto bk =
657 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800658 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
659 std::string(storageIt->second.name), path::normalize(mountPoint),
660 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800661 err < 0) {
662 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700663 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
664 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800665 return kInvalidStorageId;
666 }
667
668 mountIt->second = ifs;
669 return storageId;
670}
671
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700672bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700673 content::pm::DataLoaderParamsParcel dataLoaderParams,
674 DataLoaderStatusListener statusListener,
675 const StorageHealthCheckParams& healthCheckParams,
676 StorageHealthListener healthListener,
677 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800678 // Per Uid timeouts.
679 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700680 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800681 }
682
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700683 IfsMountPtr ifs;
684 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800685
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700686 // Re-initialize DataLoader.
687 {
688 ifs = getIfs(storageId);
689 if (!ifs) {
690 return false;
691 }
692
693 std::unique_lock l(ifs->lock);
694 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
695 }
696
697 if (dataLoaderStub) {
698 dataLoaderStub->cleanupResources();
699 dataLoaderStub = {};
700 }
701
702 {
703 std::unique_lock l(ifs->lock);
704 if (ifs->dataLoaderStub) {
705 LOG(INFO) << "Skipped data loader stub creation because it already exists";
706 return false;
707 }
708 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
709 healthCheckParams, std::move(healthListener));
710 CHECK(ifs->dataLoaderStub);
711 dataLoaderStub = ifs->dataLoaderStub;
712 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800713
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700714 if (dataLoaderStub->isSystemDataLoader()) {
715 // Readlogs from system dataloader (adb) can always be collected.
716 ifs->startLoadingTs = TimePoint::max();
717 } else {
718 // Assign time when installation wants the DL to start streaming.
719 const auto startLoadingTs = mClock->now();
720 ifs->startLoadingTs = startLoadingTs;
721 // Setup a callback to disable the readlogs after max interval.
722 addTimedJob(*mTimedQueue, storageId, Constants::readLogsMaxInterval,
723 [this, storageId, startLoadingTs]() {
724 const auto ifs = getIfs(storageId);
725 if (!ifs) {
726 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
727 << storageId;
728 return;
729 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700730 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700731 if (ifs->startLoadingTs != startLoadingTs) {
732 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
733 "installation?): "
734 << storageId;
735 return;
736 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700737 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700738 });
739 }
740
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800741 return dataLoaderStub->requestStart();
742}
743
Songchun Fan3c82a302019-11-29 14:23:45 -0800744IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
745 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700746 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800747}
748
749StorageId IncrementalService::findStorageId(std::string_view path) const {
750 std::lock_guard l(mLock);
751 auto it = findStorageLocked(path);
752 if (it == mBindsByPath.end()) {
753 return kInvalidStorageId;
754 }
755 return it->second->second.storage;
756}
757
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800758void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700759 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700760 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800761 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700762 return;
763 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700764
765 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800766 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700767 return;
768 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800769 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700770
771 const auto metadata = constants().readLogsDisabledMarkerName;
772 if (auto err = mIncFs->makeFile(ifs->control,
773 path::join(ifs->root, constants().mount,
774 constants().readLogsDisabledMarkerName),
775 0777, idFromMetadata(metadata), {})) {
776 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
777 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
778 return;
779 }
780
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700781 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700782}
783
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700784int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
785 const auto ifs = getIfs(storageId);
786 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700787 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700788 return -EINVAL;
789 }
790
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700791 std::unique_lock l(ifs->lock);
792 if (!enableReadLogs) {
793 return disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700794 }
795
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700796 if (!ifs->readLogsAllowed()) {
797 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
798 return -EPERM;
799 }
800
801 if (!ifs->dataLoaderStub) {
802 // This should never happen - only DL can call enableReadLogs.
803 LOG(ERROR) << "enableReadLogs failed: invalid state";
804 return -EPERM;
805 }
806
807 // Check installation time.
808 const auto now = mClock->now();
809 const auto startLoadingTs = ifs->startLoadingTs;
810 if (startLoadingTs <= now && now - startLoadingTs > Constants::readLogsMaxInterval) {
811 LOG(ERROR) << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
812 << storageId;
813 return -EPERM;
814 }
815
816 const auto& packageName = ifs->dataLoaderStub->params().packageName;
817
818 // Check loader usage stats permission and apop.
819 if (auto status =
820 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
821 !status.isOk()) {
822 LOG(ERROR) << " Permission: " << kLoaderUsageStats
823 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700824 return fromBinderStatus(status);
825 }
826
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700827 // Check multiuser permission.
828 if (auto status =
829 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
830 !status.isOk()) {
831 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
832 << " check failed: " << status.toString8();
833 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700834 }
835
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700836 if (auto status = applyStorageParamsLocked(*ifs, /*enableReadLogs=*/true); status != 0) {
837 return status;
838 }
839
840 registerAppOpsCallback(packageName);
841
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700842 return 0;
843}
844
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700845int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
846 return applyStorageParamsLocked(ifs, /*enableReadLogs=*/false);
847}
848
849int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700850 os::incremental::IncrementalFileSystemControlParcel control;
851 control.cmd.reset(dup(ifs.control.cmd()));
852 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700853 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700854 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700855 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700856 }
857
858 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700859 auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800860 if (status.isOk()) {
861 // Store enabled state.
862 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700863 } else {
864 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800865 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700866 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700867}
868
Songchun Fan3c82a302019-11-29 14:23:45 -0800869void IncrementalService::deleteStorage(StorageId storageId) {
870 const auto ifs = getIfs(storageId);
871 if (!ifs) {
872 return;
873 }
874 deleteStorage(*ifs);
875}
876
877void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
878 std::unique_lock l(ifs.lock);
879 deleteStorageLocked(ifs, std::move(l));
880}
881
882void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
883 std::unique_lock<std::mutex>&& ifsLock) {
884 const auto storages = std::move(ifs.storages);
885 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
886 const auto bindPoints = ifs.bindPoints;
887 ifsLock.unlock();
888
889 std::lock_guard l(mLock);
890 for (auto&& [id, _] : storages) {
891 if (id != ifs.mountId) {
892 mMounts.erase(id);
893 }
894 }
895 for (auto&& [path, _] : bindPoints) {
896 mBindsByPath.erase(path);
897 }
898 mMounts.erase(ifs.mountId);
899}
900
901StorageId IncrementalService::openStorage(std::string_view pathInMount) {
902 if (!path::isAbsolute(pathInMount)) {
903 return kInvalidStorageId;
904 }
905
906 return findStorageId(path::normalize(pathInMount));
907}
908
Songchun Fan3c82a302019-11-29 14:23:45 -0800909IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
910 std::lock_guard l(mLock);
911 return getIfsLocked(storage);
912}
913
914const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
915 auto it = mMounts.find(storage);
916 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700917 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700918 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800919 }
920 return it->second;
921}
922
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800923int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
924 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800925 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700926 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800927 return -EINVAL;
928 }
929
930 const auto ifs = getIfs(storage);
931 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700932 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800933 return -EINVAL;
934 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800935
Songchun Fan3c82a302019-11-29 14:23:45 -0800936 std::unique_lock l(ifs->lock);
937 const auto storageInfo = ifs->storages.find(storage);
938 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700939 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800940 return -EINVAL;
941 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700942 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700943 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700944 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700945 return -EINVAL;
946 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800947 l.unlock();
948 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800949 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
950 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800951}
952
953int IncrementalService::unbind(StorageId storage, std::string_view target) {
954 if (!path::isAbsolute(target)) {
955 return -EINVAL;
956 }
957
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700958 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800959
960 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
961 // otherwise there's a chance to unmount something completely unrelated
962 const auto norm = path::normalize(target);
963 std::unique_lock l(mLock);
964 const auto storageIt = mBindsByPath.find(norm);
965 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
966 return -EINVAL;
967 }
968 const auto bindIt = storageIt->second;
969 const auto storageId = bindIt->second.storage;
970 const auto ifs = getIfsLocked(storageId);
971 if (!ifs) {
972 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
973 << " is missing";
974 return -EFAULT;
975 }
976 mBindsByPath.erase(storageIt);
977 l.unlock();
978
979 mVold->unmountIncFs(bindIt->first);
980 std::unique_lock l2(ifs->lock);
981 if (ifs->bindPoints.size() <= 1) {
982 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700983 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800984 } else {
985 const std::string savedFile = std::move(bindIt->second.savedFilename);
986 ifs->bindPoints.erase(bindIt);
987 l2.unlock();
988 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800989 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800990 }
991 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700992
Songchun Fan3c82a302019-11-29 14:23:45 -0800993 return 0;
994}
995
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700996std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700997 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700998 std::string_view path) const {
999 if (!path::isAbsolute(path)) {
1000 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001001 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001002 auto normPath = path::normalize(path);
1003 if (path::startsWith(normPath, storageIt->second.name)) {
1004 return normPath;
1005 }
1006 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001007 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1008 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001009 return {};
1010 }
1011 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001012}
1013
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001014std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001015 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001016 std::unique_lock l(ifs.lock);
1017 const auto storageInfo = ifs.storages.find(storage);
1018 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001019 return {};
1020 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001021 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001022}
1023
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001024int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001025 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001026 const auto ifs = getIfs(storage);
1027 if (!ifs) {
1028 return -EINVAL;
1029 }
1030 if (data.size() > params.size) {
1031 LOG(ERROR) << "Bad data size - bigger than file size";
1032 return -EINVAL;
1033 }
1034 if (!data.empty() && data.size() != params.size) {
1035 // Writing a page is an irreversible operation, and it can't be updated with additional
1036 // data later. Check that the last written page is complete, or we may break the file.
1037 if (!isPageAligned(data.size())) {
1038 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001039 return -EINVAL;
1040 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001041 }
1042 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1043 if (normPath.empty()) {
1044 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1045 return -EINVAL;
1046 }
1047 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1048 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1049 return err;
1050 }
1051 if (params.size > 0) {
1052 // Only v2+ incfs supports automatically trimming file over-reserved sizes
1053 if (mIncFs->features() & incfs::Features::v2) {
1054 if (auto err = mIncFs->reserveSpace(ifs->control, normPath, params.size)) {
1055 if (err != -EOPNOTSUPP) {
1056 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1057 (void)mIncFs->unlink(ifs->control, normPath);
1058 return err;
1059 } else {
1060 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1061 "may run out of disk later";
1062 }
1063 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001064 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001065 if (!data.empty()) {
1066 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001067 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001068 return err;
1069 }
1070 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001071 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001072 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001073}
1074
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001075int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001076 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001077 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001078 if (normPath.empty()) {
1079 return -EINVAL;
1080 }
1081 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001082 }
1083 return -EINVAL;
1084}
1085
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001086int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001087 const auto ifs = getIfs(storageId);
1088 if (!ifs) {
1089 return -EINVAL;
1090 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001091 return makeDirs(*ifs, storageId, path, mode);
1092}
1093
1094int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1095 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001096 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1097 if (normPath.empty()) {
1098 return -EINVAL;
1099 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001100 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001101}
1102
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001103int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1104 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001105 std::unique_lock l(mLock);
1106 auto ifsSrc = getIfsLocked(sourceStorageId);
1107 if (!ifsSrc) {
1108 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001109 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001110 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1111 return -EINVAL;
1112 }
1113 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001114 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1115 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001116 if (normOldPath.empty() || normNewPath.empty()) {
1117 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1118 return -EINVAL;
1119 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001120 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1121 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1122 << " to " << newPath << "[" << normNewPath << "]";
1123 return err;
1124 }
1125 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001126}
1127
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001128int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001129 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001130 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001131 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001132 }
1133 return -EINVAL;
1134}
1135
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001136int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1137 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001138 std::string&& target, BindKind kind,
1139 std::unique_lock<std::mutex>& mainLock) {
1140 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001141 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001142 return -EINVAL;
1143 }
1144
1145 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001146 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001147 if (kind != BindKind::Temporary) {
1148 metadata::BindPoint bp;
1149 bp.set_storage_id(storage);
1150 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001151 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001152 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001153 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001154 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001155 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001156 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1157 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1158 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001159 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001160 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001161 return int(node);
1162 }
1163 }
1164
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001165 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1166 std::move(target), kind, mainLock);
1167 if (res) {
1168 mIncFs->unlink(ifs.control, metadataFullPath);
1169 }
1170 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001171}
1172
1173int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001174 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001175 std::string&& target, BindKind kind,
1176 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001177 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001178 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001179 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001180 if (!status.isOk()) {
1181 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1182 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1183 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1184 : status.serviceSpecificErrorCode() == 0
1185 ? -EFAULT
1186 : status.serviceSpecificErrorCode()
1187 : -EIO;
1188 }
1189 }
1190
1191 if (!mainLock.owns_lock()) {
1192 mainLock.lock();
1193 }
1194 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001195 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1196 std::move(target), kind);
1197 return 0;
1198}
1199
1200void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1201 std::string&& metadataName, std::string&& source,
1202 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001203 const auto [it, _] =
1204 ifs.bindPoints.insert_or_assign(target,
1205 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001206 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001207 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001208}
1209
1210RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1211 const auto ifs = getIfs(storage);
1212 if (!ifs) {
1213 return {};
1214 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001215 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001216 if (normPath.empty()) {
1217 return {};
1218 }
1219 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001220}
1221
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001222RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001223 const auto ifs = getIfs(storage);
1224 if (!ifs) {
1225 return {};
1226 }
1227 return mIncFs->getMetadata(ifs->control, node);
1228}
1229
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001230void IncrementalService::setUidReadTimeouts(StorageId storage,
1231 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001232 using microseconds = std::chrono::microseconds;
1233 using milliseconds = std::chrono::milliseconds;
1234
1235 auto maxPendingTimeUs = microseconds(0);
1236 for (const auto& timeouts : perUidReadTimeouts) {
1237 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1238 }
1239 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001240 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001241 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1242 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001243 return;
1244 }
1245
1246 const auto ifs = getIfs(storage);
1247 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001248 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001249 return;
1250 }
1251
1252 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1253 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1254 return;
1255 }
1256
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001257 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1258 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1259 if (checkUidReadTimeouts(storageId, state, timeout)) {
1260 return true;
1261 }
1262 clearUidReadTimeouts(storageId);
1263 return false;
1264 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001265}
1266
1267void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1268 const auto ifs = getIfs(storage);
1269 if (!ifs) {
1270 return;
1271 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001272 mIncFs->setUidReadTimeouts(ifs->control, {});
1273}
1274
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001275bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1276 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001277 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001278 // Reached maximum timeout.
1279 return false;
1280 }
1281 if (state.error) {
1282 // Something is wrong, abort.
1283 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001284 }
1285
1286 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001287 if (state.fullyLoaded && !state.readLogsEnabled) {
1288 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001289 }
1290
1291 const auto timeLeft = timeLimit - Clock::now();
1292 if (timeLeft < Constants::progressUpdateInterval) {
1293 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001294 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001295 }
1296
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001297 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001298}
1299
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001300std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1301 std::unordered_set<std::string_view> mountedRootNames;
1302 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1303 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1304 for (auto [source, target] : binds) {
1305 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1306 LOG(INFO) << " " << path::join(root, source);
1307 }
1308
1309 // Ensure it's a kind of a mount that's managed by IncrementalService
1310 if (path::basename(root) != constants().mount ||
1311 path::basename(backingDir) != constants().backing) {
1312 return;
1313 }
1314 const auto expectedRoot = path::dirname(root);
1315 if (path::dirname(backingDir) != expectedRoot) {
1316 return;
1317 }
1318 if (path::dirname(expectedRoot) != mIncrementalDir) {
1319 return;
1320 }
1321 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1322 return;
1323 }
1324
1325 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1326
1327 // make sure we clean up the mount if it happens to be a bad one.
1328 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1329 auto cleanupFiles = makeCleanup([&]() {
1330 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1331 IncFsMount::cleanupFilesystem(expectedRoot);
1332 });
1333 auto cleanupMounts = makeCleanup([&]() {
1334 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1335 for (auto&& [_, target] : binds) {
1336 mVold->unmountIncFs(std::string(target));
1337 }
1338 mVold->unmountIncFs(std::string(root));
1339 });
1340
1341 auto control = mIncFs->openMount(root);
1342 if (!control) {
1343 LOG(INFO) << "failed to open mount " << root;
1344 return;
1345 }
1346
1347 auto mountRecord =
1348 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1349 path::join(root, constants().infoMdName));
1350 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1351 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1352 return;
1353 }
1354
1355 auto mountId = mountRecord.storage().id();
1356 mNextId = std::max(mNextId, mountId + 1);
1357
1358 DataLoaderParamsParcel dataLoaderParams;
1359 {
1360 const auto& loader = mountRecord.loader();
1361 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1362 dataLoaderParams.packageName = loader.package_name();
1363 dataLoaderParams.className = loader.class_name();
1364 dataLoaderParams.arguments = loader.arguments();
1365 }
1366
1367 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1368 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001369 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001370
Alex Buynytskyy04035452020-06-06 20:15:58 -07001371 // Check if marker file present.
1372 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001373 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001374 }
1375
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001376 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1377 auto d = openDir(root);
1378 while (auto e = ::readdir(d.get())) {
1379 if (e->d_type == DT_REG) {
1380 auto name = std::string_view(e->d_name);
1381 if (name.starts_with(constants().mountpointMdPrefix)) {
1382 permanentBindPoints
1383 .emplace_back(name,
1384 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1385 ifs->control,
1386 path::join(root,
1387 name)));
1388 if (permanentBindPoints.back().second.dest_path().empty() ||
1389 permanentBindPoints.back().second.source_subdir().empty()) {
1390 permanentBindPoints.pop_back();
1391 mIncFs->unlink(ifs->control, path::join(root, name));
1392 } else {
1393 LOG(INFO) << "Permanent bind record: '"
1394 << permanentBindPoints.back().second.source_subdir() << "'->'"
1395 << permanentBindPoints.back().second.dest_path() << "'";
1396 }
1397 }
1398 } else if (e->d_type == DT_DIR) {
1399 if (e->d_name == "."sv || e->d_name == ".."sv) {
1400 continue;
1401 }
1402 auto name = std::string_view(e->d_name);
1403 if (name.starts_with(constants().storagePrefix)) {
1404 int storageId;
1405 const auto res =
1406 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1407 name.data() + name.size(), storageId);
1408 if (res.ec != std::errc{} || *res.ptr != '_') {
1409 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1410 << "' for mount " << expectedRoot;
1411 continue;
1412 }
1413 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1414 if (!inserted) {
1415 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1416 << " for mount " << expectedRoot;
1417 continue;
1418 }
1419 ifs->storages.insert_or_assign(storageId,
1420 IncFsMount::Storage{path::join(root, name)});
1421 mNextId = std::max(mNextId, storageId + 1);
1422 }
1423 }
1424 }
1425
1426 if (ifs->storages.empty()) {
1427 LOG(WARNING) << "No valid storages in mount " << root;
1428 return;
1429 }
1430
1431 // now match the mounted directories with what we expect to have in the metadata
1432 {
1433 std::unique_lock l(mLock, std::defer_lock);
1434 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1435 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1436 [&, bindRecord = bindRecord](auto&& bind) {
1437 return bind.second == bindRecord.dest_path() &&
1438 path::join(root, bind.first) ==
1439 bindRecord.source_subdir();
1440 });
1441 if (mountedIt != binds.end()) {
1442 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1443 << " to mount " << mountedIt->first;
1444 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1445 std::move(*bindRecord.mutable_source_subdir()),
1446 std::move(*bindRecord.mutable_dest_path()),
1447 BindKind::Permanent);
1448 if (mountedIt != binds.end() - 1) {
1449 std::iter_swap(mountedIt, binds.end() - 1);
1450 }
1451 binds = binds.first(binds.size() - 1);
1452 } else {
1453 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1454 << ", mounting";
1455 // doesn't exist - try mounting back
1456 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1457 std::move(*bindRecord.mutable_source_subdir()),
1458 std::move(*bindRecord.mutable_dest_path()),
1459 BindKind::Permanent, l)) {
1460 mIncFs->unlink(ifs->control, metadataFile);
1461 }
1462 }
1463 }
1464 }
1465
1466 // if anything stays in |binds| those are probably temporary binds; system restarted since
1467 // they were mounted - so let's unmount them all.
1468 for (auto&& [source, target] : binds) {
1469 if (source.empty()) {
1470 continue;
1471 }
1472 mVold->unmountIncFs(std::string(target));
1473 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001474 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001475
1476 if (ifs->bindPoints.empty()) {
1477 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1478 deleteStorage(*ifs);
1479 return;
1480 }
1481
1482 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1483 CHECK(ifs->dataLoaderStub);
1484
1485 mountedRootNames.insert(path::basename(ifs->root));
1486
1487 // not locking here at all: we're still in the constructor, no other calls can happen
1488 mMounts[ifs->mountId] = std::move(ifs);
1489 });
1490
1491 return mountedRootNames;
1492}
1493
1494void IncrementalService::mountExistingImages(
1495 const std::unordered_set<std::string_view>& mountedRootNames) {
1496 auto dir = openDir(mIncrementalDir);
1497 if (!dir) {
1498 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1499 return;
1500 }
1501 while (auto entry = ::readdir(dir.get())) {
1502 if (entry->d_type != DT_DIR) {
1503 continue;
1504 }
1505 std::string_view name = entry->d_name;
1506 if (!name.starts_with(constants().mountKeyPrefix)) {
1507 continue;
1508 }
1509 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001510 continue;
1511 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001512 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001513 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001514 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001515 }
1516 }
1517}
1518
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001519bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001520 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001521 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001522
Songchun Fan3c82a302019-11-29 14:23:45 -08001523 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001524 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001525 if (!status.isOk()) {
1526 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1527 return false;
1528 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001529
1530 int cmd = controlParcel.cmd.release().release();
1531 int pendingReads = controlParcel.pendingReads.release().release();
1532 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001533 int blocksWritten =
1534 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1535 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001536
1537 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1538
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001539 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1540 path::join(mountTarget, constants().infoMdName));
1541 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001542 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1543 return false;
1544 }
1545
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001546 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001547 mNextId = std::max(mNextId, ifs->mountId + 1);
1548
Alex Buynytskyy04035452020-06-06 20:15:58 -07001549 // Check if marker file present.
1550 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001551 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001552 }
1553
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001554 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001555 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001556 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001557 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001558 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001559 dataLoaderParams.packageName = loader.package_name();
1560 dataLoaderParams.className = loader.class_name();
1561 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001562 }
1563
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001564 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001565 CHECK(ifs->dataLoaderStub);
1566
Songchun Fan3c82a302019-11-29 14:23:45 -08001567 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001568 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001569 while (auto e = ::readdir(d.get())) {
1570 if (e->d_type == DT_REG) {
1571 auto name = std::string_view(e->d_name);
1572 if (name.starts_with(constants().mountpointMdPrefix)) {
1573 bindPoints.emplace_back(name,
1574 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1575 ifs->control,
1576 path::join(mountTarget,
1577 name)));
1578 if (bindPoints.back().second.dest_path().empty() ||
1579 bindPoints.back().second.source_subdir().empty()) {
1580 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001581 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001582 }
1583 }
1584 } else if (e->d_type == DT_DIR) {
1585 if (e->d_name == "."sv || e->d_name == ".."sv) {
1586 continue;
1587 }
1588 auto name = std::string_view(e->d_name);
1589 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001590 int storageId;
1591 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1592 name.data() + name.size(), storageId);
1593 if (res.ec != std::errc{} || *res.ptr != '_') {
1594 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1595 << root;
1596 continue;
1597 }
1598 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001599 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001600 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001601 << " for mount " << root;
1602 continue;
1603 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001604 ifs->storages.insert_or_assign(storageId,
1605 IncFsMount::Storage{
1606 path::join(root, constants().mount, name)});
1607 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001608 }
1609 }
1610 }
1611
1612 if (ifs->storages.empty()) {
1613 LOG(WARNING) << "No valid storages in mount " << root;
1614 return false;
1615 }
1616
1617 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001618 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001619 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001620 for (auto&& bp : bindPoints) {
1621 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1622 std::move(*bp.second.mutable_source_subdir()),
1623 std::move(*bp.second.mutable_dest_path()),
1624 BindKind::Permanent, l);
1625 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001626 }
1627
1628 if (bindCount == 0) {
1629 LOG(WARNING) << "No valid bind points for mount " << root;
1630 deleteStorage(*ifs);
1631 return false;
1632 }
1633
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001634 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001635 mMounts[ifs->mountId] = std::move(ifs);
1636 return true;
1637}
1638
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001639void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001640 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001641 while (mRunning.load(std::memory_order_relaxed)) {
1642 mLooper->pollAll(kTimeoutMsecs);
1643 }
1644}
1645
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001646void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001647 DataLoaderStatusListener&& statusListener,
1648 const StorageHealthCheckParams& healthCheckParams,
1649 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001650 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001651 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001652 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1653 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1654 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001655 if (ifs.control.blocksWritten() >= 0) {
1656 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1657 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001658 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001659
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001660 ifs.dataLoaderStub =
1661 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001662 std::move(statusListener), healthCheckParams,
1663 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001664
1665 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1666 if (!state.fullyLoaded || state.readLogsEnabled) {
1667 return true;
1668 }
1669
1670 DataLoaderStubPtr dataLoaderStub;
1671 {
1672 const auto ifs = getIfs(storageId);
1673 if (!ifs) {
1674 return false;
1675 }
1676
1677 std::unique_lock l(ifs->lock);
1678 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1679 }
1680
1681 if (dataLoaderStub) {
1682 dataLoaderStub->cleanupResources();
1683 }
1684
1685 return false;
1686 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001687}
1688
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001689template <class Duration>
1690static long elapsedMcs(Duration start, Duration end) {
1691 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1692}
1693
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001694template <class Duration>
1695static constexpr auto castToMs(Duration d) {
1696 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1697}
1698
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001699// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001700// Lib files should be placed next to the APK file in the following matter:
1701// Example:
1702// /path/to/base.apk
1703// /path/to/lib/arm/first.so
1704// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001705bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1706 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001707 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001708 auto start = Clock::now();
1709
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001710 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001711 if (!ifs) {
1712 LOG(ERROR) << "Invalid storage " << storage;
1713 return false;
1714 }
1715
Songchun Fanc8975312020-07-13 12:14:37 -07001716 const auto targetLibPathRelativeToStorage =
1717 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1718 libDirRelativePath);
1719
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001720 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001721 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1722 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001723 << " errno: " << res;
1724 return false;
1725 }
1726
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001727 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001728 ZipArchiveHandle zipFileHandle;
1729 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001730 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1731 return false;
1732 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001733
1734 // Need a shared pointer: will be passing it into all unpacking jobs.
1735 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001736 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001737 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001738 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001739 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1740 return false;
1741 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001742 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001743 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1744
1745 auto openZipTs = Clock::now();
1746
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001747 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1748 incfs::FileId sourceId;
1749 if (mapFiles) {
1750 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1751 if (!incfs::isValidFileId(sourceId)) {
1752 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1753 << "', mapping disabled";
1754 mapFiles = false;
1755 }
1756 }
1757
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001758 std::vector<Job> jobQueue;
1759 ZipEntry entry;
1760 std::string_view fileName;
1761 while (!Next(cookie, &entry, &fileName)) {
1762 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001763 continue;
1764 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001765
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001766 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001767 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001768
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001769 if (!extractNativeLibs) {
1770 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001771 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001772 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1773 return false;
1774 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001775 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001776 LOG(WARNING) << "Library " << fileName
1777 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1778 << entry.offset;
1779 return false;
1780 }
1781 continue;
1782 }
1783
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001784 auto startFileTs = Clock::now();
1785
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001786 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001787 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001788 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001789 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001790 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001791 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001792 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1793 << "; skipping extraction, spent "
1794 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1795 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001796 continue;
1797 }
1798
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001799 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1800 incfs::NewMappedFileParams mappedFileParams = {
1801 .sourceId = sourceId,
1802 .sourceOffset = entry.offset,
1803 .size = entry.uncompressed_length,
1804 };
1805
1806 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1807 mappedFileParams);
1808 res == 0) {
1809 if (perfLoggingEnabled()) {
1810 auto doneTs = Clock::now();
1811 LOG(INFO) << "incfs: Mapped " << libName << ": "
1812 << elapsedMcs(startFileTs, doneTs) << "mcs";
1813 }
1814 continue;
1815 } else {
1816 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1817 << "; falling back to full extraction";
1818 }
1819 }
1820
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001821 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001822 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001823 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001824 .signature = {},
1825 // Metadata of the new lib file is its relative path
1826 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1827 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001828 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001829 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001830 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001831 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001832 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001833 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001834 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001835
1836 auto makeFileTs = Clock::now();
1837
Songchun Fanafaf6e92020-03-18 14:12:20 -07001838 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001839 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001840 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001841 LOG(INFO) << "incfs: Extracted " << libName
1842 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001843 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001844 continue;
1845 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001846
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001847 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1848 libFileId, libPath = std::move(targetLibPath),
1849 makeFileTs]() mutable {
1850 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001851 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001852
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001853 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001854 auto prepareJobTs = Clock::now();
1855 LOG(INFO) << "incfs: Processed " << libName << ": "
1856 << elapsedMcs(startFileTs, prepareJobTs)
1857 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1858 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001859 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001860 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001861
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001862 auto processedTs = Clock::now();
1863
1864 if (!jobQueue.empty()) {
1865 {
1866 std::lock_guard lock(mJobMutex);
1867 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001868 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001869 if (existingJobs.empty()) {
1870 existingJobs = std::move(jobQueue);
1871 } else {
1872 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1873 std::move_iterator(jobQueue.end()));
1874 }
1875 }
1876 }
1877 mJobCondition.notify_all();
1878 }
1879
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001880 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001881 auto end = Clock::now();
1882 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1883 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1884 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001885 << " make files: " << elapsedMcs(openZipTs, processedTs)
1886 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001887 }
1888
1889 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001890}
1891
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001892void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1893 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001894 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001895 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001896 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001897 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001898 return;
1899 }
1900
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001901 auto startedTs = Clock::now();
1902
1903 // Write extracted data to new file
1904 // NOTE: don't zero-initialize memory, it may take a while for nothing
1905 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1906 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001907 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001908 return;
1909 }
1910
1911 auto extractFileTs = Clock::now();
1912
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001913 if (setFileContent(ifs, libFileId, debugLibPath,
1914 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001915 return;
1916 }
1917
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001918 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001919 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001920 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1921 << entry.compressed_length << " -> " << entry.uncompressed_length
1922 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001923 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1924 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001925 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001926 }
1927}
1928
1929bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001930 struct WaitPrinter {
1931 const Clock::time_point startTs = Clock::now();
1932 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001933 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001934 const auto endTs = Clock::now();
1935 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1936 << elapsedMcs(startTs, endTs) << "mcs";
1937 }
1938 }
1939 } waitPrinter;
1940
1941 MountId mount;
1942 {
1943 auto ifs = getIfs(storage);
1944 if (!ifs) {
1945 return true;
1946 }
1947 mount = ifs->mountId;
1948 }
1949
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001950 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001951 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001952 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001953 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001954 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001955 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001956}
1957
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001958int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1959 std::string_view debugFilePath,
1960 std::span<const uint8_t> data) const {
1961 auto startTs = Clock::now();
1962
1963 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1964 if (!writeFd.ok()) {
1965 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1966 << " errno: " << writeFd.get();
1967 return writeFd.get();
1968 }
1969
1970 const auto dataLength = data.size();
1971
1972 auto openFileTs = Clock::now();
1973 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1974 std::vector<IncFsDataBlock> instructions(numBlocks);
1975 for (int i = 0; i < numBlocks; i++) {
1976 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1977 instructions[i] = IncFsDataBlock{
1978 .fileFd = writeFd.get(),
1979 .pageIndex = static_cast<IncFsBlockIndex>(i),
1980 .compression = INCFS_COMPRESSION_KIND_NONE,
1981 .kind = INCFS_BLOCK_KIND_DATA,
1982 .dataSize = static_cast<uint32_t>(blockSize),
1983 .data = reinterpret_cast<const char*>(data.data()),
1984 };
1985 data = data.subspan(blockSize);
1986 }
1987 auto prepareInstsTs = Clock::now();
1988
1989 size_t res = mIncFs->writeBlocks(instructions);
1990 if (res != instructions.size()) {
1991 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1992 return res;
1993 }
1994
1995 if (perfLoggingEnabled()) {
1996 auto endTs = Clock::now();
1997 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1998 << " bytes): " << elapsedMcs(startTs, endTs)
1999 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2000 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2001 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2002 }
2003
2004 return 0;
2005}
2006
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002007incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2008 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002009 std::unique_lock l(mLock);
2010 const auto ifs = getIfsLocked(storage);
2011 if (!ifs) {
2012 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002013 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002014 }
2015 const auto storageInfo = ifs->storages.find(storage);
2016 if (storageInfo == ifs->storages.end()) {
2017 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002018 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002019 }
2020 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002021 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002022}
2023
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002024incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2025 const auto ifs = getIfs(storage);
2026 if (!ifs) {
2027 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2028 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002029 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002030 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002031}
2032
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002033IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002034 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002035 std::unique_lock l(mLock);
2036 const auto ifs = getIfsLocked(storage);
2037 if (!ifs) {
2038 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002039 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002040 }
2041 const auto storageInfo = ifs->storages.find(storage);
2042 if (storageInfo == ifs->storages.end()) {
2043 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002044 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002045 }
2046 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002047 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002048}
2049
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002050IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002051 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002052 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2053 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002054 const auto [filledBlocksCount, totalBlocksCount] =
2055 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002056 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2057 filledBlocksCount == -ENOENT) {
2058 // a kind of a file that's not really being loaded, e.g. a mapped range
2059 // an older IncFS used to return ENOENT in this case, so handle it the same way
2060 return true;
2061 }
Songchun Fan374f7652020-08-20 08:40:29 -07002062 if (filledBlocksCount < 0) {
2063 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002064 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002065 error = filledBlocksCount;
2066 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002067 }
2068 totalBlocks += totalBlocksCount;
2069 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002070 return true;
2071 });
Songchun Fan374f7652020-08-20 08:40:29 -07002072
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002073 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002074}
2075
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002076bool IncrementalService::updateLoadingProgress(StorageId storage,
2077 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002078 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002079 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002080 // Failed to get progress from incfs, abort.
2081 return false;
2082 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002083 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2084 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002085 // Stop updating progress once it is fully loaded
2086 return true;
2087 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002088 addTimedJob(*mProgressUpdateJobQueue, storage,
2089 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002090 [storage, progressListener = std::move(progressListener), this]() mutable {
2091 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002092 });
2093 return true;
2094}
2095
2096bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002097 StorageId storage, StorageLoadingProgressListener progressListener) {
2098 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002099}
2100
2101bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2102 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2103}
2104
Songchun Fan2570ec02020-10-08 17:22:33 -07002105bool IncrementalService::registerStorageHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002106 StorageId storage, const StorageHealthCheckParams& healthCheckParams,
2107 StorageHealthListener healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002108 DataLoaderStubPtr dataLoaderStub;
2109 {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002110 const auto& ifs = getIfs(storage);
Songchun Fan2570ec02020-10-08 17:22:33 -07002111 if (!ifs) {
2112 return false;
2113 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002114 std::unique_lock l(ifs->lock);
Songchun Fan2570ec02020-10-08 17:22:33 -07002115 dataLoaderStub = ifs->dataLoaderStub;
2116 if (!dataLoaderStub) {
2117 return false;
2118 }
2119 }
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002120 dataLoaderStub->setHealthListener(healthCheckParams, std::move(healthListener));
Songchun Fan2570ec02020-10-08 17:22:33 -07002121 return true;
2122}
2123
2124void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002125 registerStorageHealthListener(storage, {}, {});
Songchun Fan2570ec02020-10-08 17:22:33 -07002126}
2127
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002128bool IncrementalService::perfLoggingEnabled() {
2129 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2130 return enabled;
2131}
2132
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002133void IncrementalService::runJobProcessing() {
2134 for (;;) {
2135 std::unique_lock lock(mJobMutex);
2136 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2137 if (!mRunning) {
2138 return;
2139 }
2140
2141 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002142 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002143 auto queue = std::move(it->second);
2144 mJobQueue.erase(it);
2145 lock.unlock();
2146
2147 for (auto&& job : queue) {
2148 job();
2149 }
2150
2151 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002152 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002153 lock.unlock();
2154 mJobCondition.notify_all();
2155 }
2156}
2157
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002158void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002159 sp<IAppOpsCallback> listener;
2160 {
2161 std::unique_lock lock{mCallbacksLock};
2162 auto& cb = mCallbackRegistered[packageName];
2163 if (cb) {
2164 return;
2165 }
2166 cb = new AppOpsListener(*this, packageName);
2167 listener = cb;
2168 }
2169
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002170 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2171 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002172}
2173
2174bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2175 sp<IAppOpsCallback> listener;
2176 {
2177 std::unique_lock lock{mCallbacksLock};
2178 auto found = mCallbackRegistered.find(packageName);
2179 if (found == mCallbackRegistered.end()) {
2180 return false;
2181 }
2182 listener = found->second;
2183 mCallbackRegistered.erase(found);
2184 }
2185
2186 mAppOpsManager->stopWatchingMode(listener);
2187 return true;
2188}
2189
2190void IncrementalService::onAppOpChanged(const std::string& packageName) {
2191 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002192 return;
2193 }
2194
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002195 std::vector<IfsMountPtr> affected;
2196 {
2197 std::lock_guard l(mLock);
2198 affected.reserve(mMounts.size());
2199 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002200 std::unique_lock ll(ifs->lock);
2201
2202 if (ifs->mountId == id && ifs->dataLoaderStub &&
2203 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002204 affected.push_back(ifs);
2205 }
2206 }
2207 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002208 for (auto&& ifs : affected) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002209 applyStorageParamsLocked(*ifs, /*enableReadLogs=*/false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002210 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002211}
2212
Songchun Fana7098592020-09-03 11:45:53 -07002213bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2214 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002215 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002216 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002217 }
Songchun Fana7098592020-09-03 11:45:53 -07002218 timedQueue.addJob(id, after, std::move(what));
2219 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002220}
2221
Songchun Fana7098592020-09-03 11:45:53 -07002222bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002223 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002224 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002225 }
Songchun Fana7098592020-09-03 11:45:53 -07002226 timedQueue.removeJobs(id);
2227 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002228}
2229
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002230void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2231 bool wasEmpty;
2232 {
2233 std::lock_guard l(mIfsStateCallbacksLock);
2234 wasEmpty = mIfsStateCallbacks.empty();
2235 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2236 }
2237 if (wasEmpty) {
2238 addTimedJob(*mTimedQueue, kMaxStorageId, Constants::progressUpdateInterval,
2239 [this]() { processIfsStateCallbacks(); });
2240 }
2241}
2242
2243void IncrementalService::processIfsStateCallbacks() {
2244 StorageId storageId = kInvalidStorageId;
2245 std::vector<IfsStateCallback> local;
2246 while (true) {
2247 {
2248 std::lock_guard l(mIfsStateCallbacksLock);
2249 if (mIfsStateCallbacks.empty()) {
2250 return;
2251 }
2252 IfsStateCallbacks::iterator it;
2253 if (storageId == kInvalidStorageId) {
2254 // First entry, initialize the it.
2255 it = mIfsStateCallbacks.begin();
2256 } else {
2257 // Subsequent entries, update the storageId, and shift to the new one.
2258 it = mIfsStateCallbacks.find(storageId);
2259 if (it == mIfsStateCallbacks.end()) {
2260 // Was removed while processing, too bad.
2261 break;
2262 }
2263
2264 auto& callbacks = it->second;
2265 if (callbacks.empty()) {
2266 std::swap(callbacks, local);
2267 } else {
2268 callbacks.insert(callbacks.end(), local.begin(), local.end());
2269 }
2270 if (callbacks.empty()) {
2271 it = mIfsStateCallbacks.erase(it);
2272 if (mIfsStateCallbacks.empty()) {
2273 return;
2274 }
2275 } else {
2276 ++it;
2277 }
2278 }
2279
2280 if (it == mIfsStateCallbacks.end()) {
2281 break;
2282 }
2283
2284 storageId = it->first;
2285 auto& callbacks = it->second;
2286 if (callbacks.empty()) {
2287 // Invalid case, one extra lookup should be ok.
2288 continue;
2289 }
2290 std::swap(callbacks, local);
2291 }
2292
2293 processIfsStateCallbacks(storageId, local);
2294 }
2295
2296 addTimedJob(*mTimedQueue, kMaxStorageId, Constants::progressUpdateInterval,
2297 [this]() { processIfsStateCallbacks(); });
2298}
2299
2300void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2301 std::vector<IfsStateCallback>& callbacks) {
2302 const auto state = isMountFullyLoaded(storageId);
2303 IfsState storageState = {};
2304 storageState.error = int(state) < 0;
2305 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2306 if (storageState.fullyLoaded) {
2307 const auto ifs = getIfs(storageId);
2308 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2309 }
2310
2311 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2312 if ((*cur)(storageId, storageState)) {
2313 ++cur;
2314 } else {
2315 cur = callbacks.erase(cur);
2316 }
2317 }
2318}
2319
2320void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2321 std::lock_guard l(mIfsStateCallbacksLock);
2322 mIfsStateCallbacks.erase(storageId);
2323}
2324
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002325void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
2326 const auto duration = getMillsSinceOldestPendingRead(storageId);
2327 if (duration >= 0) {
2328 const auto kMetricsMillisSinceOldestPendingRead =
2329 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2330 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2331 }
2332}
2333
2334long IncrementalService::getMillsSinceOldestPendingRead(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002335 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002336 if (!ifs) {
2337 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, invalid storageId: " << storageId;
2338 return -EINVAL;
2339 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002340 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002341 if (!ifs->dataLoaderStub) {
2342 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, no data loader: " << storageId;
2343 return -EINVAL;
2344 }
2345 return ifs->dataLoaderStub->elapsedMsSinceOldestPendingRead();
2346}
2347
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002348IncrementalService::DataLoaderStub::DataLoaderStub(
2349 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2350 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2351 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2352 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002353 : mService(service),
2354 mId(id),
2355 mParams(std::move(params)),
2356 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002357 mStatusListener(std::move(statusListener)),
2358 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002359 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002360 mHealthCheckParams(healthCheckParams) {
2361 if (mHealthListener && !isHealthParamsValid()) {
2362 mHealthListener = {};
2363 }
2364 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002365 // Disable advanced health check statuses.
2366 mHealthCheckParams.blockedTimeoutMs = -1;
2367 }
2368 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002369}
2370
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002371IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002372 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002373 cleanupResources();
2374 }
2375}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002376
2377void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002378 auto now = Clock::now();
2379 {
2380 std::unique_lock lock(mMutex);
2381 mHealthPath.clear();
2382 unregisterFromPendingReads();
2383 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002384 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002385 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002386 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002387
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002388 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002389
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002390 {
2391 std::unique_lock lock(mMutex);
2392 mParams = {};
2393 mControl = {};
2394 mHealthControl = {};
2395 mHealthListener = {};
2396 mStatusCondition.wait_until(lock, now + 60s, [this] {
2397 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2398 });
2399 mStatusListener = {};
2400 mId = kInvalidStorageId;
2401 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002402}
2403
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002404sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2405 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002406 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002407 if (!status.isOk()) {
2408 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2409 return {};
2410 }
2411 if (!dataloader) {
2412 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2413 return {};
2414 }
2415 return dataloader;
2416}
2417
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002418bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2419 return (params().packageName == Constants::systemPackage);
2420}
2421
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002422bool IncrementalService::DataLoaderStub::requestCreate() {
2423 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2424}
2425
2426bool IncrementalService::DataLoaderStub::requestStart() {
2427 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2428}
2429
2430bool IncrementalService::DataLoaderStub::requestDestroy() {
2431 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2432}
2433
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002434bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002435 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002436 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002437 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002438 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002439 return fsmStep();
2440}
2441
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002442void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002443 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002444 mTargetStatus = status;
2445 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002446 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002447 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002448}
2449
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002450std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002451 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002452
2453 const auto now = mService.mClock->now();
2454 const bool healthy = (mPreviousBindDelay == 0ms);
2455
2456 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2457 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2458 LOG(INFO) << "Binding still in progress. "
2459 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
2460 : "Already unhealthy, don't do anything.");
2461 // Binding still in progress.
2462 if (!healthy) {
2463 // Already unhealthy, don't do anything.
2464 return {};
2465 }
2466 // The DL is healthy/freshly bound, ok to retry for a few times.
2467 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2468 // Still within grace period.
2469 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2470 // Retry interval passed, retrying.
2471 mCurrentStatusTs = now;
2472 mPreviousBindDelay = 0ms;
2473 return 0ms;
2474 }
2475 return {};
2476 }
2477 // fallthrough, mark as unhealthy, and retry with delay
2478 }
2479
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002480 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002481 mPreviousBindTs = now;
2482
2483 const auto nonCrashingInterval = std::max(castToMs(now - previousBindTs), 100ms);
2484 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2485 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2486 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002487 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002488 }
2489
2490 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2491 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2492
2493 const auto bindDelayMs =
2494 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2495 maxBindDelayMs)
2496 .count();
2497 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2498 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2499 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002500 return mPreviousBindDelay;
2501}
2502
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002503bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002504 const auto maybeBindDelay = needToBind();
2505 if (!maybeBindDelay) {
2506 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2507 return true;
2508 }
2509 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002510 if (bindDelay > 1s) {
2511 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
2512 << bindDelay.count() / 1000 << "s";
2513 }
2514
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002515 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002516 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2517 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002518 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002519 const bool healthy = (bindDelay == 0ms);
2520 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2521 << (healthy ? ", retrying." : "");
2522
2523 // Internal error, retry for healthy/new DLs.
2524 // Let needToBind migrate it to unhealthy after too many retries.
2525 if (healthy) {
2526 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2527 [this]() { fsmStep(); })) {
2528 // Mark as binding so that we know it's not the DL's fault.
2529 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2530 return true;
2531 }
2532 }
2533
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002534 return false;
2535 }
2536 return true;
2537}
2538
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002539bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002540 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002541 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002542 return false;
2543 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002544 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002545 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002546 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002547 return false;
2548 }
2549 return true;
2550}
2551
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002552bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002553 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002554 if (!dataloader) {
2555 return false;
2556 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002557 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002558 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002559 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002560 return false;
2561 }
2562 return true;
2563}
2564
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002565bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002566 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002567}
2568
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002569bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002570 if (!isValid()) {
2571 return false;
2572 }
2573
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002574 int currentStatus;
2575 int targetStatus;
2576 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002577 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002578 currentStatus = mCurrentStatus;
2579 targetStatus = mTargetStatus;
2580 }
2581
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002582 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002583
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002584 if (currentStatus == targetStatus) {
2585 return true;
2586 }
2587
2588 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002589 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2590 // Do nothing, this is a reset state.
2591 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002592 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002593 switch (currentStatus) {
2594 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2595 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2596 return true;
2597 default:
2598 return destroy();
2599 }
2600 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002601 }
2602 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2603 switch (currentStatus) {
2604 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2605 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2606 return start();
2607 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002608 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002609 }
2610 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2611 switch (currentStatus) {
2612 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002613 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002614 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002615 return bind();
2616 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002617 return create();
2618 }
2619 break;
2620 default:
2621 LOG(ERROR) << "Invalid target status: " << targetStatus
2622 << ", current status: " << currentStatus;
2623 break;
2624 }
2625 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002626}
2627
2628binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002629 if (!isValid()) {
2630 return binder::Status::
2631 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2632 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002633 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002634 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2635 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002636 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2637 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002638 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2639 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2640 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2641 [this, newStatus]() { setCurrentStatus(newStatus); });
2642 return binder::Status::ok();
2643 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002644
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002645 setCurrentStatus(newStatus);
2646 return binder::Status::ok();
2647}
2648
2649void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002650 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002651 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002652 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002653 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002654 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002655 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002656 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002657
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002658 oldStatus = mCurrentStatus;
2659 targetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002660 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002661
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002662 // Change the status.
2663 mCurrentStatus = newStatus;
2664 mCurrentStatusTs = mService.mClock->now();
2665
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002666 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2667 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002668 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2669 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002670 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002671 }
2672
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002673 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002674 << newStatus << " (target " << targetStatus << ")";
2675
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002676 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002677 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002678 }
2679
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002680 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002681
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002682 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002683}
2684
Songchun Fan33093982020-09-10 13:12:39 -07002685binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2686 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002687 if (!isValid()) {
2688 return binder::Status::
2689 fromServiceSpecificError(-EINVAL,
2690 "reportStreamHealth came to invalid DataLoaderStub");
2691 }
2692 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002693 LOG(ERROR) << "reportStreamHealth: mount ID mismatch: expected " << id()
2694 << ", but got: " << mountId;
Songchun Fan2570ec02020-10-08 17:22:33 -07002695 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2696 }
2697 {
2698 std::lock_guard lock(mMutex);
2699 mStreamStatus = newStatus;
2700 }
Songchun Fan33093982020-09-10 13:12:39 -07002701 return binder::Status::ok();
2702}
2703
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002704bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2705 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2706 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002707}
2708
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002709void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002710 int healthStatus) {
2711 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2712 if (healthListener) {
2713 healthListener->onHealthStatus(id(), healthStatus);
2714 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002715}
2716
Songchun Fan2570ec02020-10-08 17:22:33 -07002717static int adjustHealthStatus(int healthStatus, int streamStatus) {
2718 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2719 // everything is good; no need to change status
2720 return healthStatus;
2721 }
2722 int newHeathStatus = healthStatus;
2723 switch (streamStatus) {
2724 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2725 // storage is limited and storage not healthy
2726 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2727 break;
2728 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2729 // fall through
2730 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2731 // fall through
2732 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2733 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2734 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2735 }
2736 // pending/blocked status due to transportation issues is not regarded as unhealthy
2737 break;
2738 default:
2739 break;
2740 }
2741 return newHeathStatus;
2742}
2743
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002744void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2745 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002746
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002747 int healthStatusToReport = -1;
2748 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002749
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002750 {
2751 std::unique_lock lock(mMutex);
2752 unregisterFromPendingReads();
2753
2754 healthListener = mHealthListener;
2755
2756 // Healthcheck depends on timestamp of the oldest pending read.
2757 // 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 -07002758 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2759 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002760 const auto now = Clock::now();
2761 const auto kernelTsUs = getOldestPendingReadTs();
2762 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002763 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2764 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002765 mHealthBase = {now, kernelTsUs};
2766 }
2767
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002768 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2769 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002770 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2771 registerForPendingReads();
2772 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2773 lock.unlock();
2774 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002775 return;
2776 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002777
2778 resetHealthControl();
2779
2780 // Always make sure the data loader is started.
2781 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2782
2783 // Skip any further processing if health check params are invalid.
2784 if (!isHealthParamsValid()) {
2785 LOG(DEBUG) << id()
2786 << ": Skip any further processing if health check params are invalid.";
2787 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2788 lock.unlock();
2789 onHealthStatus(healthListener, healthStatusToReport);
2790 // Triggering data loader start. This is a one-time action.
2791 fsmStep();
2792 return;
2793 }
2794
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002795 // Don't schedule timer job less than 500ms in advance.
2796 static constexpr auto kTolerance = 500ms;
2797
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002798 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2799 const auto unhealthyTimeout =
2800 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2801 const auto unhealthyMonitoring =
2802 std::max(1000ms,
2803 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2804
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002805 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002806
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002807 Milliseconds checkBackAfter;
2808 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002809 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002810 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002811 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002812 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002813 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002814 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002815 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2816 } else {
2817 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002818 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002819 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2820 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002821 // Adjust health status based on stream status
2822 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002823 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002824 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002825 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2826 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002827 }
2828
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002829 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002830 if (healthStatusToReport != -1) {
2831 onHealthStatus(healthListener, healthStatusToReport);
2832 }
2833
2834 fsmStep();
2835}
2836
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002837Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2838 BootClockTsUs kernelTsUs) {
2839 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2840 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2841 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2842}
2843
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002844const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2845 if (mHealthPath.empty()) {
2846 resetHealthControl();
2847 return mHealthControl;
2848 }
2849 if (mHealthControl.pendingReads() < 0) {
2850 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2851 }
2852 if (mHealthControl.pendingReads() < 0) {
2853 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2854 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2855 << mHealthControl.logs() << ")";
2856 }
2857 return mHealthControl;
2858}
2859
2860void IncrementalService::DataLoaderStub::resetHealthControl() {
2861 mHealthControl = {};
2862}
2863
2864BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2865 auto result = kMaxBootClockTsUs;
2866
2867 const auto& control = initializeHealthControl();
2868 if (control.pendingReads() < 0) {
2869 return result;
2870 }
2871
Songchun Fan6944f1e2020-11-06 15:24:24 -08002872 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002873 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002874 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002875 // Clear previous pending reads
2876 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002877 return result;
2878 }
2879
2880 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002881 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002882
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002883 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002884}
2885
2886void IncrementalService::DataLoaderStub::registerForPendingReads() {
2887 const auto pendingReadsFd = mHealthControl.pendingReads();
2888 if (pendingReadsFd < 0) {
2889 return;
2890 }
2891
2892 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2893
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002894 mService.mLooper->addFd(
2895 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2896 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002897 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002898 self->updateHealthStatus(/*baseline=*/true);
2899 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002900 },
2901 this);
2902 mService.mLooper->wake();
2903}
2904
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002905BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2906 auto result = kMaxBootClockTsUs;
2907 for (auto&& pendingRead : mLastPendingReads) {
2908 result = std::min(result, pendingRead.bootClockTsUs);
2909 }
2910 return result;
2911}
2912
2913long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
2914 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
2915 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
2916 return 0;
2917 }
2918 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
2919}
2920
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002921void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002922 const auto pendingReadsFd = mHealthControl.pendingReads();
2923 if (pendingReadsFd < 0) {
2924 return;
2925 }
2926
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002927 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2928
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002929 mService.mLooper->removeFd(pendingReadsFd);
2930 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002931}
2932
Songchun Fan2570ec02020-10-08 17:22:33 -07002933void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002934 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002935 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002936 mHealthCheckParams = healthCheckParams;
2937 mHealthListener = std::move(healthListener);
2938 if (!mHealthListener) {
2939 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07002940 }
2941}
2942
Songchun Fan6944f1e2020-11-06 15:24:24 -08002943static std::string toHexString(const RawMetadata& metadata) {
2944 int n = metadata.size();
2945 std::string res(n * 2, '\0');
2946 // Same as incfs::toString(fileId)
2947 static constexpr char kHexChar[] = "0123456789abcdef";
2948 for (int i = 0; i < n; ++i) {
2949 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2950 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2951 }
2952 return res;
2953}
2954
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002955void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002956 dprintf(fd, " dataLoader: {\n");
2957 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002958 dprintf(fd, " currentStatusTs: %lldmcs\n",
2959 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002960 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2961 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002962 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002963 dprintf(fd, " health: {\n");
2964 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2965 dprintf(fd, " base: %lldmcs (%lld)\n",
2966 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2967 (long long)mHealthBase.kernelTsUs);
2968 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2969 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2970 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2971 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002972 dprintf(fd, " lastPendingReads: \n");
2973 const auto control = mService.mIncFs->openMount(mHealthPath);
2974 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07002975 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08002976 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2977 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2978 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2979 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2980 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002981 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
2982 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
2983 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002984 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002985 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002986 dprintf(fd, " dataLoaderParams: {\n");
2987 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2988 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2989 dprintf(fd, " className: %s\n", params.className.c_str());
2990 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2991 dprintf(fd, " }\n");
2992 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002993}
2994
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002995void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2996 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002997}
2998
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002999binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3000 bool enableReadLogs, int32_t* _aidl_return) {
3001 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3002 return binder::Status::ok();
3003}
3004
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003005FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3006 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3007}
3008
Songchun Fan3c82a302019-11-29 14:23:45 -08003009} // namespace android::incremental