blob: ce6e6ab1e29c2509afcecdc07379ecadcd6d3b07 [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;
77 // 10s, 100s (~2min), 1000s (~15min), 10000s (~3hrs)
78 static constexpr auto minBindDelay = 10s;
79 static constexpr auto maxBindDelay = 10000s;
80 static constexpr auto bindDelayMultiplier = 10;
81 static constexpr auto bindDelayJitterDivider = 10;
Songchun Fan3c82a302019-11-29 14:23:45 -080082};
83
84static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070085 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080086 return c;
87}
88
89template <base::LogSeverity level = base::ERROR>
90bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
91 auto cstr = path::c_str(name);
92 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080093 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080094 PLOG(level) << "Can't create directory '" << name << '\'';
95 return false;
96 }
97 struct stat st;
98 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
99 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
100 return false;
101 }
102 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800103 if (::chmod(cstr, mode)) {
104 PLOG(level) << "Changing permission failed for '" << name << '\'';
105 return false;
106 }
107
Songchun Fan3c82a302019-11-29 14:23:45 -0800108 return true;
109}
110
111static std::string toMountKey(std::string_view path) {
112 if (path.empty()) {
113 return "@none";
114 }
115 if (path == "/"sv) {
116 return "@root";
117 }
118 if (path::isAbsolute(path)) {
119 path.remove_prefix(1);
120 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700121 if (path.size() > 16) {
122 path = path.substr(0, 16);
123 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800124 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700125 std::replace_if(
126 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
127 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800128}
129
130static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
131 std::string_view path) {
132 auto mountKey = toMountKey(path);
133 const auto prefixSize = mountKey.size();
134 for (int counter = 0; counter < 1000;
135 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
136 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800137 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800138 return {mountKey, mountRoot};
139 }
140 }
141 return {};
142}
143
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700144template <class Map>
145typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
146 const auto nextIt = map.upper_bound(path);
147 if (nextIt == map.begin()) {
148 return map.end();
149 }
150 const auto suspectIt = std::prev(nextIt);
151 if (!path::startsWith(path, suspectIt->first)) {
152 return map.end();
153 }
154 return suspectIt;
155}
156
157static base::unique_fd dup(base::borrowed_fd fd) {
158 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
159 return base::unique_fd(res);
160}
161
Songchun Fan3c82a302019-11-29 14:23:45 -0800162template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700163static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800164 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800165 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800166 ProtoMessage message;
167 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
168}
169
170static bool isValidMountTarget(std::string_view path) {
171 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
172}
173
174std::string makeBindMdName() {
175 static constexpr auto uuidStringSize = 36;
176
177 uuid_t guid;
178 uuid_generate(guid);
179
180 std::string name;
181 const auto prefixSize = constants().mountpointMdPrefix.size();
182 name.reserve(prefixSize + uuidStringSize);
183
184 name = constants().mountpointMdPrefix;
185 name.resize(prefixSize + uuidStringSize);
186 uuid_unparse(guid, name.data() + prefixSize);
187
188 return name;
189}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700190
191static bool checkReadLogsDisabledMarker(std::string_view root) {
192 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
193 struct stat st;
194 return (::stat(markerPath, &st) == 0);
195}
196
Songchun Fan3c82a302019-11-29 14:23:45 -0800197} // namespace
198
199IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700200 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700201 dataLoaderStub->cleanupResources();
202 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700203 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700204 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800205 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
206 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700207 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800208 incrementalService.mVold->unmountIncFs(target);
209 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700210 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800211 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
212 cleanupFilesystem(root);
213}
214
215auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800216 std::string name;
217 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
218 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
219 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800220 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
221 constants().storagePrefix.data(), id, no);
222 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800223 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800224 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800225 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
226 } else if (err != EEXIST) {
227 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
228 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800229 }
230 }
231 nextStorageDirNo = 0;
232 return storages.end();
233}
234
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700235template <class Func>
236static auto makeCleanup(Func&& f) {
237 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700238 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700239 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
240}
241
242static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
243 return {::opendir(dir), ::closedir};
244}
245
246static auto openDir(std::string_view dir) {
247 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800248}
249
250static int rmDirContent(const char* path) {
251 auto dir = openDir(path);
252 if (!dir) {
253 return -EINVAL;
254 }
255 while (auto entry = ::readdir(dir.get())) {
256 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
257 continue;
258 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700259 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800260 if (entry->d_type == DT_DIR) {
261 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
262 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
263 return err;
264 }
265 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
266 PLOG(WARNING) << "Failed to rmdir " << fullPath;
267 return err;
268 }
269 } else {
270 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
271 PLOG(WARNING) << "Failed to delete " << fullPath;
272 return err;
273 }
274 }
275 }
276 return 0;
277}
278
Songchun Fan3c82a302019-11-29 14:23:45 -0800279void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800280 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800281 ::rmdir(path::join(root, constants().backing).c_str());
282 ::rmdir(path::join(root, constants().mount).c_str());
283 ::rmdir(path::c_str(root));
284}
285
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800286IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800287 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800288 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800289 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700290 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700291 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700292 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700293 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700294 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700295 mFs(sm.getFs()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800296 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700297 CHECK(mVold) << "Vold service is unavailable";
298 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
299 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
300 CHECK(mJni) << "JNI is unavailable";
301 CHECK(mLooper) << "Looper is unavailable";
302 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700303 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700304 CHECK(mFs) << "Fs is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700305
306 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700307 mJobProcessor = std::thread([this]() {
308 mJni->initializeForCurrentThread();
309 runJobProcessing();
310 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700311 mCmdLooperThread = std::thread([this]() {
312 mJni->initializeForCurrentThread();
313 runCmdLooper();
314 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700315
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700316 const auto mountedRootNames = adoptMountedInstances();
317 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800318}
319
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700320IncrementalService::~IncrementalService() {
321 {
322 std::lock_guard lock(mJobMutex);
323 mRunning = false;
324 }
325 mJobCondition.notify_all();
326 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700327 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700328 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700329 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700330 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700331 // Ensure that mounts are destroyed while the service is still valid.
332 mBindsByPath.clear();
333 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700334}
Songchun Fan3c82a302019-11-29 14:23:45 -0800335
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700336static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800337 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800338 case IncrementalService::BindKind::Temporary:
339 return "Temporary";
340 case IncrementalService::BindKind::Permanent:
341 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800342 }
343}
344
345void IncrementalService::onDump(int fd) {
346 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
347 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
348
349 std::unique_lock l(mLock);
350
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700351 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800352 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700353 const IncFsMount& mnt = *ifs;
354 dprintf(fd, " [%d]: {\n", id);
355 if (id != mnt.mountId) {
356 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
357 } else {
358 dprintf(fd, " mountId: %d\n", mnt.mountId);
359 dprintf(fd, " root: %s\n", mnt.root.c_str());
360 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
361 if (mnt.dataLoaderStub) {
362 mnt.dataLoaderStub->onDump(fd);
363 } else {
364 dprintf(fd, " dataLoader: null\n");
365 }
366 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
367 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700368 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800369 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str(),
370 /*stopOnFirstIncomplete=*/false)
371 .getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800372 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700373 }
374 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800375
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700376 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
377 for (auto&& [target, bind] : mnt.bindPoints) {
378 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
379 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
380 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
381 dprintf(fd, " kind: %s\n", toString(bind.kind));
382 }
383 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800384 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700385 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800386 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700387 dprintf(fd, "}\n");
388 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800389 for (auto&& [target, mountPairIt] : mBindsByPath) {
390 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700391 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
392 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
393 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
394 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800395 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700396 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800397}
398
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800399bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
400 if (ifs.dataLoaderStub->params().packageName == Constants::systemPackage) {
401 return true;
402 }
403
404 // Check all permanent binds.
405 for (auto&& [_, bindPoint] : ifs.bindPoints) {
406 if (bindPoint.kind != BindKind::Permanent) {
407 continue;
408 }
409 const auto progress = getLoadingProgressFromPath(ifs, bindPoint.sourceDir,
410 /*stopOnFirstIncomplete=*/true);
411 if (!progress.isError() && !progress.fullyLoaded()) {
412 LOG(INFO) << "Non system mount: [" << bindPoint.sourceDir
413 << "], partial progress: " << progress.getProgress() * 100 << "%";
414 return true;
415 }
416 }
417
418 return false;
419}
420
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700421void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800422 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700423 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800424 }
425
426 std::vector<IfsMountPtr> mounts;
427 {
428 std::lock_guard l(mLock);
429 mounts.reserve(mMounts.size());
430 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800431 if (ifs->mountId != id) {
432 continue;
433 }
434
435 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800436 mounts.push_back(ifs);
437 }
438 }
439 }
440
Alex Buynytskyy69941662020-04-11 21:40:37 -0700441 if (mounts.empty()) {
442 return;
443 }
444
Songchun Fan3c82a302019-11-29 14:23:45 -0800445 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700446 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800447 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700448 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800449 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800450 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800451}
452
453auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
454 for (;;) {
455 if (mNextId == kMaxStorageId) {
456 mNextId = 0;
457 }
458 auto id = ++mNextId;
459 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
460 if (inserted) {
461 return it;
462 }
463 }
464}
465
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800466StorageId IncrementalService::createStorage(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800467 std::string_view mountPoint, const content::pm::DataLoaderParamsParcel& dataLoaderParams,
468 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800469 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
470 if (!path::isAbsolute(mountPoint)) {
471 LOG(ERROR) << "path is not absolute: " << mountPoint;
472 return kInvalidStorageId;
473 }
474
475 auto mountNorm = path::normalize(mountPoint);
476 {
477 const auto id = findStorageId(mountNorm);
478 if (id != kInvalidStorageId) {
479 if (options & CreateOptions::OpenExisting) {
480 LOG(INFO) << "Opened existing storage " << id;
481 return id;
482 }
483 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
484 return kInvalidStorageId;
485 }
486 }
487
488 if (!(options & CreateOptions::CreateNew)) {
489 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
490 return kInvalidStorageId;
491 }
492
493 if (!path::isEmptyDir(mountNorm)) {
494 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
495 return kInvalidStorageId;
496 }
497 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
498 if (mountRoot.empty()) {
499 LOG(ERROR) << "Bad mount point";
500 return kInvalidStorageId;
501 }
502 // Make sure the code removes all crap it may create while still failing.
503 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
504 auto firstCleanupOnFailure =
505 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
506
507 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800508 const auto backing = path::join(mountRoot, constants().backing);
509 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800510 return kInvalidStorageId;
511 }
512
Songchun Fan3c82a302019-11-29 14:23:45 -0800513 IncFsMount::Control control;
514 {
515 std::lock_guard l(mMountOperationLock);
516 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800517
518 if (auto err = rmDirContent(backing.c_str())) {
519 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
520 return kInvalidStorageId;
521 }
522 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
523 return kInvalidStorageId;
524 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800525 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
526 return kInvalidStorageId;
527 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800528 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800529 if (!status.isOk()) {
530 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
531 return kInvalidStorageId;
532 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800533 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
534 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800535 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
536 return kInvalidStorageId;
537 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800538 int cmd = controlParcel.cmd.release().release();
539 int pendingReads = controlParcel.pendingReads.release().release();
540 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800541 int blocksWritten =
542 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
543 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800544 }
545
546 std::unique_lock l(mLock);
547 const auto mountIt = getStorageSlotLocked();
548 const auto mountId = mountIt->first;
549 l.unlock();
550
551 auto ifs =
552 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
553 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
554 // is the removal of the |ifs|.
555 firstCleanupOnFailure.release();
556
557 auto secondCleanup = [this, &l](auto itPtr) {
558 if (!l.owns_lock()) {
559 l.lock();
560 }
561 mMounts.erase(*itPtr);
562 };
563 auto secondCleanupOnFailure =
564 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
565
566 const auto storageIt = ifs->makeStorage(ifs->mountId);
567 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800568 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800569 return kInvalidStorageId;
570 }
571
572 {
573 metadata::Mount m;
574 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700575 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800576 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
577 m.mutable_loader()->set_class_name(dataLoaderParams.className);
578 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800579 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800580 if (auto err =
581 mIncFs->makeFile(ifs->control,
582 path::join(ifs->root, constants().mount,
583 constants().infoMdName),
584 0777, idFromMetadata(metadata),
585 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800586 LOG(ERROR) << "Saving mount metadata failed: " << -err;
587 return kInvalidStorageId;
588 }
589 }
590
591 const auto bk =
592 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800593 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
594 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800595 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800596 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800597 return kInvalidStorageId;
598 }
599
600 // Done here as well, all data structures are in good state.
601 secondCleanupOnFailure.release();
602
Songchun Fan3c82a302019-11-29 14:23:45 -0800603 mountIt->second = std::move(ifs);
604 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700605
Songchun Fan3c82a302019-11-29 14:23:45 -0800606 LOG(INFO) << "created storage " << mountId;
607 return mountId;
608}
609
610StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
611 StorageId linkedStorage,
612 IncrementalService::CreateOptions options) {
613 if (!isValidMountTarget(mountPoint)) {
614 LOG(ERROR) << "Mount point is invalid or missing";
615 return kInvalidStorageId;
616 }
617
618 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700619 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800620 if (!ifs) {
621 LOG(ERROR) << "Ifs unavailable";
622 return kInvalidStorageId;
623 }
624
625 const auto mountIt = getStorageSlotLocked();
626 const auto storageId = mountIt->first;
627 const auto storageIt = ifs->makeStorage(storageId);
628 if (storageIt == ifs->storages.end()) {
629 LOG(ERROR) << "Can't create a new storage";
630 mMounts.erase(mountIt);
631 return kInvalidStorageId;
632 }
633
634 l.unlock();
635
636 const auto bk =
637 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800638 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
639 std::string(storageIt->second.name), path::normalize(mountPoint),
640 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800641 err < 0) {
642 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700643 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
644 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800645 return kInvalidStorageId;
646 }
647
648 mountIt->second = ifs;
649 return storageId;
650}
651
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800652bool IncrementalService::startLoading(StorageId storage,
653 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
654 const DataLoaderStatusListener& statusListener,
655 StorageHealthCheckParams&& healthCheckParams,
656 const StorageHealthListener& healthListener,
657 const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
658 // Per Uid timeouts.
659 if (!perUidReadTimeouts.empty()) {
660 setUidReadTimeouts(storage, perUidReadTimeouts);
661 }
662
663 // Re-initialize DataLoader.
664 std::unique_lock l(mLock);
665 const auto ifs = getIfsLocked(storage);
666 if (!ifs) {
667 return false;
668 }
669 if (ifs->dataLoaderStub) {
670 ifs->dataLoaderStub->cleanupResources();
671 ifs->dataLoaderStub = {};
672 }
673 l.unlock();
674
675 // DataLoader.
676 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
677 std::move(healthCheckParams), &healthListener);
678 CHECK(dataLoaderStub);
679
680 return dataLoaderStub->requestStart();
681}
682
Songchun Fan3c82a302019-11-29 14:23:45 -0800683IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
684 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700685 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800686}
687
688StorageId IncrementalService::findStorageId(std::string_view path) const {
689 std::lock_guard l(mLock);
690 auto it = findStorageLocked(path);
691 if (it == mBindsByPath.end()) {
692 return kInvalidStorageId;
693 }
694 return it->second->second.storage;
695}
696
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800697void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700698 std::unique_lock l(mLock);
699 const auto ifs = getIfsLocked(storageId);
700 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800701 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700702 return;
703 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800704 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700705 return;
706 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800707 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700708 l.unlock();
709
710 const auto metadata = constants().readLogsDisabledMarkerName;
711 if (auto err = mIncFs->makeFile(ifs->control,
712 path::join(ifs->root, constants().mount,
713 constants().readLogsDisabledMarkerName),
714 0777, idFromMetadata(metadata), {})) {
715 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
716 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
717 return;
718 }
719
720 setStorageParams(storageId, /*enableReadLogs=*/false);
721}
722
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700723int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
724 const auto ifs = getIfs(storageId);
725 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700726 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700727 return -EINVAL;
728 }
729
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700730 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700731 if (enableReadLogs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800732 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700733 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
734 return -EPERM;
735 }
736
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800737 // Check loader usage stats permission and apop.
738 if (auto status = mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700739 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700740 !status.isOk()) {
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800741 LOG(ERROR) << " Permission: " << kLoaderUsageStats
742 << " check failed: " << status.toString8();
743 return fromBinderStatus(status);
744 }
745
746 // Check multiuser permission.
747 if (auto status = mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr,
748 params.packageName.c_str());
749 !status.isOk()) {
750 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
751 << " check failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700752 return fromBinderStatus(status);
753 }
754 }
755
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700756 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
757 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
758 return fromBinderStatus(status);
759 }
760
761 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700762 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700763 }
764
765 return 0;
766}
767
768binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700769 os::incremental::IncrementalFileSystemControlParcel control;
770 control.cmd.reset(dup(ifs.control.cmd()));
771 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700772 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700773 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700774 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700775 }
776
777 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800778 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
779 if (status.isOk()) {
780 // Store enabled state.
781 ifs.setReadLogsEnabled(enableReadLogs);
782 }
783 return status;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700784}
785
Songchun Fan3c82a302019-11-29 14:23:45 -0800786void IncrementalService::deleteStorage(StorageId storageId) {
787 const auto ifs = getIfs(storageId);
788 if (!ifs) {
789 return;
790 }
791 deleteStorage(*ifs);
792}
793
794void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
795 std::unique_lock l(ifs.lock);
796 deleteStorageLocked(ifs, std::move(l));
797}
798
799void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
800 std::unique_lock<std::mutex>&& ifsLock) {
801 const auto storages = std::move(ifs.storages);
802 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
803 const auto bindPoints = ifs.bindPoints;
804 ifsLock.unlock();
805
806 std::lock_guard l(mLock);
807 for (auto&& [id, _] : storages) {
808 if (id != ifs.mountId) {
809 mMounts.erase(id);
810 }
811 }
812 for (auto&& [path, _] : bindPoints) {
813 mBindsByPath.erase(path);
814 }
815 mMounts.erase(ifs.mountId);
816}
817
818StorageId IncrementalService::openStorage(std::string_view pathInMount) {
819 if (!path::isAbsolute(pathInMount)) {
820 return kInvalidStorageId;
821 }
822
823 return findStorageId(path::normalize(pathInMount));
824}
825
Songchun Fan3c82a302019-11-29 14:23:45 -0800826IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
827 std::lock_guard l(mLock);
828 return getIfsLocked(storage);
829}
830
831const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
832 auto it = mMounts.find(storage);
833 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700834 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700835 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800836 }
837 return it->second;
838}
839
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800840int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
841 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800842 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700843 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800844 return -EINVAL;
845 }
846
847 const auto ifs = getIfs(storage);
848 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700849 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800850 return -EINVAL;
851 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800852
Songchun Fan3c82a302019-11-29 14:23:45 -0800853 std::unique_lock l(ifs->lock);
854 const auto storageInfo = ifs->storages.find(storage);
855 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700856 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800857 return -EINVAL;
858 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700859 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700860 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700861 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700862 return -EINVAL;
863 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800864 l.unlock();
865 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800866 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
867 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800868}
869
870int IncrementalService::unbind(StorageId storage, std::string_view target) {
871 if (!path::isAbsolute(target)) {
872 return -EINVAL;
873 }
874
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700875 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800876
877 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
878 // otherwise there's a chance to unmount something completely unrelated
879 const auto norm = path::normalize(target);
880 std::unique_lock l(mLock);
881 const auto storageIt = mBindsByPath.find(norm);
882 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
883 return -EINVAL;
884 }
885 const auto bindIt = storageIt->second;
886 const auto storageId = bindIt->second.storage;
887 const auto ifs = getIfsLocked(storageId);
888 if (!ifs) {
889 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
890 << " is missing";
891 return -EFAULT;
892 }
893 mBindsByPath.erase(storageIt);
894 l.unlock();
895
896 mVold->unmountIncFs(bindIt->first);
897 std::unique_lock l2(ifs->lock);
898 if (ifs->bindPoints.size() <= 1) {
899 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700900 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800901 } else {
902 const std::string savedFile = std::move(bindIt->second.savedFilename);
903 ifs->bindPoints.erase(bindIt);
904 l2.unlock();
905 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800906 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800907 }
908 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700909
Songchun Fan3c82a302019-11-29 14:23:45 -0800910 return 0;
911}
912
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700913std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700914 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700915 std::string_view path) const {
916 if (!path::isAbsolute(path)) {
917 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700918 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700919 auto normPath = path::normalize(path);
920 if (path::startsWith(normPath, storageIt->second.name)) {
921 return normPath;
922 }
923 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700924 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
925 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700926 return {};
927 }
928 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700929}
930
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700931std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700932 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700933 std::unique_lock l(ifs.lock);
934 const auto storageInfo = ifs.storages.find(storage);
935 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800936 return {};
937 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700938 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800939}
940
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800941int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700942 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800943 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700944 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800945 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700946 LOG(ERROR) << "Internal error: storageId " << storage
947 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800948 return -EINVAL;
949 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700950 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700951 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800952 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800953 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700954 if (!data.empty()) {
955 if (auto err = setFileContent(ifs, id, path, data); err) {
956 return err;
957 }
958 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800959 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800960 }
961 return -EINVAL;
962}
963
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800964int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800965 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700966 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800967 if (normPath.empty()) {
968 return -EINVAL;
969 }
970 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800971 }
972 return -EINVAL;
973}
974
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800975int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800976 const auto ifs = getIfs(storageId);
977 if (!ifs) {
978 return -EINVAL;
979 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700980 return makeDirs(*ifs, storageId, path, mode);
981}
982
983int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
984 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800985 std::string normPath = normalizePathToStorage(ifs, storageId, path);
986 if (normPath.empty()) {
987 return -EINVAL;
988 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700989 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800990}
991
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800992int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
993 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700994 std::unique_lock l(mLock);
995 auto ifsSrc = getIfsLocked(sourceStorageId);
996 if (!ifsSrc) {
997 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800998 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700999 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1000 return -EINVAL;
1001 }
1002 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001003 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1004 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001005 if (normOldPath.empty() || normNewPath.empty()) {
1006 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1007 return -EINVAL;
1008 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001009 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1010 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1011 << " to " << newPath << "[" << normNewPath << "]";
1012 return err;
1013 }
1014 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001015}
1016
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001017int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001018 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001019 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001020 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001021 }
1022 return -EINVAL;
1023}
1024
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001025int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1026 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001027 std::string&& target, BindKind kind,
1028 std::unique_lock<std::mutex>& mainLock) {
1029 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001030 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001031 return -EINVAL;
1032 }
1033
1034 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001035 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001036 if (kind != BindKind::Temporary) {
1037 metadata::BindPoint bp;
1038 bp.set_storage_id(storage);
1039 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001040 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001041 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001042 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001043 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001044 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001045 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1046 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1047 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001048 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001049 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001050 return int(node);
1051 }
1052 }
1053
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001054 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1055 std::move(target), kind, mainLock);
1056 if (res) {
1057 mIncFs->unlink(ifs.control, metadataFullPath);
1058 }
1059 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001060}
1061
1062int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001063 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001064 std::string&& target, BindKind kind,
1065 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001066 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001067 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001068 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001069 if (!status.isOk()) {
1070 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1071 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1072 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1073 : status.serviceSpecificErrorCode() == 0
1074 ? -EFAULT
1075 : status.serviceSpecificErrorCode()
1076 : -EIO;
1077 }
1078 }
1079
1080 if (!mainLock.owns_lock()) {
1081 mainLock.lock();
1082 }
1083 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001084 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1085 std::move(target), kind);
1086 return 0;
1087}
1088
1089void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1090 std::string&& metadataName, std::string&& source,
1091 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001092 const auto [it, _] =
1093 ifs.bindPoints.insert_or_assign(target,
1094 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001095 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001096 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001097}
1098
1099RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1100 const auto ifs = getIfs(storage);
1101 if (!ifs) {
1102 return {};
1103 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001104 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001105 if (normPath.empty()) {
1106 return {};
1107 }
1108 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001109}
1110
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001111RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001112 const auto ifs = getIfs(storage);
1113 if (!ifs) {
1114 return {};
1115 }
1116 return mIncFs->getMetadata(ifs->control, node);
1117}
1118
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001119void IncrementalService::setUidReadTimeouts(
1120 StorageId storage, const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
1121 using microseconds = std::chrono::microseconds;
1122 using milliseconds = std::chrono::milliseconds;
1123
1124 auto maxPendingTimeUs = microseconds(0);
1125 for (const auto& timeouts : perUidReadTimeouts) {
1126 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1127 }
1128 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001129 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001130 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1131 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001132 return;
1133 }
1134
1135 const auto ifs = getIfs(storage);
1136 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001137 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001138 return;
1139 }
1140
1141 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1142 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1143 return;
1144 }
1145
1146 const auto timeout = std::chrono::duration_cast<milliseconds>(maxPendingTimeUs) -
1147 Constants::perUidTimeoutOffset;
1148 updateUidReadTimeouts(storage, Clock::now() + timeout);
1149}
1150
1151void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1152 const auto ifs = getIfs(storage);
1153 if (!ifs) {
1154 return;
1155 }
1156
1157 mIncFs->setUidReadTimeouts(ifs->control, {});
1158}
1159
1160void IncrementalService::updateUidReadTimeouts(StorageId storage, Clock::time_point timeLimit) {
1161 // Reached maximum timeout.
1162 if (Clock::now() >= timeLimit) {
1163 return clearUidReadTimeouts(storage);
1164 }
1165
1166 // Still loading?
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001167 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/true);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001168 if (progress.isError()) {
1169 // Something is wrong, abort.
1170 return clearUidReadTimeouts(storage);
1171 }
1172
1173 if (progress.started() && progress.fullyLoaded()) {
1174 // Fully loaded, check readLogs collection.
1175 const auto ifs = getIfs(storage);
1176 if (!ifs->readLogsEnabled()) {
1177 return clearUidReadTimeouts(storage);
1178 }
1179 }
1180
1181 const auto timeLeft = timeLimit - Clock::now();
1182 if (timeLeft < Constants::progressUpdateInterval) {
1183 // Don't bother.
1184 return clearUidReadTimeouts(storage);
1185 }
1186
1187 addTimedJob(*mTimedQueue, storage, Constants::progressUpdateInterval,
1188 [this, storage, timeLimit]() { updateUidReadTimeouts(storage, timeLimit); });
1189}
1190
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001191std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1192 std::unordered_set<std::string_view> mountedRootNames;
1193 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1194 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1195 for (auto [source, target] : binds) {
1196 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1197 LOG(INFO) << " " << path::join(root, source);
1198 }
1199
1200 // Ensure it's a kind of a mount that's managed by IncrementalService
1201 if (path::basename(root) != constants().mount ||
1202 path::basename(backingDir) != constants().backing) {
1203 return;
1204 }
1205 const auto expectedRoot = path::dirname(root);
1206 if (path::dirname(backingDir) != expectedRoot) {
1207 return;
1208 }
1209 if (path::dirname(expectedRoot) != mIncrementalDir) {
1210 return;
1211 }
1212 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1213 return;
1214 }
1215
1216 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1217
1218 // make sure we clean up the mount if it happens to be a bad one.
1219 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1220 auto cleanupFiles = makeCleanup([&]() {
1221 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1222 IncFsMount::cleanupFilesystem(expectedRoot);
1223 });
1224 auto cleanupMounts = makeCleanup([&]() {
1225 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1226 for (auto&& [_, target] : binds) {
1227 mVold->unmountIncFs(std::string(target));
1228 }
1229 mVold->unmountIncFs(std::string(root));
1230 });
1231
1232 auto control = mIncFs->openMount(root);
1233 if (!control) {
1234 LOG(INFO) << "failed to open mount " << root;
1235 return;
1236 }
1237
1238 auto mountRecord =
1239 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1240 path::join(root, constants().infoMdName));
1241 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1242 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1243 return;
1244 }
1245
1246 auto mountId = mountRecord.storage().id();
1247 mNextId = std::max(mNextId, mountId + 1);
1248
1249 DataLoaderParamsParcel dataLoaderParams;
1250 {
1251 const auto& loader = mountRecord.loader();
1252 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1253 dataLoaderParams.packageName = loader.package_name();
1254 dataLoaderParams.className = loader.class_name();
1255 dataLoaderParams.arguments = loader.arguments();
1256 }
1257
1258 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1259 std::move(control), *this);
1260 cleanupFiles.release(); // ifs will take care of that now
1261
Alex Buynytskyy04035452020-06-06 20:15:58 -07001262 // Check if marker file present.
1263 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001264 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001265 }
1266
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001267 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1268 auto d = openDir(root);
1269 while (auto e = ::readdir(d.get())) {
1270 if (e->d_type == DT_REG) {
1271 auto name = std::string_view(e->d_name);
1272 if (name.starts_with(constants().mountpointMdPrefix)) {
1273 permanentBindPoints
1274 .emplace_back(name,
1275 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1276 ifs->control,
1277 path::join(root,
1278 name)));
1279 if (permanentBindPoints.back().second.dest_path().empty() ||
1280 permanentBindPoints.back().second.source_subdir().empty()) {
1281 permanentBindPoints.pop_back();
1282 mIncFs->unlink(ifs->control, path::join(root, name));
1283 } else {
1284 LOG(INFO) << "Permanent bind record: '"
1285 << permanentBindPoints.back().second.source_subdir() << "'->'"
1286 << permanentBindPoints.back().second.dest_path() << "'";
1287 }
1288 }
1289 } else if (e->d_type == DT_DIR) {
1290 if (e->d_name == "."sv || e->d_name == ".."sv) {
1291 continue;
1292 }
1293 auto name = std::string_view(e->d_name);
1294 if (name.starts_with(constants().storagePrefix)) {
1295 int storageId;
1296 const auto res =
1297 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1298 name.data() + name.size(), storageId);
1299 if (res.ec != std::errc{} || *res.ptr != '_') {
1300 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1301 << "' for mount " << expectedRoot;
1302 continue;
1303 }
1304 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1305 if (!inserted) {
1306 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1307 << " for mount " << expectedRoot;
1308 continue;
1309 }
1310 ifs->storages.insert_or_assign(storageId,
1311 IncFsMount::Storage{path::join(root, name)});
1312 mNextId = std::max(mNextId, storageId + 1);
1313 }
1314 }
1315 }
1316
1317 if (ifs->storages.empty()) {
1318 LOG(WARNING) << "No valid storages in mount " << root;
1319 return;
1320 }
1321
1322 // now match the mounted directories with what we expect to have in the metadata
1323 {
1324 std::unique_lock l(mLock, std::defer_lock);
1325 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1326 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1327 [&, bindRecord = bindRecord](auto&& bind) {
1328 return bind.second == bindRecord.dest_path() &&
1329 path::join(root, bind.first) ==
1330 bindRecord.source_subdir();
1331 });
1332 if (mountedIt != binds.end()) {
1333 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1334 << " to mount " << mountedIt->first;
1335 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1336 std::move(*bindRecord.mutable_source_subdir()),
1337 std::move(*bindRecord.mutable_dest_path()),
1338 BindKind::Permanent);
1339 if (mountedIt != binds.end() - 1) {
1340 std::iter_swap(mountedIt, binds.end() - 1);
1341 }
1342 binds = binds.first(binds.size() - 1);
1343 } else {
1344 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1345 << ", mounting";
1346 // doesn't exist - try mounting back
1347 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1348 std::move(*bindRecord.mutable_source_subdir()),
1349 std::move(*bindRecord.mutable_dest_path()),
1350 BindKind::Permanent, l)) {
1351 mIncFs->unlink(ifs->control, metadataFile);
1352 }
1353 }
1354 }
1355 }
1356
1357 // if anything stays in |binds| those are probably temporary binds; system restarted since
1358 // they were mounted - so let's unmount them all.
1359 for (auto&& [source, target] : binds) {
1360 if (source.empty()) {
1361 continue;
1362 }
1363 mVold->unmountIncFs(std::string(target));
1364 }
1365 cleanupMounts.release(); // ifs now manages everything
1366
1367 if (ifs->bindPoints.empty()) {
1368 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1369 deleteStorage(*ifs);
1370 return;
1371 }
1372
1373 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1374 CHECK(ifs->dataLoaderStub);
1375
1376 mountedRootNames.insert(path::basename(ifs->root));
1377
1378 // not locking here at all: we're still in the constructor, no other calls can happen
1379 mMounts[ifs->mountId] = std::move(ifs);
1380 });
1381
1382 return mountedRootNames;
1383}
1384
1385void IncrementalService::mountExistingImages(
1386 const std::unordered_set<std::string_view>& mountedRootNames) {
1387 auto dir = openDir(mIncrementalDir);
1388 if (!dir) {
1389 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1390 return;
1391 }
1392 while (auto entry = ::readdir(dir.get())) {
1393 if (entry->d_type != DT_DIR) {
1394 continue;
1395 }
1396 std::string_view name = entry->d_name;
1397 if (!name.starts_with(constants().mountKeyPrefix)) {
1398 continue;
1399 }
1400 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001401 continue;
1402 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001403 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001404 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001405 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001406 }
1407 }
1408}
1409
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001410bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001411 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001412 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001413
Songchun Fan3c82a302019-11-29 14:23:45 -08001414 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001415 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001416 if (!status.isOk()) {
1417 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1418 return false;
1419 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001420
1421 int cmd = controlParcel.cmd.release().release();
1422 int pendingReads = controlParcel.pendingReads.release().release();
1423 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001424 int blocksWritten =
1425 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1426 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001427
1428 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1429
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001430 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1431 path::join(mountTarget, constants().infoMdName));
1432 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001433 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1434 return false;
1435 }
1436
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001437 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001438 mNextId = std::max(mNextId, ifs->mountId + 1);
1439
Alex Buynytskyy04035452020-06-06 20:15:58 -07001440 // Check if marker file present.
1441 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001442 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001443 }
1444
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001445 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001446 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001447 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001448 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001449 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001450 dataLoaderParams.packageName = loader.package_name();
1451 dataLoaderParams.className = loader.class_name();
1452 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001453 }
1454
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001455 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001456 CHECK(ifs->dataLoaderStub);
1457
Songchun Fan3c82a302019-11-29 14:23:45 -08001458 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001459 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001460 while (auto e = ::readdir(d.get())) {
1461 if (e->d_type == DT_REG) {
1462 auto name = std::string_view(e->d_name);
1463 if (name.starts_with(constants().mountpointMdPrefix)) {
1464 bindPoints.emplace_back(name,
1465 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1466 ifs->control,
1467 path::join(mountTarget,
1468 name)));
1469 if (bindPoints.back().second.dest_path().empty() ||
1470 bindPoints.back().second.source_subdir().empty()) {
1471 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001472 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001473 }
1474 }
1475 } else if (e->d_type == DT_DIR) {
1476 if (e->d_name == "."sv || e->d_name == ".."sv) {
1477 continue;
1478 }
1479 auto name = std::string_view(e->d_name);
1480 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001481 int storageId;
1482 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1483 name.data() + name.size(), storageId);
1484 if (res.ec != std::errc{} || *res.ptr != '_') {
1485 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1486 << root;
1487 continue;
1488 }
1489 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001490 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001491 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001492 << " for mount " << root;
1493 continue;
1494 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001495 ifs->storages.insert_or_assign(storageId,
1496 IncFsMount::Storage{
1497 path::join(root, constants().mount, name)});
1498 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001499 }
1500 }
1501 }
1502
1503 if (ifs->storages.empty()) {
1504 LOG(WARNING) << "No valid storages in mount " << root;
1505 return false;
1506 }
1507
1508 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001509 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001510 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001511 for (auto&& bp : bindPoints) {
1512 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1513 std::move(*bp.second.mutable_source_subdir()),
1514 std::move(*bp.second.mutable_dest_path()),
1515 BindKind::Permanent, l);
1516 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001517 }
1518
1519 if (bindCount == 0) {
1520 LOG(WARNING) << "No valid bind points for mount " << root;
1521 deleteStorage(*ifs);
1522 return false;
1523 }
1524
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001525 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001526 mMounts[ifs->mountId] = std::move(ifs);
1527 return true;
1528}
1529
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001530void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001531 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001532 while (mRunning.load(std::memory_order_relaxed)) {
1533 mLooper->pollAll(kTimeoutMsecs);
1534 }
1535}
1536
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001537IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001538 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001539 const DataLoaderStatusListener* statusListener,
1540 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001541 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001542 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1543 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001544 return ifs.dataLoaderStub;
1545}
1546
1547void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001548 const DataLoaderStatusListener* statusListener,
1549 StorageHealthCheckParams&& healthCheckParams,
1550 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001551 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001552 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001553 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001554 }
1555
Songchun Fan3c82a302019-11-29 14:23:45 -08001556 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001557 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001558 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1559 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1560 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001561 if (ifs.control.blocksWritten() >= 0) {
1562 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1563 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001564 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001565
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001566 ifs.dataLoaderStub =
1567 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001568 statusListener, std::move(healthCheckParams), healthListener,
1569 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001570}
1571
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001572template <class Duration>
1573static long elapsedMcs(Duration start, Duration end) {
1574 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1575}
1576
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001577template <class Duration>
1578static constexpr auto castToMs(Duration d) {
1579 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1580}
1581
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001582// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001583// Lib files should be placed next to the APK file in the following matter:
1584// Example:
1585// /path/to/base.apk
1586// /path/to/lib/arm/first.so
1587// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001588bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1589 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001590 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001591 auto start = Clock::now();
1592
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001593 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001594 if (!ifs) {
1595 LOG(ERROR) << "Invalid storage " << storage;
1596 return false;
1597 }
1598
Songchun Fanc8975312020-07-13 12:14:37 -07001599 const auto targetLibPathRelativeToStorage =
1600 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1601 libDirRelativePath);
1602
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001603 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001604 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1605 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001606 << " errno: " << res;
1607 return false;
1608 }
1609
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001610 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001611 ZipArchiveHandle zipFileHandle;
1612 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001613 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1614 return false;
1615 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001616
1617 // Need a shared pointer: will be passing it into all unpacking jobs.
1618 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001619 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001620 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001621 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001622 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1623 return false;
1624 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001625 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001626 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1627
1628 auto openZipTs = Clock::now();
1629
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001630 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1631 incfs::FileId sourceId;
1632 if (mapFiles) {
1633 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1634 if (!incfs::isValidFileId(sourceId)) {
1635 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1636 << "', mapping disabled";
1637 mapFiles = false;
1638 }
1639 }
1640
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001641 std::vector<Job> jobQueue;
1642 ZipEntry entry;
1643 std::string_view fileName;
1644 while (!Next(cookie, &entry, &fileName)) {
1645 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001646 continue;
1647 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001648
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001649 const auto entryUncompressed = entry.method == kCompressStored;
1650 const auto entryPageAligned = (entry.offset & (constants().blockSize - 1)) == 0;
1651
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001652 if (!extractNativeLibs) {
1653 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001654 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001655 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1656 return false;
1657 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001658 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001659 LOG(WARNING) << "Library " << fileName
1660 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1661 << entry.offset;
1662 return false;
1663 }
1664 continue;
1665 }
1666
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001667 auto startFileTs = Clock::now();
1668
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001669 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001670 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001671 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001672 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001673 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001674 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001675 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1676 << "; skipping extraction, spent "
1677 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1678 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001679 continue;
1680 }
1681
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001682 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1683 incfs::NewMappedFileParams mappedFileParams = {
1684 .sourceId = sourceId,
1685 .sourceOffset = entry.offset,
1686 .size = entry.uncompressed_length,
1687 };
1688
1689 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1690 mappedFileParams);
1691 res == 0) {
1692 if (perfLoggingEnabled()) {
1693 auto doneTs = Clock::now();
1694 LOG(INFO) << "incfs: Mapped " << libName << ": "
1695 << elapsedMcs(startFileTs, doneTs) << "mcs";
1696 }
1697 continue;
1698 } else {
1699 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1700 << "; falling back to full extraction";
1701 }
1702 }
1703
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001704 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001705 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001706 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001707 .signature = {},
1708 // Metadata of the new lib file is its relative path
1709 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1710 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001711 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001712 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001713 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001714 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001715 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001716 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001717 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001718
1719 auto makeFileTs = Clock::now();
1720
Songchun Fanafaf6e92020-03-18 14:12:20 -07001721 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001722 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001723 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001724 LOG(INFO) << "incfs: Extracted " << libName
1725 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001726 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001727 continue;
1728 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001729
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001730 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1731 libFileId, libPath = std::move(targetLibPath),
1732 makeFileTs]() mutable {
1733 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001734 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001735
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001736 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001737 auto prepareJobTs = Clock::now();
1738 LOG(INFO) << "incfs: Processed " << libName << ": "
1739 << elapsedMcs(startFileTs, prepareJobTs)
1740 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1741 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001742 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001743 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001744
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001745 auto processedTs = Clock::now();
1746
1747 if (!jobQueue.empty()) {
1748 {
1749 std::lock_guard lock(mJobMutex);
1750 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001751 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001752 if (existingJobs.empty()) {
1753 existingJobs = std::move(jobQueue);
1754 } else {
1755 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1756 std::move_iterator(jobQueue.end()));
1757 }
1758 }
1759 }
1760 mJobCondition.notify_all();
1761 }
1762
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001763 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001764 auto end = Clock::now();
1765 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1766 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1767 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001768 << " make files: " << elapsedMcs(openZipTs, processedTs)
1769 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001770 }
1771
1772 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001773}
1774
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001775void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1776 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001777 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001778 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001779 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001780 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001781 return;
1782 }
1783
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001784 auto startedTs = Clock::now();
1785
1786 // Write extracted data to new file
1787 // NOTE: don't zero-initialize memory, it may take a while for nothing
1788 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1789 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001790 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001791 return;
1792 }
1793
1794 auto extractFileTs = Clock::now();
1795
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001796 if (setFileContent(ifs, libFileId, debugLibPath,
1797 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001798 return;
1799 }
1800
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001801 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001802 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001803 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1804 << entry.compressed_length << " -> " << entry.uncompressed_length
1805 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001806 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1807 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001808 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001809 }
1810}
1811
1812bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001813 struct WaitPrinter {
1814 const Clock::time_point startTs = Clock::now();
1815 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001816 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001817 const auto endTs = Clock::now();
1818 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1819 << elapsedMcs(startTs, endTs) << "mcs";
1820 }
1821 }
1822 } waitPrinter;
1823
1824 MountId mount;
1825 {
1826 auto ifs = getIfs(storage);
1827 if (!ifs) {
1828 return true;
1829 }
1830 mount = ifs->mountId;
1831 }
1832
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001833 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001834 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001835 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001836 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001837 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001838 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001839}
1840
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001841int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1842 std::string_view debugFilePath,
1843 std::span<const uint8_t> data) const {
1844 auto startTs = Clock::now();
1845
1846 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1847 if (!writeFd.ok()) {
1848 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1849 << " errno: " << writeFd.get();
1850 return writeFd.get();
1851 }
1852
1853 const auto dataLength = data.size();
1854
1855 auto openFileTs = Clock::now();
1856 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1857 std::vector<IncFsDataBlock> instructions(numBlocks);
1858 for (int i = 0; i < numBlocks; i++) {
1859 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1860 instructions[i] = IncFsDataBlock{
1861 .fileFd = writeFd.get(),
1862 .pageIndex = static_cast<IncFsBlockIndex>(i),
1863 .compression = INCFS_COMPRESSION_KIND_NONE,
1864 .kind = INCFS_BLOCK_KIND_DATA,
1865 .dataSize = static_cast<uint32_t>(blockSize),
1866 .data = reinterpret_cast<const char*>(data.data()),
1867 };
1868 data = data.subspan(blockSize);
1869 }
1870 auto prepareInstsTs = Clock::now();
1871
1872 size_t res = mIncFs->writeBlocks(instructions);
1873 if (res != instructions.size()) {
1874 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1875 return res;
1876 }
1877
1878 if (perfLoggingEnabled()) {
1879 auto endTs = Clock::now();
1880 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1881 << " bytes): " << elapsedMcs(startTs, endTs)
1882 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1883 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1884 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1885 }
1886
1887 return 0;
1888}
1889
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001890int IncrementalService::isFileFullyLoaded(StorageId storage, std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001891 std::unique_lock l(mLock);
1892 const auto ifs = getIfsLocked(storage);
1893 if (!ifs) {
1894 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1895 return -EINVAL;
1896 }
1897 const auto storageInfo = ifs->storages.find(storage);
1898 if (storageInfo == ifs->storages.end()) {
1899 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1900 return -EINVAL;
1901 }
1902 l.unlock();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001903 return isFileFullyLoadedFromPath(*ifs, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001904}
1905
1906int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1907 std::string_view filePath) const {
1908 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1909 if (filledBlocks < 0) {
1910 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1911 << filePath << " errno: " << filledBlocks;
1912 return filledBlocks;
1913 }
1914 if (totalBlocks < filledBlocks) {
1915 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1916 return -EINVAL;
1917 }
1918 return totalBlocks - filledBlocks;
1919}
1920
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001921IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001922 StorageId storage, bool stopOnFirstIncomplete) const {
Songchun Fan374f7652020-08-20 08:40:29 -07001923 std::unique_lock l(mLock);
1924 const auto ifs = getIfsLocked(storage);
1925 if (!ifs) {
1926 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001927 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001928 }
1929 const auto storageInfo = ifs->storages.find(storage);
1930 if (storageInfo == ifs->storages.end()) {
1931 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001932 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001933 }
1934 l.unlock();
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001935 return getLoadingProgressFromPath(*ifs, storageInfo->second.name, stopOnFirstIncomplete);
Songchun Fan374f7652020-08-20 08:40:29 -07001936}
1937
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001938IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001939 const IncFsMount& ifs, std::string_view storagePath,
1940 const bool stopOnFirstIncomplete) const {
1941 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
1942 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07001943 const auto [filledBlocksCount, totalBlocksCount] =
1944 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001945 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
1946 filledBlocksCount == -ENOENT) {
1947 // a kind of a file that's not really being loaded, e.g. a mapped range
1948 // an older IncFS used to return ENOENT in this case, so handle it the same way
1949 return true;
1950 }
Songchun Fan374f7652020-08-20 08:40:29 -07001951 if (filledBlocksCount < 0) {
1952 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1953 << " errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001954 error = filledBlocksCount;
1955 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07001956 }
1957 totalBlocks += totalBlocksCount;
1958 filledBlocks += filledBlocksCount;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001959 if (stopOnFirstIncomplete && filledBlocks < totalBlocks) {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001960 return false;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001961 }
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001962 return true;
1963 });
Songchun Fan374f7652020-08-20 08:40:29 -07001964
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001965 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07001966}
1967
Songchun Fana7098592020-09-03 11:45:53 -07001968bool IncrementalService::updateLoadingProgress(
1969 StorageId storage, const StorageLoadingProgressListener& progressListener) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001970 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/false);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001971 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07001972 // Failed to get progress from incfs, abort.
1973 return false;
1974 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001975 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
1976 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07001977 // Stop updating progress once it is fully loaded
1978 return true;
1979 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001980 addTimedJob(*mProgressUpdateJobQueue, storage,
1981 Constants::progressUpdateInterval /* repeat after 1s */,
Songchun Fana7098592020-09-03 11:45:53 -07001982 [storage, progressListener, this]() {
1983 updateLoadingProgress(storage, progressListener);
1984 });
1985 return true;
1986}
1987
1988bool IncrementalService::registerLoadingProgressListener(
1989 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1990 return updateLoadingProgress(storage, progressListener);
1991}
1992
1993bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
1994 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
1995}
1996
Songchun Fan2570ec02020-10-08 17:22:33 -07001997bool IncrementalService::registerStorageHealthListener(
1998 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
1999 const StorageHealthListener& healthListener) {
2000 DataLoaderStubPtr dataLoaderStub;
2001 {
2002 std::unique_lock l(mLock);
2003 const auto& ifs = getIfsLocked(storage);
2004 if (!ifs) {
2005 return false;
2006 }
2007 dataLoaderStub = ifs->dataLoaderStub;
2008 if (!dataLoaderStub) {
2009 return false;
2010 }
2011 }
2012 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
2013 return true;
2014}
2015
2016void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
2017 StorageHealthCheckParams invalidCheckParams;
2018 invalidCheckParams.blockedTimeoutMs = -1;
2019 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
2020}
2021
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002022bool IncrementalService::perfLoggingEnabled() {
2023 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2024 return enabled;
2025}
2026
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002027void IncrementalService::runJobProcessing() {
2028 for (;;) {
2029 std::unique_lock lock(mJobMutex);
2030 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2031 if (!mRunning) {
2032 return;
2033 }
2034
2035 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002036 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002037 auto queue = std::move(it->second);
2038 mJobQueue.erase(it);
2039 lock.unlock();
2040
2041 for (auto&& job : queue) {
2042 job();
2043 }
2044
2045 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002046 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002047 lock.unlock();
2048 mJobCondition.notify_all();
2049 }
2050}
2051
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002052void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002053 sp<IAppOpsCallback> listener;
2054 {
2055 std::unique_lock lock{mCallbacksLock};
2056 auto& cb = mCallbackRegistered[packageName];
2057 if (cb) {
2058 return;
2059 }
2060 cb = new AppOpsListener(*this, packageName);
2061 listener = cb;
2062 }
2063
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002064 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2065 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002066}
2067
2068bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2069 sp<IAppOpsCallback> listener;
2070 {
2071 std::unique_lock lock{mCallbacksLock};
2072 auto found = mCallbackRegistered.find(packageName);
2073 if (found == mCallbackRegistered.end()) {
2074 return false;
2075 }
2076 listener = found->second;
2077 mCallbackRegistered.erase(found);
2078 }
2079
2080 mAppOpsManager->stopWatchingMode(listener);
2081 return true;
2082}
2083
2084void IncrementalService::onAppOpChanged(const std::string& packageName) {
2085 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002086 return;
2087 }
2088
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002089 std::vector<IfsMountPtr> affected;
2090 {
2091 std::lock_guard l(mLock);
2092 affected.reserve(mMounts.size());
2093 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002094 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002095 affected.push_back(ifs);
2096 }
2097 }
2098 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002099 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002100 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002101 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002102}
2103
Songchun Fana7098592020-09-03 11:45:53 -07002104bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2105 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002106 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002107 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002108 }
Songchun Fana7098592020-09-03 11:45:53 -07002109 timedQueue.addJob(id, after, std::move(what));
2110 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002111}
2112
Songchun Fana7098592020-09-03 11:45:53 -07002113bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002114 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002115 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002116 }
Songchun Fana7098592020-09-03 11:45:53 -07002117 timedQueue.removeJobs(id);
2118 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002119}
2120
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002121IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
2122 DataLoaderParamsParcel&& params,
2123 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002124 const DataLoaderStatusListener* statusListener,
2125 StorageHealthCheckParams&& healthCheckParams,
2126 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002127 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002128 : mService(service),
2129 mId(id),
2130 mParams(std::move(params)),
2131 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002132 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
2133 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002134 mHealthPath(std::move(healthPath)),
2135 mHealthCheckParams(std::move(healthCheckParams)) {
2136 if (mHealthListener) {
2137 if (!isHealthParamsValid()) {
2138 mHealthListener = {};
2139 }
2140 } else {
2141 // Disable advanced health check statuses.
2142 mHealthCheckParams.blockedTimeoutMs = -1;
2143 }
2144 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002145}
2146
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002147IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002148 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002149 cleanupResources();
2150 }
2151}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002152
2153void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002154 auto now = Clock::now();
2155 {
2156 std::unique_lock lock(mMutex);
2157 mHealthPath.clear();
2158 unregisterFromPendingReads();
2159 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002160 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002161 }
2162
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002163 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002164
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002165 {
2166 std::unique_lock lock(mMutex);
2167 mParams = {};
2168 mControl = {};
2169 mHealthControl = {};
2170 mHealthListener = {};
2171 mStatusCondition.wait_until(lock, now + 60s, [this] {
2172 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2173 });
2174 mStatusListener = {};
2175 mId = kInvalidStorageId;
2176 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002177}
2178
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002179sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2180 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002181 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002182 if (!status.isOk()) {
2183 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2184 return {};
2185 }
2186 if (!dataloader) {
2187 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2188 return {};
2189 }
2190 return dataloader;
2191}
2192
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002193bool IncrementalService::DataLoaderStub::requestCreate() {
2194 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2195}
2196
2197bool IncrementalService::DataLoaderStub::requestStart() {
2198 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2199}
2200
2201bool IncrementalService::DataLoaderStub::requestDestroy() {
2202 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2203}
2204
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002205bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002206 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002207 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002208 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002209 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002210 return fsmStep();
2211}
2212
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002213void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002214 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002215 mTargetStatus = status;
2216 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002217 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002218 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002219}
2220
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002221Milliseconds IncrementalService::DataLoaderStub::updateBindDelay() {
2222 std::unique_lock lock(mMutex);
2223 const auto previousBindTs = mPreviousBindTs;
2224 const auto now = Clock::now();
2225 mPreviousBindTs = now;
2226
2227 const auto nonCrashingInterval = std::max(castToMs(now - previousBindTs), 100ms);
2228 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2229 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2230 mPreviousBindDelay = 0ms;
2231 return mPreviousBindDelay;
2232 }
2233
2234 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2235 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2236
2237 const auto bindDelayMs =
2238 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2239 maxBindDelayMs)
2240 .count();
2241 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2242 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2243 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
2244
2245 return mPreviousBindDelay;
2246}
2247
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002248bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002249 const auto bindDelay = updateBindDelay();
2250 if (bindDelay > 1s) {
2251 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
2252 << bindDelay.count() / 1000 << "s";
2253 }
2254
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002255 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002256 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2257 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002258 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002259 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002260 return false;
2261 }
2262 return true;
2263}
2264
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002265bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002266 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002267 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002268 return false;
2269 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002270 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002271 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002272 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002273 return false;
2274 }
2275 return true;
2276}
2277
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002278bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002279 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002280 if (!dataloader) {
2281 return false;
2282 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002283 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002284 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002285 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002286 return false;
2287 }
2288 return true;
2289}
2290
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002291bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002292 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002293}
2294
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002295bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002296 if (!isValid()) {
2297 return false;
2298 }
2299
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002300 int currentStatus;
2301 int targetStatus;
2302 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002303 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002304 currentStatus = mCurrentStatus;
2305 targetStatus = mTargetStatus;
2306 }
2307
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002308 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002309
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002310 if (currentStatus == targetStatus) {
2311 return true;
2312 }
2313
2314 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002315 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2316 // Do nothing, this is a reset state.
2317 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002318 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
2319 return destroy();
2320 }
2321 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2322 switch (currentStatus) {
2323 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2324 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2325 return start();
2326 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002327 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002328 }
2329 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2330 switch (currentStatus) {
2331 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002332 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002333 return bind();
2334 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002335 return create();
2336 }
2337 break;
2338 default:
2339 LOG(ERROR) << "Invalid target status: " << targetStatus
2340 << ", current status: " << currentStatus;
2341 break;
2342 }
2343 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002344}
2345
2346binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002347 if (!isValid()) {
2348 return binder::Status::
2349 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2350 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002351 if (id() != mountId) {
2352 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002353 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2354 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002355 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2356 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2357 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2358 [this, newStatus]() { setCurrentStatus(newStatus); });
2359 return binder::Status::ok();
2360 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002361
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002362 setCurrentStatus(newStatus);
2363 return binder::Status::ok();
2364}
2365
2366void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002367 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002368 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002369 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002370 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002371 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002372 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002373 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002374
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002375 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002376 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002377 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002378
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002379 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002380
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002381 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2382 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002383 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2384 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002385 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002386 }
2387
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002388 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002389 << newStatus << " (target " << targetStatus << ")";
2390
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002391 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002392 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002393 }
2394
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002395 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002396
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002397 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002398}
2399
Songchun Fan33093982020-09-10 13:12:39 -07002400binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2401 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002402 if (!isValid()) {
2403 return binder::Status::
2404 fromServiceSpecificError(-EINVAL,
2405 "reportStreamHealth came to invalid DataLoaderStub");
2406 }
2407 if (id() != mountId) {
2408 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
2409 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2410 }
2411 {
2412 std::lock_guard lock(mMutex);
2413 mStreamStatus = newStatus;
2414 }
Songchun Fan33093982020-09-10 13:12:39 -07002415 return binder::Status::ok();
2416}
2417
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002418bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2419 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2420 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002421}
2422
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002423void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2424 int healthStatus) {
2425 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2426 if (healthListener) {
2427 healthListener->onHealthStatus(id(), healthStatus);
2428 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002429}
2430
Songchun Fan2570ec02020-10-08 17:22:33 -07002431static int adjustHealthStatus(int healthStatus, int streamStatus) {
2432 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2433 // everything is good; no need to change status
2434 return healthStatus;
2435 }
2436 int newHeathStatus = healthStatus;
2437 switch (streamStatus) {
2438 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2439 // storage is limited and storage not healthy
2440 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2441 break;
2442 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2443 // fall through
2444 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2445 // fall through
2446 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2447 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2448 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2449 }
2450 // pending/blocked status due to transportation issues is not regarded as unhealthy
2451 break;
2452 default:
2453 break;
2454 }
2455 return newHeathStatus;
2456}
2457
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002458void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2459 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002460
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002461 int healthStatusToReport = -1;
2462 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002463
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002464 {
2465 std::unique_lock lock(mMutex);
2466 unregisterFromPendingReads();
2467
2468 healthListener = mHealthListener;
2469
2470 // Healthcheck depends on timestamp of the oldest pending read.
2471 // 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 -07002472 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2473 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002474 const auto now = Clock::now();
2475 const auto kernelTsUs = getOldestPendingReadTs();
2476 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002477 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2478 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002479 mHealthBase = {now, kernelTsUs};
2480 }
2481
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002482 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2483 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002484 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2485 registerForPendingReads();
2486 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2487 lock.unlock();
2488 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002489 return;
2490 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002491
2492 resetHealthControl();
2493
2494 // Always make sure the data loader is started.
2495 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2496
2497 // Skip any further processing if health check params are invalid.
2498 if (!isHealthParamsValid()) {
2499 LOG(DEBUG) << id()
2500 << ": Skip any further processing if health check params are invalid.";
2501 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2502 lock.unlock();
2503 onHealthStatus(healthListener, healthStatusToReport);
2504 // Triggering data loader start. This is a one-time action.
2505 fsmStep();
2506 return;
2507 }
2508
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002509 // Don't schedule timer job less than 500ms in advance.
2510 static constexpr auto kTolerance = 500ms;
2511
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002512 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2513 const auto unhealthyTimeout =
2514 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2515 const auto unhealthyMonitoring =
2516 std::max(1000ms,
2517 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2518
2519 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2520 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002521 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002522
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002523 Milliseconds checkBackAfter;
2524 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002525 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002526 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002527 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002528 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002529 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002530 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002531 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2532 } else {
2533 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002534 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002535 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2536 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002537 // Adjust health status based on stream status
2538 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002539 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002540 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002541 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2542 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002543 }
2544
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002545 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002546 if (healthStatusToReport != -1) {
2547 onHealthStatus(healthListener, healthStatusToReport);
2548 }
2549
2550 fsmStep();
2551}
2552
2553const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2554 if (mHealthPath.empty()) {
2555 resetHealthControl();
2556 return mHealthControl;
2557 }
2558 if (mHealthControl.pendingReads() < 0) {
2559 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2560 }
2561 if (mHealthControl.pendingReads() < 0) {
2562 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2563 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2564 << mHealthControl.logs() << ")";
2565 }
2566 return mHealthControl;
2567}
2568
2569void IncrementalService::DataLoaderStub::resetHealthControl() {
2570 mHealthControl = {};
2571}
2572
2573BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2574 auto result = kMaxBootClockTsUs;
2575
2576 const auto& control = initializeHealthControl();
2577 if (control.pendingReads() < 0) {
2578 return result;
2579 }
2580
Songchun Fan6944f1e2020-11-06 15:24:24 -08002581 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002582 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002583 mLastPendingReads.empty()) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002584 return result;
2585 }
2586
2587 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002588 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002589
Songchun Fan6944f1e2020-11-06 15:24:24 -08002590 for (auto&& pendingRead : mLastPendingReads) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002591 result = std::min(result, pendingRead.bootClockTsUs);
2592 }
2593 return result;
2594}
2595
2596void IncrementalService::DataLoaderStub::registerForPendingReads() {
2597 const auto pendingReadsFd = mHealthControl.pendingReads();
2598 if (pendingReadsFd < 0) {
2599 return;
2600 }
2601
2602 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2603
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002604 mService.mLooper->addFd(
2605 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2606 [](int, int, void* data) -> int {
2607 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002608 self->updateHealthStatus(/*baseline=*/true);
2609 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002610 },
2611 this);
2612 mService.mLooper->wake();
2613}
2614
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002615void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002616 const auto pendingReadsFd = mHealthControl.pendingReads();
2617 if (pendingReadsFd < 0) {
2618 return;
2619 }
2620
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002621 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2622
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002623 mService.mLooper->removeFd(pendingReadsFd);
2624 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002625}
2626
Songchun Fan2570ec02020-10-08 17:22:33 -07002627void IncrementalService::DataLoaderStub::setHealthListener(
2628 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2629 std::lock_guard lock(mMutex);
2630 mHealthCheckParams = std::move(healthCheckParams);
2631 if (healthListener == nullptr) {
2632 // reset listener and params
2633 mHealthListener = {};
2634 } else {
2635 mHealthListener = *healthListener;
2636 }
2637}
2638
Songchun Fan6944f1e2020-11-06 15:24:24 -08002639static std::string toHexString(const RawMetadata& metadata) {
2640 int n = metadata.size();
2641 std::string res(n * 2, '\0');
2642 // Same as incfs::toString(fileId)
2643 static constexpr char kHexChar[] = "0123456789abcdef";
2644 for (int i = 0; i < n; ++i) {
2645 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2646 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2647 }
2648 return res;
2649}
2650
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002651void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002652 dprintf(fd, " dataLoader: {\n");
2653 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2654 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2655 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002656 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002657 dprintf(fd, " health: {\n");
2658 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2659 dprintf(fd, " base: %lldmcs (%lld)\n",
2660 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2661 (long long)mHealthBase.kernelTsUs);
2662 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2663 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2664 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2665 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002666 dprintf(fd, " lastPendingReads: \n");
2667 const auto control = mService.mIncFs->openMount(mHealthPath);
2668 for (auto&& pendingRead : mLastPendingReads) {
2669 dprintf(fd, " fileId: %s\n", mService.mIncFs->toString(pendingRead.id).c_str());
2670 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2671 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2672 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2673 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2674 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002675 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
2676 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
2677 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002678 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002679 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002680 dprintf(fd, " dataLoaderParams: {\n");
2681 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2682 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2683 dprintf(fd, " className: %s\n", params.className.c_str());
2684 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2685 dprintf(fd, " }\n");
2686 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002687}
2688
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002689void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2690 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002691}
2692
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002693binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2694 bool enableReadLogs, int32_t* _aidl_return) {
2695 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2696 return binder::Status::ok();
2697}
2698
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002699FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2700 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2701}
2702
Songchun Fan3c82a302019-11-29 14:23:45 -08002703} // namespace android::incremental