blob: 2fa927bcccfd4d53fc39aaf6be0f539d53a6c866 [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;
Songchun Fan2ff2a482020-09-29 11:45:18 -07001620 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 Zubrytskyida208012020-04-07 15:35:21 -07001630 std::vector<Job> jobQueue;
1631 ZipEntry entry;
1632 std::string_view fileName;
1633 while (!Next(cookie, &entry, &fileName)) {
1634 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001635 continue;
1636 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001637
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001638 if (!extractNativeLibs) {
1639 // ensure the file is properly aligned and unpacked
1640 if (entry.method != kCompressStored) {
1641 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1642 return false;
1643 }
1644 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1645 LOG(WARNING) << "Library " << fileName
1646 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1647 << entry.offset;
1648 return false;
1649 }
1650 continue;
1651 }
1652
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001653 auto startFileTs = Clock::now();
1654
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001655 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001656 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001657 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001658 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001659 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001660 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001661 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1662 << "; skipping extraction, spent "
1663 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1664 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001665 continue;
1666 }
1667
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001668 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001669 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001670 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001671 .signature = {},
1672 // Metadata of the new lib file is its relative path
1673 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1674 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001675 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001676 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1677 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001678 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001679 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001680 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001681 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001682
1683 auto makeFileTs = Clock::now();
1684
Songchun Fanafaf6e92020-03-18 14:12:20 -07001685 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001686 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001687 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001688 LOG(INFO) << "incfs: Extracted " << libName
1689 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001690 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001691 continue;
1692 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001693
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001694 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1695 libFileId, libPath = std::move(targetLibPath),
1696 makeFileTs]() mutable {
1697 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001698 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001699
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001700 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001701 auto prepareJobTs = Clock::now();
1702 LOG(INFO) << "incfs: Processed " << libName << ": "
1703 << elapsedMcs(startFileTs, prepareJobTs)
1704 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1705 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001706 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001707 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001708
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001709 auto processedTs = Clock::now();
1710
1711 if (!jobQueue.empty()) {
1712 {
1713 std::lock_guard lock(mJobMutex);
1714 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001715 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001716 if (existingJobs.empty()) {
1717 existingJobs = std::move(jobQueue);
1718 } else {
1719 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1720 std::move_iterator(jobQueue.end()));
1721 }
1722 }
1723 }
1724 mJobCondition.notify_all();
1725 }
1726
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001727 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001728 auto end = Clock::now();
1729 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1730 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1731 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001732 << " make files: " << elapsedMcs(openZipTs, processedTs)
1733 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001734 }
1735
1736 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001737}
1738
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001739void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1740 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001741 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001742 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001743 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001744 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001745 return;
1746 }
1747
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001748 auto startedTs = Clock::now();
1749
1750 // Write extracted data to new file
1751 // NOTE: don't zero-initialize memory, it may take a while for nothing
1752 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1753 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001754 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001755 return;
1756 }
1757
1758 auto extractFileTs = Clock::now();
1759
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001760 if (setFileContent(ifs, libFileId, debugLibPath,
1761 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001762 return;
1763 }
1764
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001765 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001766 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001767 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1768 << entry.compressed_length << " -> " << entry.uncompressed_length
1769 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001770 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1771 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001772 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001773 }
1774}
1775
1776bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001777 struct WaitPrinter {
1778 const Clock::time_point startTs = Clock::now();
1779 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001780 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001781 const auto endTs = Clock::now();
1782 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1783 << elapsedMcs(startTs, endTs) << "mcs";
1784 }
1785 }
1786 } waitPrinter;
1787
1788 MountId mount;
1789 {
1790 auto ifs = getIfs(storage);
1791 if (!ifs) {
1792 return true;
1793 }
1794 mount = ifs->mountId;
1795 }
1796
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001797 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001798 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001799 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001800 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001801 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001802 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001803}
1804
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001805int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1806 std::string_view debugFilePath,
1807 std::span<const uint8_t> data) const {
1808 auto startTs = Clock::now();
1809
1810 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1811 if (!writeFd.ok()) {
1812 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1813 << " errno: " << writeFd.get();
1814 return writeFd.get();
1815 }
1816
1817 const auto dataLength = data.size();
1818
1819 auto openFileTs = Clock::now();
1820 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1821 std::vector<IncFsDataBlock> instructions(numBlocks);
1822 for (int i = 0; i < numBlocks; i++) {
1823 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1824 instructions[i] = IncFsDataBlock{
1825 .fileFd = writeFd.get(),
1826 .pageIndex = static_cast<IncFsBlockIndex>(i),
1827 .compression = INCFS_COMPRESSION_KIND_NONE,
1828 .kind = INCFS_BLOCK_KIND_DATA,
1829 .dataSize = static_cast<uint32_t>(blockSize),
1830 .data = reinterpret_cast<const char*>(data.data()),
1831 };
1832 data = data.subspan(blockSize);
1833 }
1834 auto prepareInstsTs = Clock::now();
1835
1836 size_t res = mIncFs->writeBlocks(instructions);
1837 if (res != instructions.size()) {
1838 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1839 return res;
1840 }
1841
1842 if (perfLoggingEnabled()) {
1843 auto endTs = Clock::now();
1844 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1845 << " bytes): " << elapsedMcs(startTs, endTs)
1846 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1847 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1848 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1849 }
1850
1851 return 0;
1852}
1853
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001854int IncrementalService::isFileFullyLoaded(StorageId storage, std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001855 std::unique_lock l(mLock);
1856 const auto ifs = getIfsLocked(storage);
1857 if (!ifs) {
1858 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1859 return -EINVAL;
1860 }
1861 const auto storageInfo = ifs->storages.find(storage);
1862 if (storageInfo == ifs->storages.end()) {
1863 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1864 return -EINVAL;
1865 }
1866 l.unlock();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001867 return isFileFullyLoadedFromPath(*ifs, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001868}
1869
1870int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1871 std::string_view filePath) const {
1872 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1873 if (filledBlocks < 0) {
1874 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1875 << filePath << " errno: " << filledBlocks;
1876 return filledBlocks;
1877 }
1878 if (totalBlocks < filledBlocks) {
1879 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1880 return -EINVAL;
1881 }
1882 return totalBlocks - filledBlocks;
1883}
1884
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001885IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001886 StorageId storage, bool stopOnFirstIncomplete) const {
Songchun Fan374f7652020-08-20 08:40:29 -07001887 std::unique_lock l(mLock);
1888 const auto ifs = getIfsLocked(storage);
1889 if (!ifs) {
1890 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001891 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001892 }
1893 const auto storageInfo = ifs->storages.find(storage);
1894 if (storageInfo == ifs->storages.end()) {
1895 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001896 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001897 }
1898 l.unlock();
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001899 return getLoadingProgressFromPath(*ifs, storageInfo->second.name, stopOnFirstIncomplete);
Songchun Fan374f7652020-08-20 08:40:29 -07001900}
1901
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001902IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001903 const IncFsMount& ifs, std::string_view storagePath, bool stopOnFirstIncomplete) const {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001904 ssize_t totalBlocks = 0, filledBlocks = 0;
Songchun Fan374f7652020-08-20 08:40:29 -07001905 const auto filePaths = mFs->listFilesRecursive(storagePath);
1906 for (const auto& filePath : filePaths) {
1907 const auto [filledBlocksCount, totalBlocksCount] =
1908 mIncFs->countFilledBlocks(ifs.control, filePath);
1909 if (filledBlocksCount < 0) {
1910 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1911 << " errno: " << filledBlocksCount;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001912 return {filledBlocksCount, filledBlocksCount};
Songchun Fan374f7652020-08-20 08:40:29 -07001913 }
1914 totalBlocks += totalBlocksCount;
1915 filledBlocks += filledBlocksCount;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001916 if (stopOnFirstIncomplete && filledBlocks < totalBlocks) {
1917 break;
1918 }
Songchun Fan374f7652020-08-20 08:40:29 -07001919 }
1920
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001921 return {filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07001922}
1923
Songchun Fana7098592020-09-03 11:45:53 -07001924bool IncrementalService::updateLoadingProgress(
1925 StorageId storage, const StorageLoadingProgressListener& progressListener) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001926 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/false);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001927 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07001928 // Failed to get progress from incfs, abort.
1929 return false;
1930 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001931 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
1932 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07001933 // Stop updating progress once it is fully loaded
1934 return true;
1935 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001936 addTimedJob(*mProgressUpdateJobQueue, storage,
1937 Constants::progressUpdateInterval /* repeat after 1s */,
Songchun Fana7098592020-09-03 11:45:53 -07001938 [storage, progressListener, this]() {
1939 updateLoadingProgress(storage, progressListener);
1940 });
1941 return true;
1942}
1943
1944bool IncrementalService::registerLoadingProgressListener(
1945 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1946 return updateLoadingProgress(storage, progressListener);
1947}
1948
1949bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
1950 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
1951}
1952
Songchun Fan2570ec02020-10-08 17:22:33 -07001953bool IncrementalService::registerStorageHealthListener(
1954 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
1955 const StorageHealthListener& healthListener) {
1956 DataLoaderStubPtr dataLoaderStub;
1957 {
1958 std::unique_lock l(mLock);
1959 const auto& ifs = getIfsLocked(storage);
1960 if (!ifs) {
1961 return false;
1962 }
1963 dataLoaderStub = ifs->dataLoaderStub;
1964 if (!dataLoaderStub) {
1965 return false;
1966 }
1967 }
1968 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
1969 return true;
1970}
1971
1972void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
1973 StorageHealthCheckParams invalidCheckParams;
1974 invalidCheckParams.blockedTimeoutMs = -1;
1975 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
1976}
1977
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001978bool IncrementalService::perfLoggingEnabled() {
1979 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1980 return enabled;
1981}
1982
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001983void IncrementalService::runJobProcessing() {
1984 for (;;) {
1985 std::unique_lock lock(mJobMutex);
1986 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1987 if (!mRunning) {
1988 return;
1989 }
1990
1991 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001992 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001993 auto queue = std::move(it->second);
1994 mJobQueue.erase(it);
1995 lock.unlock();
1996
1997 for (auto&& job : queue) {
1998 job();
1999 }
2000
2001 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002002 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002003 lock.unlock();
2004 mJobCondition.notify_all();
2005 }
2006}
2007
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002008void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002009 sp<IAppOpsCallback> listener;
2010 {
2011 std::unique_lock lock{mCallbacksLock};
2012 auto& cb = mCallbackRegistered[packageName];
2013 if (cb) {
2014 return;
2015 }
2016 cb = new AppOpsListener(*this, packageName);
2017 listener = cb;
2018 }
2019
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002020 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2021 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002022}
2023
2024bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2025 sp<IAppOpsCallback> listener;
2026 {
2027 std::unique_lock lock{mCallbacksLock};
2028 auto found = mCallbackRegistered.find(packageName);
2029 if (found == mCallbackRegistered.end()) {
2030 return false;
2031 }
2032 listener = found->second;
2033 mCallbackRegistered.erase(found);
2034 }
2035
2036 mAppOpsManager->stopWatchingMode(listener);
2037 return true;
2038}
2039
2040void IncrementalService::onAppOpChanged(const std::string& packageName) {
2041 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002042 return;
2043 }
2044
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002045 std::vector<IfsMountPtr> affected;
2046 {
2047 std::lock_guard l(mLock);
2048 affected.reserve(mMounts.size());
2049 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002050 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002051 affected.push_back(ifs);
2052 }
2053 }
2054 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002055 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002056 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002057 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002058}
2059
Songchun Fana7098592020-09-03 11:45:53 -07002060bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2061 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002062 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002063 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002064 }
Songchun Fana7098592020-09-03 11:45:53 -07002065 timedQueue.addJob(id, after, std::move(what));
2066 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002067}
2068
Songchun Fana7098592020-09-03 11:45:53 -07002069bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002070 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002071 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002072 }
Songchun Fana7098592020-09-03 11:45:53 -07002073 timedQueue.removeJobs(id);
2074 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002075}
2076
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002077IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
2078 DataLoaderParamsParcel&& params,
2079 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002080 const DataLoaderStatusListener* statusListener,
2081 StorageHealthCheckParams&& healthCheckParams,
2082 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002083 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002084 : mService(service),
2085 mId(id),
2086 mParams(std::move(params)),
2087 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002088 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
2089 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002090 mHealthPath(std::move(healthPath)),
2091 mHealthCheckParams(std::move(healthCheckParams)) {
2092 if (mHealthListener) {
2093 if (!isHealthParamsValid()) {
2094 mHealthListener = {};
2095 }
2096 } else {
2097 // Disable advanced health check statuses.
2098 mHealthCheckParams.blockedTimeoutMs = -1;
2099 }
2100 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002101}
2102
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002103IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002104 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002105 cleanupResources();
2106 }
2107}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002108
2109void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002110 auto now = Clock::now();
2111 {
2112 std::unique_lock lock(mMutex);
2113 mHealthPath.clear();
2114 unregisterFromPendingReads();
2115 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002116 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002117 }
2118
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002119 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002120
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002121 {
2122 std::unique_lock lock(mMutex);
2123 mParams = {};
2124 mControl = {};
2125 mHealthControl = {};
2126 mHealthListener = {};
2127 mStatusCondition.wait_until(lock, now + 60s, [this] {
2128 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2129 });
2130 mStatusListener = {};
2131 mId = kInvalidStorageId;
2132 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002133}
2134
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002135sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2136 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002137 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002138 if (!status.isOk()) {
2139 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2140 return {};
2141 }
2142 if (!dataloader) {
2143 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2144 return {};
2145 }
2146 return dataloader;
2147}
2148
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002149bool IncrementalService::DataLoaderStub::requestCreate() {
2150 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2151}
2152
2153bool IncrementalService::DataLoaderStub::requestStart() {
2154 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2155}
2156
2157bool IncrementalService::DataLoaderStub::requestDestroy() {
2158 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2159}
2160
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002161bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002162 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002163 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002164 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002165 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002166 return fsmStep();
2167}
2168
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002169void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002170 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002171 mTargetStatus = status;
2172 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002173 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002174 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002175}
2176
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002177Milliseconds IncrementalService::DataLoaderStub::updateBindDelay() {
2178 std::unique_lock lock(mMutex);
2179 const auto previousBindTs = mPreviousBindTs;
2180 const auto now = Clock::now();
2181 mPreviousBindTs = now;
2182
2183 const auto nonCrashingInterval = std::max(castToMs(now - previousBindTs), 100ms);
2184 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2185 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2186 mPreviousBindDelay = 0ms;
2187 return mPreviousBindDelay;
2188 }
2189
2190 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2191 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2192
2193 const auto bindDelayMs =
2194 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2195 maxBindDelayMs)
2196 .count();
2197 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2198 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2199 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
2200
2201 return mPreviousBindDelay;
2202}
2203
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002204bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002205 const auto bindDelay = updateBindDelay();
2206 if (bindDelay > 1s) {
2207 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
2208 << bindDelay.count() / 1000 << "s";
2209 }
2210
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002211 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002212 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2213 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002214 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002215 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002216 return false;
2217 }
2218 return true;
2219}
2220
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002221bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002222 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002223 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002224 return false;
2225 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002226 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002227 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002228 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002229 return false;
2230 }
2231 return true;
2232}
2233
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002234bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002235 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002236 if (!dataloader) {
2237 return false;
2238 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002239 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002240 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002241 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002242 return false;
2243 }
2244 return true;
2245}
2246
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002247bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002248 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002249}
2250
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002251bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002252 if (!isValid()) {
2253 return false;
2254 }
2255
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002256 int currentStatus;
2257 int targetStatus;
2258 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002259 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002260 currentStatus = mCurrentStatus;
2261 targetStatus = mTargetStatus;
2262 }
2263
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002264 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002265
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002266 if (currentStatus == targetStatus) {
2267 return true;
2268 }
2269
2270 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002271 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2272 // Do nothing, this is a reset state.
2273 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002274 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
2275 return destroy();
2276 }
2277 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2278 switch (currentStatus) {
2279 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2280 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2281 return start();
2282 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002283 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002284 }
2285 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2286 switch (currentStatus) {
2287 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002288 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002289 return bind();
2290 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002291 return create();
2292 }
2293 break;
2294 default:
2295 LOG(ERROR) << "Invalid target status: " << targetStatus
2296 << ", current status: " << currentStatus;
2297 break;
2298 }
2299 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002300}
2301
2302binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002303 if (!isValid()) {
2304 return binder::Status::
2305 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2306 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002307 if (id() != mountId) {
2308 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002309 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2310 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002311 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2312 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2313 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2314 [this, newStatus]() { setCurrentStatus(newStatus); });
2315 return binder::Status::ok();
2316 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002317
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002318 setCurrentStatus(newStatus);
2319 return binder::Status::ok();
2320}
2321
2322void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002323 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002324 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002325 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002326 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002327 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002328 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002329 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002330
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002331 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002332 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002333 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002334
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002335 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002336
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002337 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2338 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002339 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2340 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002341 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002342 }
2343
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002344 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002345 << newStatus << " (target " << targetStatus << ")";
2346
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002347 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002348 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002349 }
2350
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002351 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002352
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002353 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002354}
2355
Songchun Fan33093982020-09-10 13:12:39 -07002356binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2357 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002358 if (!isValid()) {
2359 return binder::Status::
2360 fromServiceSpecificError(-EINVAL,
2361 "reportStreamHealth came to invalid DataLoaderStub");
2362 }
2363 if (id() != mountId) {
2364 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
2365 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2366 }
2367 {
2368 std::lock_guard lock(mMutex);
2369 mStreamStatus = newStatus;
2370 }
Songchun Fan33093982020-09-10 13:12:39 -07002371 return binder::Status::ok();
2372}
2373
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002374bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2375 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2376 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002377}
2378
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002379void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2380 int healthStatus) {
2381 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2382 if (healthListener) {
2383 healthListener->onHealthStatus(id(), healthStatus);
2384 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002385}
2386
Songchun Fan2570ec02020-10-08 17:22:33 -07002387static int adjustHealthStatus(int healthStatus, int streamStatus) {
2388 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2389 // everything is good; no need to change status
2390 return healthStatus;
2391 }
2392 int newHeathStatus = healthStatus;
2393 switch (streamStatus) {
2394 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2395 // storage is limited and storage not healthy
2396 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2397 break;
2398 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2399 // fall through
2400 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2401 // fall through
2402 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2403 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2404 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2405 }
2406 // pending/blocked status due to transportation issues is not regarded as unhealthy
2407 break;
2408 default:
2409 break;
2410 }
2411 return newHeathStatus;
2412}
2413
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002414void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2415 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002416
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002417 int healthStatusToReport = -1;
2418 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002419
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002420 {
2421 std::unique_lock lock(mMutex);
2422 unregisterFromPendingReads();
2423
2424 healthListener = mHealthListener;
2425
2426 // Healthcheck depends on timestamp of the oldest pending read.
2427 // 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 -07002428 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2429 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002430 const auto now = Clock::now();
2431 const auto kernelTsUs = getOldestPendingReadTs();
2432 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002433 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2434 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002435 mHealthBase = {now, kernelTsUs};
2436 }
2437
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002438 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2439 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002440 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2441 registerForPendingReads();
2442 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2443 lock.unlock();
2444 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002445 return;
2446 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002447
2448 resetHealthControl();
2449
2450 // Always make sure the data loader is started.
2451 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2452
2453 // Skip any further processing if health check params are invalid.
2454 if (!isHealthParamsValid()) {
2455 LOG(DEBUG) << id()
2456 << ": Skip any further processing if health check params are invalid.";
2457 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2458 lock.unlock();
2459 onHealthStatus(healthListener, healthStatusToReport);
2460 // Triggering data loader start. This is a one-time action.
2461 fsmStep();
2462 return;
2463 }
2464
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002465 // Don't schedule timer job less than 500ms in advance.
2466 static constexpr auto kTolerance = 500ms;
2467
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002468 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2469 const auto unhealthyTimeout =
2470 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2471 const auto unhealthyMonitoring =
2472 std::max(1000ms,
2473 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2474
2475 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2476 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002477 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002478
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002479 Milliseconds checkBackAfter;
2480 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002481 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002482 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002483 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002484 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002485 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002486 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002487 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2488 } else {
2489 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002490 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002491 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2492 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002493 // Adjust health status based on stream status
2494 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002495 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002496 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002497 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2498 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002499 }
2500
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002501 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002502 if (healthStatusToReport != -1) {
2503 onHealthStatus(healthListener, healthStatusToReport);
2504 }
2505
2506 fsmStep();
2507}
2508
2509const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2510 if (mHealthPath.empty()) {
2511 resetHealthControl();
2512 return mHealthControl;
2513 }
2514 if (mHealthControl.pendingReads() < 0) {
2515 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2516 }
2517 if (mHealthControl.pendingReads() < 0) {
2518 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2519 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2520 << mHealthControl.logs() << ")";
2521 }
2522 return mHealthControl;
2523}
2524
2525void IncrementalService::DataLoaderStub::resetHealthControl() {
2526 mHealthControl = {};
2527}
2528
2529BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2530 auto result = kMaxBootClockTsUs;
2531
2532 const auto& control = initializeHealthControl();
2533 if (control.pendingReads() < 0) {
2534 return result;
2535 }
2536
Songchun Fan6944f1e2020-11-06 15:24:24 -08002537 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002538 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002539 mLastPendingReads.empty()) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002540 return result;
2541 }
2542
2543 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002544 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002545
Songchun Fan6944f1e2020-11-06 15:24:24 -08002546 for (auto&& pendingRead : mLastPendingReads) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002547 result = std::min(result, pendingRead.bootClockTsUs);
2548 }
2549 return result;
2550}
2551
2552void IncrementalService::DataLoaderStub::registerForPendingReads() {
2553 const auto pendingReadsFd = mHealthControl.pendingReads();
2554 if (pendingReadsFd < 0) {
2555 return;
2556 }
2557
2558 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2559
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002560 mService.mLooper->addFd(
2561 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2562 [](int, int, void* data) -> int {
2563 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002564 self->updateHealthStatus(/*baseline=*/true);
2565 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002566 },
2567 this);
2568 mService.mLooper->wake();
2569}
2570
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002571void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002572 const auto pendingReadsFd = mHealthControl.pendingReads();
2573 if (pendingReadsFd < 0) {
2574 return;
2575 }
2576
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002577 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2578
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002579 mService.mLooper->removeFd(pendingReadsFd);
2580 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002581}
2582
Songchun Fan2570ec02020-10-08 17:22:33 -07002583void IncrementalService::DataLoaderStub::setHealthListener(
2584 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2585 std::lock_guard lock(mMutex);
2586 mHealthCheckParams = std::move(healthCheckParams);
2587 if (healthListener == nullptr) {
2588 // reset listener and params
2589 mHealthListener = {};
2590 } else {
2591 mHealthListener = *healthListener;
2592 }
2593}
2594
Songchun Fan6944f1e2020-11-06 15:24:24 -08002595static std::string toHexString(const RawMetadata& metadata) {
2596 int n = metadata.size();
2597 std::string res(n * 2, '\0');
2598 // Same as incfs::toString(fileId)
2599 static constexpr char kHexChar[] = "0123456789abcdef";
2600 for (int i = 0; i < n; ++i) {
2601 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2602 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2603 }
2604 return res;
2605}
2606
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002607void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002608 dprintf(fd, " dataLoader: {\n");
2609 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2610 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2611 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002612 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002613 dprintf(fd, " health: {\n");
2614 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2615 dprintf(fd, " base: %lldmcs (%lld)\n",
2616 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2617 (long long)mHealthBase.kernelTsUs);
2618 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2619 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2620 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2621 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002622 dprintf(fd, " lastPendingReads: \n");
2623 const auto control = mService.mIncFs->openMount(mHealthPath);
2624 for (auto&& pendingRead : mLastPendingReads) {
2625 dprintf(fd, " fileId: %s\n", mService.mIncFs->toString(pendingRead.id).c_str());
2626 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2627 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2628 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2629 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2630 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002631 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
2632 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
2633 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002634 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002635 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002636 dprintf(fd, " dataLoaderParams: {\n");
2637 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2638 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2639 dprintf(fd, " className: %s\n", params.className.c_str());
2640 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2641 dprintf(fd, " }\n");
2642 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002643}
2644
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002645void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2646 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002647}
2648
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002649binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2650 bool enableReadLogs, int32_t* _aidl_return) {
2651 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2652 return binder::Status::ok();
2653}
2654
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002655FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2656 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2657}
2658
Songchun Fan3c82a302019-11-29 14:23:45 -08002659} // namespace android::incremental