blob: 56cb3d11d552ab805539a565908e1415ea2743f7 [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
69 static constexpr auto progressUpdateInterval = 1000ms;
70 static constexpr auto perUidTimeoutOffset = progressUpdateInterval * 2;
71 static constexpr auto minPerUidTimeout = progressUpdateInterval * 3;
Songchun Fan3c82a302019-11-29 14:23:45 -080072};
73
74static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070075 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080076 return c;
77}
78
79template <base::LogSeverity level = base::ERROR>
80bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
81 auto cstr = path::c_str(name);
82 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080083 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080084 PLOG(level) << "Can't create directory '" << name << '\'';
85 return false;
86 }
87 struct stat st;
88 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
89 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
90 return false;
91 }
92 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080093 if (::chmod(cstr, mode)) {
94 PLOG(level) << "Changing permission failed for '" << name << '\'';
95 return false;
96 }
97
Songchun Fan3c82a302019-11-29 14:23:45 -080098 return true;
99}
100
101static std::string toMountKey(std::string_view path) {
102 if (path.empty()) {
103 return "@none";
104 }
105 if (path == "/"sv) {
106 return "@root";
107 }
108 if (path::isAbsolute(path)) {
109 path.remove_prefix(1);
110 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700111 if (path.size() > 16) {
112 path = path.substr(0, 16);
113 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800114 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700115 std::replace_if(
116 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
117 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800118}
119
120static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
121 std::string_view path) {
122 auto mountKey = toMountKey(path);
123 const auto prefixSize = mountKey.size();
124 for (int counter = 0; counter < 1000;
125 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
126 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800127 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800128 return {mountKey, mountRoot};
129 }
130 }
131 return {};
132}
133
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700134template <class Map>
135typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
136 const auto nextIt = map.upper_bound(path);
137 if (nextIt == map.begin()) {
138 return map.end();
139 }
140 const auto suspectIt = std::prev(nextIt);
141 if (!path::startsWith(path, suspectIt->first)) {
142 return map.end();
143 }
144 return suspectIt;
145}
146
147static base::unique_fd dup(base::borrowed_fd fd) {
148 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
149 return base::unique_fd(res);
150}
151
Songchun Fan3c82a302019-11-29 14:23:45 -0800152template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700153static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800154 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800155 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800156 ProtoMessage message;
157 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
158}
159
160static bool isValidMountTarget(std::string_view path) {
161 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
162}
163
164std::string makeBindMdName() {
165 static constexpr auto uuidStringSize = 36;
166
167 uuid_t guid;
168 uuid_generate(guid);
169
170 std::string name;
171 const auto prefixSize = constants().mountpointMdPrefix.size();
172 name.reserve(prefixSize + uuidStringSize);
173
174 name = constants().mountpointMdPrefix;
175 name.resize(prefixSize + uuidStringSize);
176 uuid_unparse(guid, name.data() + prefixSize);
177
178 return name;
179}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700180
181static bool checkReadLogsDisabledMarker(std::string_view root) {
182 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
183 struct stat st;
184 return (::stat(markerPath, &st) == 0);
185}
186
Songchun Fan3c82a302019-11-29 14:23:45 -0800187} // namespace
188
189IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700190 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700191 dataLoaderStub->cleanupResources();
192 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700193 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700194 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800195 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
196 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700197 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800198 incrementalService.mVold->unmountIncFs(target);
199 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700200 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800201 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
202 cleanupFilesystem(root);
203}
204
205auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800206 std::string name;
207 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
208 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
209 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800210 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
211 constants().storagePrefix.data(), id, no);
212 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800213 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800214 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800215 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
216 } else if (err != EEXIST) {
217 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
218 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800219 }
220 }
221 nextStorageDirNo = 0;
222 return storages.end();
223}
224
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700225template <class Func>
226static auto makeCleanup(Func&& f) {
227 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700228 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700229 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
230}
231
232static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
233 return {::opendir(dir), ::closedir};
234}
235
236static auto openDir(std::string_view dir) {
237 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800238}
239
240static int rmDirContent(const char* path) {
241 auto dir = openDir(path);
242 if (!dir) {
243 return -EINVAL;
244 }
245 while (auto entry = ::readdir(dir.get())) {
246 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
247 continue;
248 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700249 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800250 if (entry->d_type == DT_DIR) {
251 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
252 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
253 return err;
254 }
255 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
256 PLOG(WARNING) << "Failed to rmdir " << fullPath;
257 return err;
258 }
259 } else {
260 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
261 PLOG(WARNING) << "Failed to delete " << fullPath;
262 return err;
263 }
264 }
265 }
266 return 0;
267}
268
Songchun Fan3c82a302019-11-29 14:23:45 -0800269void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800270 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800271 ::rmdir(path::join(root, constants().backing).c_str());
272 ::rmdir(path::join(root, constants().mount).c_str());
273 ::rmdir(path::c_str(root));
274}
275
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800276IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800277 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800278 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800279 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700280 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700281 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700282 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700283 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700284 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700285 mFs(sm.getFs()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800286 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700287 CHECK(mVold) << "Vold service is unavailable";
288 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
289 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
290 CHECK(mJni) << "JNI is unavailable";
291 CHECK(mLooper) << "Looper is unavailable";
292 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700293 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700294 CHECK(mFs) << "Fs is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700295
296 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700297 mJobProcessor = std::thread([this]() {
298 mJni->initializeForCurrentThread();
299 runJobProcessing();
300 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700301 mCmdLooperThread = std::thread([this]() {
302 mJni->initializeForCurrentThread();
303 runCmdLooper();
304 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700305
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700306 const auto mountedRootNames = adoptMountedInstances();
307 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800308}
309
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700310IncrementalService::~IncrementalService() {
311 {
312 std::lock_guard lock(mJobMutex);
313 mRunning = false;
314 }
315 mJobCondition.notify_all();
316 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700317 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700318 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700319 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700320 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700321 // Ensure that mounts are destroyed while the service is still valid.
322 mBindsByPath.clear();
323 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700324}
Songchun Fan3c82a302019-11-29 14:23:45 -0800325
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700326static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800327 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800328 case IncrementalService::BindKind::Temporary:
329 return "Temporary";
330 case IncrementalService::BindKind::Permanent:
331 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800332 }
333}
334
335void IncrementalService::onDump(int fd) {
336 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
337 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
338
339 std::unique_lock l(mLock);
340
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700341 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800342 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700343 const IncFsMount& mnt = *ifs;
344 dprintf(fd, " [%d]: {\n", id);
345 if (id != mnt.mountId) {
346 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
347 } else {
348 dprintf(fd, " mountId: %d\n", mnt.mountId);
349 dprintf(fd, " root: %s\n", mnt.root.c_str());
350 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
351 if (mnt.dataLoaderStub) {
352 mnt.dataLoaderStub->onDump(fd);
353 } else {
354 dprintf(fd, " dataLoader: null\n");
355 }
356 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
357 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700358 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800359 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str(),
360 /*stopOnFirstIncomplete=*/false)
361 .getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800362 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700363 }
364 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800365
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700366 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
367 for (auto&& [target, bind] : mnt.bindPoints) {
368 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
369 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
370 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
371 dprintf(fd, " kind: %s\n", toString(bind.kind));
372 }
373 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800374 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700375 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800376 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700377 dprintf(fd, "}\n");
378 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800379 for (auto&& [target, mountPairIt] : mBindsByPath) {
380 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700381 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
382 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
383 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
384 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800385 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700386 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800387}
388
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700389void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800390 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700391 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800392 }
393
394 std::vector<IfsMountPtr> mounts;
395 {
396 std::lock_guard l(mLock);
397 mounts.reserve(mMounts.size());
398 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -0700399 if (ifs->mountId == id &&
400 ifs->dataLoaderStub->params().packageName == Constants::systemPackage) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800401 mounts.push_back(ifs);
402 }
403 }
404 }
405
Alex Buynytskyy69941662020-04-11 21:40:37 -0700406 if (mounts.empty()) {
407 return;
408 }
409
Songchun Fan3c82a302019-11-29 14:23:45 -0800410 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700411 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800412 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700413 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800414 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800415 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800416}
417
418auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
419 for (;;) {
420 if (mNextId == kMaxStorageId) {
421 mNextId = 0;
422 }
423 auto id = ++mNextId;
424 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
425 if (inserted) {
426 return it;
427 }
428 }
429}
430
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800431StorageId IncrementalService::createStorage(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800432 std::string_view mountPoint, const content::pm::DataLoaderParamsParcel& dataLoaderParams,
433 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800434 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
435 if (!path::isAbsolute(mountPoint)) {
436 LOG(ERROR) << "path is not absolute: " << mountPoint;
437 return kInvalidStorageId;
438 }
439
440 auto mountNorm = path::normalize(mountPoint);
441 {
442 const auto id = findStorageId(mountNorm);
443 if (id != kInvalidStorageId) {
444 if (options & CreateOptions::OpenExisting) {
445 LOG(INFO) << "Opened existing storage " << id;
446 return id;
447 }
448 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
449 return kInvalidStorageId;
450 }
451 }
452
453 if (!(options & CreateOptions::CreateNew)) {
454 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
455 return kInvalidStorageId;
456 }
457
458 if (!path::isEmptyDir(mountNorm)) {
459 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
460 return kInvalidStorageId;
461 }
462 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
463 if (mountRoot.empty()) {
464 LOG(ERROR) << "Bad mount point";
465 return kInvalidStorageId;
466 }
467 // Make sure the code removes all crap it may create while still failing.
468 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
469 auto firstCleanupOnFailure =
470 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
471
472 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800473 const auto backing = path::join(mountRoot, constants().backing);
474 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800475 return kInvalidStorageId;
476 }
477
Songchun Fan3c82a302019-11-29 14:23:45 -0800478 IncFsMount::Control control;
479 {
480 std::lock_guard l(mMountOperationLock);
481 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800482
483 if (auto err = rmDirContent(backing.c_str())) {
484 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
485 return kInvalidStorageId;
486 }
487 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
488 return kInvalidStorageId;
489 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800490 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
491 return kInvalidStorageId;
492 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800493 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800494 if (!status.isOk()) {
495 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
496 return kInvalidStorageId;
497 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800498 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
499 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800500 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
501 return kInvalidStorageId;
502 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800503 int cmd = controlParcel.cmd.release().release();
504 int pendingReads = controlParcel.pendingReads.release().release();
505 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800506 int blocksWritten =
507 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
508 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800509 }
510
511 std::unique_lock l(mLock);
512 const auto mountIt = getStorageSlotLocked();
513 const auto mountId = mountIt->first;
514 l.unlock();
515
516 auto ifs =
517 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
518 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
519 // is the removal of the |ifs|.
520 firstCleanupOnFailure.release();
521
522 auto secondCleanup = [this, &l](auto itPtr) {
523 if (!l.owns_lock()) {
524 l.lock();
525 }
526 mMounts.erase(*itPtr);
527 };
528 auto secondCleanupOnFailure =
529 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
530
531 const auto storageIt = ifs->makeStorage(ifs->mountId);
532 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800533 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800534 return kInvalidStorageId;
535 }
536
537 {
538 metadata::Mount m;
539 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700540 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800541 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
542 m.mutable_loader()->set_class_name(dataLoaderParams.className);
543 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800544 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800545 if (auto err =
546 mIncFs->makeFile(ifs->control,
547 path::join(ifs->root, constants().mount,
548 constants().infoMdName),
549 0777, idFromMetadata(metadata),
550 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800551 LOG(ERROR) << "Saving mount metadata failed: " << -err;
552 return kInvalidStorageId;
553 }
554 }
555
556 const auto bk =
557 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800558 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
559 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800560 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800561 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800562 return kInvalidStorageId;
563 }
564
565 // Done here as well, all data structures are in good state.
566 secondCleanupOnFailure.release();
567
Songchun Fan3c82a302019-11-29 14:23:45 -0800568 mountIt->second = std::move(ifs);
569 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700570
Songchun Fan3c82a302019-11-29 14:23:45 -0800571 LOG(INFO) << "created storage " << mountId;
572 return mountId;
573}
574
575StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
576 StorageId linkedStorage,
577 IncrementalService::CreateOptions options) {
578 if (!isValidMountTarget(mountPoint)) {
579 LOG(ERROR) << "Mount point is invalid or missing";
580 return kInvalidStorageId;
581 }
582
583 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700584 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800585 if (!ifs) {
586 LOG(ERROR) << "Ifs unavailable";
587 return kInvalidStorageId;
588 }
589
590 const auto mountIt = getStorageSlotLocked();
591 const auto storageId = mountIt->first;
592 const auto storageIt = ifs->makeStorage(storageId);
593 if (storageIt == ifs->storages.end()) {
594 LOG(ERROR) << "Can't create a new storage";
595 mMounts.erase(mountIt);
596 return kInvalidStorageId;
597 }
598
599 l.unlock();
600
601 const auto bk =
602 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800603 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
604 std::string(storageIt->second.name), path::normalize(mountPoint),
605 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800606 err < 0) {
607 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700608 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
609 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800610 return kInvalidStorageId;
611 }
612
613 mountIt->second = ifs;
614 return storageId;
615}
616
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800617bool IncrementalService::startLoading(StorageId storage,
618 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
619 const DataLoaderStatusListener& statusListener,
620 StorageHealthCheckParams&& healthCheckParams,
621 const StorageHealthListener& healthListener,
622 const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
623 // Per Uid timeouts.
624 if (!perUidReadTimeouts.empty()) {
625 setUidReadTimeouts(storage, perUidReadTimeouts);
626 }
627
628 // Re-initialize DataLoader.
629 std::unique_lock l(mLock);
630 const auto ifs = getIfsLocked(storage);
631 if (!ifs) {
632 return false;
633 }
634 if (ifs->dataLoaderStub) {
635 ifs->dataLoaderStub->cleanupResources();
636 ifs->dataLoaderStub = {};
637 }
638 l.unlock();
639
640 // DataLoader.
641 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
642 std::move(healthCheckParams), &healthListener);
643 CHECK(dataLoaderStub);
644
645 return dataLoaderStub->requestStart();
646}
647
Songchun Fan3c82a302019-11-29 14:23:45 -0800648IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
649 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700650 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800651}
652
653StorageId IncrementalService::findStorageId(std::string_view path) const {
654 std::lock_guard l(mLock);
655 auto it = findStorageLocked(path);
656 if (it == mBindsByPath.end()) {
657 return kInvalidStorageId;
658 }
659 return it->second->second.storage;
660}
661
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800662void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700663 std::unique_lock l(mLock);
664 const auto ifs = getIfsLocked(storageId);
665 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800666 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700667 return;
668 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800669 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700670 return;
671 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800672 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700673 l.unlock();
674
675 const auto metadata = constants().readLogsDisabledMarkerName;
676 if (auto err = mIncFs->makeFile(ifs->control,
677 path::join(ifs->root, constants().mount,
678 constants().readLogsDisabledMarkerName),
679 0777, idFromMetadata(metadata), {})) {
680 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
681 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
682 return;
683 }
684
685 setStorageParams(storageId, /*enableReadLogs=*/false);
686}
687
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700688int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
689 const auto ifs = getIfs(storageId);
690 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700691 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700692 return -EINVAL;
693 }
694
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700695 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700696 if (enableReadLogs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800697 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700698 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
699 return -EPERM;
700 }
701
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800702 // Check loader usage stats permission and apop.
703 if (auto status = mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700704 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700705 !status.isOk()) {
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800706 LOG(ERROR) << " Permission: " << kLoaderUsageStats
707 << " check failed: " << status.toString8();
708 return fromBinderStatus(status);
709 }
710
711 // Check multiuser permission.
712 if (auto status = mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr,
713 params.packageName.c_str());
714 !status.isOk()) {
715 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
716 << " check failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700717 return fromBinderStatus(status);
718 }
719 }
720
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700721 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
722 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
723 return fromBinderStatus(status);
724 }
725
726 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700727 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700728 }
729
730 return 0;
731}
732
733binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700734 os::incremental::IncrementalFileSystemControlParcel control;
735 control.cmd.reset(dup(ifs.control.cmd()));
736 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700737 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700738 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700739 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700740 }
741
742 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800743 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
744 if (status.isOk()) {
745 // Store enabled state.
746 ifs.setReadLogsEnabled(enableReadLogs);
747 }
748 return status;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700749}
750
Songchun Fan3c82a302019-11-29 14:23:45 -0800751void IncrementalService::deleteStorage(StorageId storageId) {
752 const auto ifs = getIfs(storageId);
753 if (!ifs) {
754 return;
755 }
756 deleteStorage(*ifs);
757}
758
759void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
760 std::unique_lock l(ifs.lock);
761 deleteStorageLocked(ifs, std::move(l));
762}
763
764void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
765 std::unique_lock<std::mutex>&& ifsLock) {
766 const auto storages = std::move(ifs.storages);
767 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
768 const auto bindPoints = ifs.bindPoints;
769 ifsLock.unlock();
770
771 std::lock_guard l(mLock);
772 for (auto&& [id, _] : storages) {
773 if (id != ifs.mountId) {
774 mMounts.erase(id);
775 }
776 }
777 for (auto&& [path, _] : bindPoints) {
778 mBindsByPath.erase(path);
779 }
780 mMounts.erase(ifs.mountId);
781}
782
783StorageId IncrementalService::openStorage(std::string_view pathInMount) {
784 if (!path::isAbsolute(pathInMount)) {
785 return kInvalidStorageId;
786 }
787
788 return findStorageId(path::normalize(pathInMount));
789}
790
Songchun Fan3c82a302019-11-29 14:23:45 -0800791IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
792 std::lock_guard l(mLock);
793 return getIfsLocked(storage);
794}
795
796const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
797 auto it = mMounts.find(storage);
798 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700799 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700800 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800801 }
802 return it->second;
803}
804
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800805int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
806 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800807 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700808 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800809 return -EINVAL;
810 }
811
812 const auto ifs = getIfs(storage);
813 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700814 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800815 return -EINVAL;
816 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800817
Songchun Fan3c82a302019-11-29 14:23:45 -0800818 std::unique_lock l(ifs->lock);
819 const auto storageInfo = ifs->storages.find(storage);
820 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700821 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800822 return -EINVAL;
823 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700824 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700825 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700826 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700827 return -EINVAL;
828 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800829 l.unlock();
830 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800831 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
832 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800833}
834
835int IncrementalService::unbind(StorageId storage, std::string_view target) {
836 if (!path::isAbsolute(target)) {
837 return -EINVAL;
838 }
839
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700840 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800841
842 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
843 // otherwise there's a chance to unmount something completely unrelated
844 const auto norm = path::normalize(target);
845 std::unique_lock l(mLock);
846 const auto storageIt = mBindsByPath.find(norm);
847 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
848 return -EINVAL;
849 }
850 const auto bindIt = storageIt->second;
851 const auto storageId = bindIt->second.storage;
852 const auto ifs = getIfsLocked(storageId);
853 if (!ifs) {
854 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
855 << " is missing";
856 return -EFAULT;
857 }
858 mBindsByPath.erase(storageIt);
859 l.unlock();
860
861 mVold->unmountIncFs(bindIt->first);
862 std::unique_lock l2(ifs->lock);
863 if (ifs->bindPoints.size() <= 1) {
864 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700865 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800866 } else {
867 const std::string savedFile = std::move(bindIt->second.savedFilename);
868 ifs->bindPoints.erase(bindIt);
869 l2.unlock();
870 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800871 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800872 }
873 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700874
Songchun Fan3c82a302019-11-29 14:23:45 -0800875 return 0;
876}
877
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700878std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700879 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700880 std::string_view path) const {
881 if (!path::isAbsolute(path)) {
882 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700883 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700884 auto normPath = path::normalize(path);
885 if (path::startsWith(normPath, storageIt->second.name)) {
886 return normPath;
887 }
888 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700889 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
890 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700891 return {};
892 }
893 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700894}
895
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700896std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700897 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700898 std::unique_lock l(ifs.lock);
899 const auto storageInfo = ifs.storages.find(storage);
900 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800901 return {};
902 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700903 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800904}
905
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800906int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700907 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800908 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700909 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800910 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700911 LOG(ERROR) << "Internal error: storageId " << storage
912 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800913 return -EINVAL;
914 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700915 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700916 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800917 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800918 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700919 if (!data.empty()) {
920 if (auto err = setFileContent(ifs, id, path, data); err) {
921 return err;
922 }
923 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800924 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800925 }
926 return -EINVAL;
927}
928
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800929int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800930 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700931 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800932 if (normPath.empty()) {
933 return -EINVAL;
934 }
935 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800936 }
937 return -EINVAL;
938}
939
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800940int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800941 const auto ifs = getIfs(storageId);
942 if (!ifs) {
943 return -EINVAL;
944 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700945 return makeDirs(*ifs, storageId, path, mode);
946}
947
948int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
949 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800950 std::string normPath = normalizePathToStorage(ifs, storageId, path);
951 if (normPath.empty()) {
952 return -EINVAL;
953 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700954 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800955}
956
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800957int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
958 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700959 std::unique_lock l(mLock);
960 auto ifsSrc = getIfsLocked(sourceStorageId);
961 if (!ifsSrc) {
962 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800963 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700964 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
965 return -EINVAL;
966 }
967 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700968 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
969 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700970 if (normOldPath.empty() || normNewPath.empty()) {
971 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
972 return -EINVAL;
973 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800974 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
975 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
976 << " to " << newPath << "[" << normNewPath << "]";
977 return err;
978 }
979 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800980}
981
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800982int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800983 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700984 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800985 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800986 }
987 return -EINVAL;
988}
989
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800990int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
991 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800992 std::string&& target, BindKind kind,
993 std::unique_lock<std::mutex>& mainLock) {
994 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700995 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800996 return -EINVAL;
997 }
998
999 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001000 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001001 if (kind != BindKind::Temporary) {
1002 metadata::BindPoint bp;
1003 bp.set_storage_id(storage);
1004 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001005 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001006 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001007 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001008 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001009 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001010 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1011 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1012 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001013 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001014 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001015 return int(node);
1016 }
1017 }
1018
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001019 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1020 std::move(target), kind, mainLock);
1021 if (res) {
1022 mIncFs->unlink(ifs.control, metadataFullPath);
1023 }
1024 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001025}
1026
1027int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001028 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001029 std::string&& target, BindKind kind,
1030 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001031 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001032 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001033 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001034 if (!status.isOk()) {
1035 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1036 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1037 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1038 : status.serviceSpecificErrorCode() == 0
1039 ? -EFAULT
1040 : status.serviceSpecificErrorCode()
1041 : -EIO;
1042 }
1043 }
1044
1045 if (!mainLock.owns_lock()) {
1046 mainLock.lock();
1047 }
1048 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001049 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1050 std::move(target), kind);
1051 return 0;
1052}
1053
1054void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1055 std::string&& metadataName, std::string&& source,
1056 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001057 const auto [it, _] =
1058 ifs.bindPoints.insert_or_assign(target,
1059 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001060 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001061 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001062}
1063
1064RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1065 const auto ifs = getIfs(storage);
1066 if (!ifs) {
1067 return {};
1068 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001069 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001070 if (normPath.empty()) {
1071 return {};
1072 }
1073 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001074}
1075
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001076RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001077 const auto ifs = getIfs(storage);
1078 if (!ifs) {
1079 return {};
1080 }
1081 return mIncFs->getMetadata(ifs->control, node);
1082}
1083
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001084void IncrementalService::setUidReadTimeouts(
1085 StorageId storage, const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
1086 using microseconds = std::chrono::microseconds;
1087 using milliseconds = std::chrono::milliseconds;
1088
1089 auto maxPendingTimeUs = microseconds(0);
1090 for (const auto& timeouts : perUidReadTimeouts) {
1091 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1092 }
1093 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001094 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001095 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1096 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001097 return;
1098 }
1099
1100 const auto ifs = getIfs(storage);
1101 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001102 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001103 return;
1104 }
1105
1106 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1107 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1108 return;
1109 }
1110
1111 const auto timeout = std::chrono::duration_cast<milliseconds>(maxPendingTimeUs) -
1112 Constants::perUidTimeoutOffset;
1113 updateUidReadTimeouts(storage, Clock::now() + timeout);
1114}
1115
1116void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1117 const auto ifs = getIfs(storage);
1118 if (!ifs) {
1119 return;
1120 }
1121
1122 mIncFs->setUidReadTimeouts(ifs->control, {});
1123}
1124
1125void IncrementalService::updateUidReadTimeouts(StorageId storage, Clock::time_point timeLimit) {
1126 // Reached maximum timeout.
1127 if (Clock::now() >= timeLimit) {
1128 return clearUidReadTimeouts(storage);
1129 }
1130
1131 // Still loading?
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001132 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/true);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001133 if (progress.isError()) {
1134 // Something is wrong, abort.
1135 return clearUidReadTimeouts(storage);
1136 }
1137
1138 if (progress.started() && progress.fullyLoaded()) {
1139 // Fully loaded, check readLogs collection.
1140 const auto ifs = getIfs(storage);
1141 if (!ifs->readLogsEnabled()) {
1142 return clearUidReadTimeouts(storage);
1143 }
1144 }
1145
1146 const auto timeLeft = timeLimit - Clock::now();
1147 if (timeLeft < Constants::progressUpdateInterval) {
1148 // Don't bother.
1149 return clearUidReadTimeouts(storage);
1150 }
1151
1152 addTimedJob(*mTimedQueue, storage, Constants::progressUpdateInterval,
1153 [this, storage, timeLimit]() { updateUidReadTimeouts(storage, timeLimit); });
1154}
1155
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001156std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1157 std::unordered_set<std::string_view> mountedRootNames;
1158 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1159 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1160 for (auto [source, target] : binds) {
1161 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1162 LOG(INFO) << " " << path::join(root, source);
1163 }
1164
1165 // Ensure it's a kind of a mount that's managed by IncrementalService
1166 if (path::basename(root) != constants().mount ||
1167 path::basename(backingDir) != constants().backing) {
1168 return;
1169 }
1170 const auto expectedRoot = path::dirname(root);
1171 if (path::dirname(backingDir) != expectedRoot) {
1172 return;
1173 }
1174 if (path::dirname(expectedRoot) != mIncrementalDir) {
1175 return;
1176 }
1177 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1178 return;
1179 }
1180
1181 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1182
1183 // make sure we clean up the mount if it happens to be a bad one.
1184 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1185 auto cleanupFiles = makeCleanup([&]() {
1186 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1187 IncFsMount::cleanupFilesystem(expectedRoot);
1188 });
1189 auto cleanupMounts = makeCleanup([&]() {
1190 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1191 for (auto&& [_, target] : binds) {
1192 mVold->unmountIncFs(std::string(target));
1193 }
1194 mVold->unmountIncFs(std::string(root));
1195 });
1196
1197 auto control = mIncFs->openMount(root);
1198 if (!control) {
1199 LOG(INFO) << "failed to open mount " << root;
1200 return;
1201 }
1202
1203 auto mountRecord =
1204 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1205 path::join(root, constants().infoMdName));
1206 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1207 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1208 return;
1209 }
1210
1211 auto mountId = mountRecord.storage().id();
1212 mNextId = std::max(mNextId, mountId + 1);
1213
1214 DataLoaderParamsParcel dataLoaderParams;
1215 {
1216 const auto& loader = mountRecord.loader();
1217 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1218 dataLoaderParams.packageName = loader.package_name();
1219 dataLoaderParams.className = loader.class_name();
1220 dataLoaderParams.arguments = loader.arguments();
1221 }
1222
1223 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1224 std::move(control), *this);
1225 cleanupFiles.release(); // ifs will take care of that now
1226
Alex Buynytskyy04035452020-06-06 20:15:58 -07001227 // Check if marker file present.
1228 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001229 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001230 }
1231
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001232 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1233 auto d = openDir(root);
1234 while (auto e = ::readdir(d.get())) {
1235 if (e->d_type == DT_REG) {
1236 auto name = std::string_view(e->d_name);
1237 if (name.starts_with(constants().mountpointMdPrefix)) {
1238 permanentBindPoints
1239 .emplace_back(name,
1240 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1241 ifs->control,
1242 path::join(root,
1243 name)));
1244 if (permanentBindPoints.back().second.dest_path().empty() ||
1245 permanentBindPoints.back().second.source_subdir().empty()) {
1246 permanentBindPoints.pop_back();
1247 mIncFs->unlink(ifs->control, path::join(root, name));
1248 } else {
1249 LOG(INFO) << "Permanent bind record: '"
1250 << permanentBindPoints.back().second.source_subdir() << "'->'"
1251 << permanentBindPoints.back().second.dest_path() << "'";
1252 }
1253 }
1254 } else if (e->d_type == DT_DIR) {
1255 if (e->d_name == "."sv || e->d_name == ".."sv) {
1256 continue;
1257 }
1258 auto name = std::string_view(e->d_name);
1259 if (name.starts_with(constants().storagePrefix)) {
1260 int storageId;
1261 const auto res =
1262 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1263 name.data() + name.size(), storageId);
1264 if (res.ec != std::errc{} || *res.ptr != '_') {
1265 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1266 << "' for mount " << expectedRoot;
1267 continue;
1268 }
1269 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1270 if (!inserted) {
1271 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1272 << " for mount " << expectedRoot;
1273 continue;
1274 }
1275 ifs->storages.insert_or_assign(storageId,
1276 IncFsMount::Storage{path::join(root, name)});
1277 mNextId = std::max(mNextId, storageId + 1);
1278 }
1279 }
1280 }
1281
1282 if (ifs->storages.empty()) {
1283 LOG(WARNING) << "No valid storages in mount " << root;
1284 return;
1285 }
1286
1287 // now match the mounted directories with what we expect to have in the metadata
1288 {
1289 std::unique_lock l(mLock, std::defer_lock);
1290 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1291 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1292 [&, bindRecord = bindRecord](auto&& bind) {
1293 return bind.second == bindRecord.dest_path() &&
1294 path::join(root, bind.first) ==
1295 bindRecord.source_subdir();
1296 });
1297 if (mountedIt != binds.end()) {
1298 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1299 << " to mount " << mountedIt->first;
1300 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1301 std::move(*bindRecord.mutable_source_subdir()),
1302 std::move(*bindRecord.mutable_dest_path()),
1303 BindKind::Permanent);
1304 if (mountedIt != binds.end() - 1) {
1305 std::iter_swap(mountedIt, binds.end() - 1);
1306 }
1307 binds = binds.first(binds.size() - 1);
1308 } else {
1309 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1310 << ", mounting";
1311 // doesn't exist - try mounting back
1312 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1313 std::move(*bindRecord.mutable_source_subdir()),
1314 std::move(*bindRecord.mutable_dest_path()),
1315 BindKind::Permanent, l)) {
1316 mIncFs->unlink(ifs->control, metadataFile);
1317 }
1318 }
1319 }
1320 }
1321
1322 // if anything stays in |binds| those are probably temporary binds; system restarted since
1323 // they were mounted - so let's unmount them all.
1324 for (auto&& [source, target] : binds) {
1325 if (source.empty()) {
1326 continue;
1327 }
1328 mVold->unmountIncFs(std::string(target));
1329 }
1330 cleanupMounts.release(); // ifs now manages everything
1331
1332 if (ifs->bindPoints.empty()) {
1333 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1334 deleteStorage(*ifs);
1335 return;
1336 }
1337
1338 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1339 CHECK(ifs->dataLoaderStub);
1340
1341 mountedRootNames.insert(path::basename(ifs->root));
1342
1343 // not locking here at all: we're still in the constructor, no other calls can happen
1344 mMounts[ifs->mountId] = std::move(ifs);
1345 });
1346
1347 return mountedRootNames;
1348}
1349
1350void IncrementalService::mountExistingImages(
1351 const std::unordered_set<std::string_view>& mountedRootNames) {
1352 auto dir = openDir(mIncrementalDir);
1353 if (!dir) {
1354 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1355 return;
1356 }
1357 while (auto entry = ::readdir(dir.get())) {
1358 if (entry->d_type != DT_DIR) {
1359 continue;
1360 }
1361 std::string_view name = entry->d_name;
1362 if (!name.starts_with(constants().mountKeyPrefix)) {
1363 continue;
1364 }
1365 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001366 continue;
1367 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001368 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001369 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001370 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001371 }
1372 }
1373}
1374
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001375bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001376 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001377 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001378
Songchun Fan3c82a302019-11-29 14:23:45 -08001379 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001380 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001381 if (!status.isOk()) {
1382 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1383 return false;
1384 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001385
1386 int cmd = controlParcel.cmd.release().release();
1387 int pendingReads = controlParcel.pendingReads.release().release();
1388 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001389 int blocksWritten =
1390 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1391 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001392
1393 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1394
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001395 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1396 path::join(mountTarget, constants().infoMdName));
1397 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001398 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1399 return false;
1400 }
1401
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001402 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001403 mNextId = std::max(mNextId, ifs->mountId + 1);
1404
Alex Buynytskyy04035452020-06-06 20:15:58 -07001405 // Check if marker file present.
1406 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001407 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001408 }
1409
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001410 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001411 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001412 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001413 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001414 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001415 dataLoaderParams.packageName = loader.package_name();
1416 dataLoaderParams.className = loader.class_name();
1417 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001418 }
1419
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001420 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001421 CHECK(ifs->dataLoaderStub);
1422
Songchun Fan3c82a302019-11-29 14:23:45 -08001423 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001424 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001425 while (auto e = ::readdir(d.get())) {
1426 if (e->d_type == DT_REG) {
1427 auto name = std::string_view(e->d_name);
1428 if (name.starts_with(constants().mountpointMdPrefix)) {
1429 bindPoints.emplace_back(name,
1430 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1431 ifs->control,
1432 path::join(mountTarget,
1433 name)));
1434 if (bindPoints.back().second.dest_path().empty() ||
1435 bindPoints.back().second.source_subdir().empty()) {
1436 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001437 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001438 }
1439 }
1440 } else if (e->d_type == DT_DIR) {
1441 if (e->d_name == "."sv || e->d_name == ".."sv) {
1442 continue;
1443 }
1444 auto name = std::string_view(e->d_name);
1445 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001446 int storageId;
1447 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1448 name.data() + name.size(), storageId);
1449 if (res.ec != std::errc{} || *res.ptr != '_') {
1450 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1451 << root;
1452 continue;
1453 }
1454 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001455 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001456 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001457 << " for mount " << root;
1458 continue;
1459 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001460 ifs->storages.insert_or_assign(storageId,
1461 IncFsMount::Storage{
1462 path::join(root, constants().mount, name)});
1463 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001464 }
1465 }
1466 }
1467
1468 if (ifs->storages.empty()) {
1469 LOG(WARNING) << "No valid storages in mount " << root;
1470 return false;
1471 }
1472
1473 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001474 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001475 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001476 for (auto&& bp : bindPoints) {
1477 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1478 std::move(*bp.second.mutable_source_subdir()),
1479 std::move(*bp.second.mutable_dest_path()),
1480 BindKind::Permanent, l);
1481 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001482 }
1483
1484 if (bindCount == 0) {
1485 LOG(WARNING) << "No valid bind points for mount " << root;
1486 deleteStorage(*ifs);
1487 return false;
1488 }
1489
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001490 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001491 mMounts[ifs->mountId] = std::move(ifs);
1492 return true;
1493}
1494
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001495void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001496 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001497 while (mRunning.load(std::memory_order_relaxed)) {
1498 mLooper->pollAll(kTimeoutMsecs);
1499 }
1500}
1501
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001502IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001503 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001504 const DataLoaderStatusListener* statusListener,
1505 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001506 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001507 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1508 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001509 return ifs.dataLoaderStub;
1510}
1511
1512void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001513 const DataLoaderStatusListener* statusListener,
1514 StorageHealthCheckParams&& healthCheckParams,
1515 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001516 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001517 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001518 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001519 }
1520
Songchun Fan3c82a302019-11-29 14:23:45 -08001521 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001522 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001523 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1524 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1525 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001526 if (ifs.control.blocksWritten() >= 0) {
1527 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1528 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001529 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001530
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001531 ifs.dataLoaderStub =
1532 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001533 statusListener, std::move(healthCheckParams), healthListener,
1534 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001535}
1536
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001537template <class Duration>
1538static long elapsedMcs(Duration start, Duration end) {
1539 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1540}
1541
1542// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001543// Lib files should be placed next to the APK file in the following matter:
1544// Example:
1545// /path/to/base.apk
1546// /path/to/lib/arm/first.so
1547// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001548bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1549 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001550 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001551 auto start = Clock::now();
1552
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001553 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001554 if (!ifs) {
1555 LOG(ERROR) << "Invalid storage " << storage;
1556 return false;
1557 }
1558
Songchun Fanc8975312020-07-13 12:14:37 -07001559 const auto targetLibPathRelativeToStorage =
1560 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1561 libDirRelativePath);
1562
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001563 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001564 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1565 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001566 << " errno: " << res;
1567 return false;
1568 }
1569
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001570 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001571 ZipArchiveHandle zipFileHandle;
1572 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001573 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1574 return false;
1575 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001576
1577 // Need a shared pointer: will be passing it into all unpacking jobs.
1578 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001579 void* cookie = nullptr;
Songchun Fan2ff2a482020-09-29 11:45:18 -07001580 const auto libFilePrefix = path::join(constants().libDir, abi) + "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001581 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001582 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1583 return false;
1584 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001585 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001586 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1587
1588 auto openZipTs = Clock::now();
1589
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001590 std::vector<Job> jobQueue;
1591 ZipEntry entry;
1592 std::string_view fileName;
1593 while (!Next(cookie, &entry, &fileName)) {
1594 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001595 continue;
1596 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001597
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001598 if (!extractNativeLibs) {
1599 // ensure the file is properly aligned and unpacked
1600 if (entry.method != kCompressStored) {
1601 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1602 return false;
1603 }
1604 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1605 LOG(WARNING) << "Library " << fileName
1606 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1607 << entry.offset;
1608 return false;
1609 }
1610 continue;
1611 }
1612
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001613 auto startFileTs = Clock::now();
1614
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001615 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001616 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001617 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001618 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001619 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001620 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001621 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1622 << "; skipping extraction, spent "
1623 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1624 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001625 continue;
1626 }
1627
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001628 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001629 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001630 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001631 .signature = {},
1632 // Metadata of the new lib file is its relative path
1633 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1634 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001635 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001636 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1637 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001638 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001639 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001640 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001641 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001642
1643 auto makeFileTs = Clock::now();
1644
Songchun Fanafaf6e92020-03-18 14:12:20 -07001645 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001646 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001647 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001648 LOG(INFO) << "incfs: Extracted " << libName
1649 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001650 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001651 continue;
1652 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001653
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001654 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1655 libFileId, libPath = std::move(targetLibPath),
1656 makeFileTs]() mutable {
1657 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001658 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001659
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001660 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001661 auto prepareJobTs = Clock::now();
1662 LOG(INFO) << "incfs: Processed " << libName << ": "
1663 << elapsedMcs(startFileTs, prepareJobTs)
1664 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1665 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001666 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001667 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001668
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001669 auto processedTs = Clock::now();
1670
1671 if (!jobQueue.empty()) {
1672 {
1673 std::lock_guard lock(mJobMutex);
1674 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001675 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001676 if (existingJobs.empty()) {
1677 existingJobs = std::move(jobQueue);
1678 } else {
1679 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1680 std::move_iterator(jobQueue.end()));
1681 }
1682 }
1683 }
1684 mJobCondition.notify_all();
1685 }
1686
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001687 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001688 auto end = Clock::now();
1689 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1690 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1691 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001692 << " make files: " << elapsedMcs(openZipTs, processedTs)
1693 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001694 }
1695
1696 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001697}
1698
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001699void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1700 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001701 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001702 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001703 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001704 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001705 return;
1706 }
1707
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001708 auto startedTs = Clock::now();
1709
1710 // Write extracted data to new file
1711 // NOTE: don't zero-initialize memory, it may take a while for nothing
1712 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1713 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001714 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001715 return;
1716 }
1717
1718 auto extractFileTs = Clock::now();
1719
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001720 if (setFileContent(ifs, libFileId, debugLibPath,
1721 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001722 return;
1723 }
1724
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001725 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001726 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001727 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1728 << entry.compressed_length << " -> " << entry.uncompressed_length
1729 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001730 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1731 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001732 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001733 }
1734}
1735
1736bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001737 struct WaitPrinter {
1738 const Clock::time_point startTs = Clock::now();
1739 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001740 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001741 const auto endTs = Clock::now();
1742 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1743 << elapsedMcs(startTs, endTs) << "mcs";
1744 }
1745 }
1746 } waitPrinter;
1747
1748 MountId mount;
1749 {
1750 auto ifs = getIfs(storage);
1751 if (!ifs) {
1752 return true;
1753 }
1754 mount = ifs->mountId;
1755 }
1756
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001757 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001758 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001759 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001760 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001761 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001762 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001763}
1764
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001765int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1766 std::string_view debugFilePath,
1767 std::span<const uint8_t> data) const {
1768 auto startTs = Clock::now();
1769
1770 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1771 if (!writeFd.ok()) {
1772 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1773 << " errno: " << writeFd.get();
1774 return writeFd.get();
1775 }
1776
1777 const auto dataLength = data.size();
1778
1779 auto openFileTs = Clock::now();
1780 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1781 std::vector<IncFsDataBlock> instructions(numBlocks);
1782 for (int i = 0; i < numBlocks; i++) {
1783 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1784 instructions[i] = IncFsDataBlock{
1785 .fileFd = writeFd.get(),
1786 .pageIndex = static_cast<IncFsBlockIndex>(i),
1787 .compression = INCFS_COMPRESSION_KIND_NONE,
1788 .kind = INCFS_BLOCK_KIND_DATA,
1789 .dataSize = static_cast<uint32_t>(blockSize),
1790 .data = reinterpret_cast<const char*>(data.data()),
1791 };
1792 data = data.subspan(blockSize);
1793 }
1794 auto prepareInstsTs = Clock::now();
1795
1796 size_t res = mIncFs->writeBlocks(instructions);
1797 if (res != instructions.size()) {
1798 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1799 return res;
1800 }
1801
1802 if (perfLoggingEnabled()) {
1803 auto endTs = Clock::now();
1804 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1805 << " bytes): " << elapsedMcs(startTs, endTs)
1806 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1807 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1808 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1809 }
1810
1811 return 0;
1812}
1813
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001814int IncrementalService::isFileFullyLoaded(StorageId storage, std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001815 std::unique_lock l(mLock);
1816 const auto ifs = getIfsLocked(storage);
1817 if (!ifs) {
1818 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1819 return -EINVAL;
1820 }
1821 const auto storageInfo = ifs->storages.find(storage);
1822 if (storageInfo == ifs->storages.end()) {
1823 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1824 return -EINVAL;
1825 }
1826 l.unlock();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001827 return isFileFullyLoadedFromPath(*ifs, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001828}
1829
1830int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1831 std::string_view filePath) const {
1832 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1833 if (filledBlocks < 0) {
1834 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1835 << filePath << " errno: " << filledBlocks;
1836 return filledBlocks;
1837 }
1838 if (totalBlocks < filledBlocks) {
1839 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1840 return -EINVAL;
1841 }
1842 return totalBlocks - filledBlocks;
1843}
1844
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001845IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001846 StorageId storage, bool stopOnFirstIncomplete) const {
Songchun Fan374f7652020-08-20 08:40:29 -07001847 std::unique_lock l(mLock);
1848 const auto ifs = getIfsLocked(storage);
1849 if (!ifs) {
1850 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001851 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001852 }
1853 const auto storageInfo = ifs->storages.find(storage);
1854 if (storageInfo == ifs->storages.end()) {
1855 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001856 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001857 }
1858 l.unlock();
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001859 return getLoadingProgressFromPath(*ifs, storageInfo->second.name, stopOnFirstIncomplete);
Songchun Fan374f7652020-08-20 08:40:29 -07001860}
1861
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001862IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001863 const IncFsMount& ifs, std::string_view storagePath, bool stopOnFirstIncomplete) const {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001864 ssize_t totalBlocks = 0, filledBlocks = 0;
Songchun Fan374f7652020-08-20 08:40:29 -07001865 const auto filePaths = mFs->listFilesRecursive(storagePath);
1866 for (const auto& filePath : filePaths) {
1867 const auto [filledBlocksCount, totalBlocksCount] =
1868 mIncFs->countFilledBlocks(ifs.control, filePath);
1869 if (filledBlocksCount < 0) {
1870 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1871 << " errno: " << filledBlocksCount;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001872 return {filledBlocksCount, filledBlocksCount};
Songchun Fan374f7652020-08-20 08:40:29 -07001873 }
1874 totalBlocks += totalBlocksCount;
1875 filledBlocks += filledBlocksCount;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001876 if (stopOnFirstIncomplete && filledBlocks < totalBlocks) {
1877 break;
1878 }
Songchun Fan374f7652020-08-20 08:40:29 -07001879 }
1880
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001881 return {filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07001882}
1883
Songchun Fana7098592020-09-03 11:45:53 -07001884bool IncrementalService::updateLoadingProgress(
1885 StorageId storage, const StorageLoadingProgressListener& progressListener) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001886 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/false);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001887 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07001888 // Failed to get progress from incfs, abort.
1889 return false;
1890 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001891 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
1892 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07001893 // Stop updating progress once it is fully loaded
1894 return true;
1895 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001896 addTimedJob(*mProgressUpdateJobQueue, storage,
1897 Constants::progressUpdateInterval /* repeat after 1s */,
Songchun Fana7098592020-09-03 11:45:53 -07001898 [storage, progressListener, this]() {
1899 updateLoadingProgress(storage, progressListener);
1900 });
1901 return true;
1902}
1903
1904bool IncrementalService::registerLoadingProgressListener(
1905 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1906 return updateLoadingProgress(storage, progressListener);
1907}
1908
1909bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
1910 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
1911}
1912
Songchun Fan2570ec02020-10-08 17:22:33 -07001913bool IncrementalService::registerStorageHealthListener(
1914 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
1915 const StorageHealthListener& healthListener) {
1916 DataLoaderStubPtr dataLoaderStub;
1917 {
1918 std::unique_lock l(mLock);
1919 const auto& ifs = getIfsLocked(storage);
1920 if (!ifs) {
1921 return false;
1922 }
1923 dataLoaderStub = ifs->dataLoaderStub;
1924 if (!dataLoaderStub) {
1925 return false;
1926 }
1927 }
1928 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
1929 return true;
1930}
1931
1932void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
1933 StorageHealthCheckParams invalidCheckParams;
1934 invalidCheckParams.blockedTimeoutMs = -1;
1935 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
1936}
1937
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001938bool IncrementalService::perfLoggingEnabled() {
1939 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1940 return enabled;
1941}
1942
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001943void IncrementalService::runJobProcessing() {
1944 for (;;) {
1945 std::unique_lock lock(mJobMutex);
1946 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1947 if (!mRunning) {
1948 return;
1949 }
1950
1951 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001952 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001953 auto queue = std::move(it->second);
1954 mJobQueue.erase(it);
1955 lock.unlock();
1956
1957 for (auto&& job : queue) {
1958 job();
1959 }
1960
1961 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001962 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001963 lock.unlock();
1964 mJobCondition.notify_all();
1965 }
1966}
1967
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001968void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001969 sp<IAppOpsCallback> listener;
1970 {
1971 std::unique_lock lock{mCallbacksLock};
1972 auto& cb = mCallbackRegistered[packageName];
1973 if (cb) {
1974 return;
1975 }
1976 cb = new AppOpsListener(*this, packageName);
1977 listener = cb;
1978 }
1979
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001980 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1981 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001982}
1983
1984bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1985 sp<IAppOpsCallback> listener;
1986 {
1987 std::unique_lock lock{mCallbacksLock};
1988 auto found = mCallbackRegistered.find(packageName);
1989 if (found == mCallbackRegistered.end()) {
1990 return false;
1991 }
1992 listener = found->second;
1993 mCallbackRegistered.erase(found);
1994 }
1995
1996 mAppOpsManager->stopWatchingMode(listener);
1997 return true;
1998}
1999
2000void IncrementalService::onAppOpChanged(const std::string& packageName) {
2001 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002002 return;
2003 }
2004
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002005 std::vector<IfsMountPtr> affected;
2006 {
2007 std::lock_guard l(mLock);
2008 affected.reserve(mMounts.size());
2009 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002010 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002011 affected.push_back(ifs);
2012 }
2013 }
2014 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002015 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002016 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002017 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002018}
2019
Songchun Fana7098592020-09-03 11:45:53 -07002020bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2021 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002022 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002023 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002024 }
Songchun Fana7098592020-09-03 11:45:53 -07002025 timedQueue.addJob(id, after, std::move(what));
2026 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002027}
2028
Songchun Fana7098592020-09-03 11:45:53 -07002029bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002030 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002031 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002032 }
Songchun Fana7098592020-09-03 11:45:53 -07002033 timedQueue.removeJobs(id);
2034 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002035}
2036
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002037IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
2038 DataLoaderParamsParcel&& params,
2039 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002040 const DataLoaderStatusListener* statusListener,
2041 StorageHealthCheckParams&& healthCheckParams,
2042 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002043 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002044 : mService(service),
2045 mId(id),
2046 mParams(std::move(params)),
2047 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002048 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
2049 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002050 mHealthPath(std::move(healthPath)),
2051 mHealthCheckParams(std::move(healthCheckParams)) {
2052 if (mHealthListener) {
2053 if (!isHealthParamsValid()) {
2054 mHealthListener = {};
2055 }
2056 } else {
2057 // Disable advanced health check statuses.
2058 mHealthCheckParams.blockedTimeoutMs = -1;
2059 }
2060 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002061}
2062
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002063IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002064 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002065 cleanupResources();
2066 }
2067}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002068
2069void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002070 auto now = Clock::now();
2071 {
2072 std::unique_lock lock(mMutex);
2073 mHealthPath.clear();
2074 unregisterFromPendingReads();
2075 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002076 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002077 }
2078
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002079 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002080
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002081 {
2082 std::unique_lock lock(mMutex);
2083 mParams = {};
2084 mControl = {};
2085 mHealthControl = {};
2086 mHealthListener = {};
2087 mStatusCondition.wait_until(lock, now + 60s, [this] {
2088 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2089 });
2090 mStatusListener = {};
2091 mId = kInvalidStorageId;
2092 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002093}
2094
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002095sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2096 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002097 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002098 if (!status.isOk()) {
2099 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2100 return {};
2101 }
2102 if (!dataloader) {
2103 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2104 return {};
2105 }
2106 return dataloader;
2107}
2108
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002109bool IncrementalService::DataLoaderStub::requestCreate() {
2110 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2111}
2112
2113bool IncrementalService::DataLoaderStub::requestStart() {
2114 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2115}
2116
2117bool IncrementalService::DataLoaderStub::requestDestroy() {
2118 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2119}
2120
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002121bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002122 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002123 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002124 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002125 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002126 return fsmStep();
2127}
2128
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002129void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002130 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002131 mTargetStatus = status;
2132 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002133 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002134 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002135}
2136
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002137bool IncrementalService::DataLoaderStub::bind() {
2138 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002139 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002140 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002141 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002142 return false;
2143 }
2144 return true;
2145}
2146
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002147bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002148 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002149 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002150 return false;
2151 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002152 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002153 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002154 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002155 return false;
2156 }
2157 return true;
2158}
2159
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002160bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002161 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002162 if (!dataloader) {
2163 return false;
2164 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002165 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002166 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002167 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002168 return false;
2169 }
2170 return true;
2171}
2172
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002173bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002174 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002175}
2176
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002177bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002178 if (!isValid()) {
2179 return false;
2180 }
2181
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002182 int currentStatus;
2183 int targetStatus;
2184 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002185 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002186 currentStatus = mCurrentStatus;
2187 targetStatus = mTargetStatus;
2188 }
2189
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002190 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002191
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002192 if (currentStatus == targetStatus) {
2193 return true;
2194 }
2195
2196 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002197 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2198 // Do nothing, this is a reset state.
2199 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002200 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
2201 return destroy();
2202 }
2203 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2204 switch (currentStatus) {
2205 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2206 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2207 return start();
2208 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002209 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002210 }
2211 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2212 switch (currentStatus) {
2213 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002214 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002215 return bind();
2216 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002217 return create();
2218 }
2219 break;
2220 default:
2221 LOG(ERROR) << "Invalid target status: " << targetStatus
2222 << ", current status: " << currentStatus;
2223 break;
2224 }
2225 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002226}
2227
2228binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002229 if (!isValid()) {
2230 return binder::Status::
2231 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2232 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002233 if (id() != mountId) {
2234 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002235 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2236 }
2237
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002238 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002239 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002240 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002241 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002242 if (mCurrentStatus == newStatus) {
2243 return binder::Status::ok();
2244 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002245
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002246 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002247 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002248 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002249
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002250 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002251
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002252 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002253 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2254 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002255 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002256 }
2257
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002258 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002259 << newStatus << " (target " << targetStatus << ")";
2260
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002261 if (listener) {
2262 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002263 }
2264
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002265 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002266
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002267 mStatusCondition.notify_all();
2268
Songchun Fan3c82a302019-11-29 14:23:45 -08002269 return binder::Status::ok();
2270}
2271
Songchun Fan33093982020-09-10 13:12:39 -07002272binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2273 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002274 if (!isValid()) {
2275 return binder::Status::
2276 fromServiceSpecificError(-EINVAL,
2277 "reportStreamHealth came to invalid DataLoaderStub");
2278 }
2279 if (id() != mountId) {
2280 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
2281 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2282 }
2283 {
2284 std::lock_guard lock(mMutex);
2285 mStreamStatus = newStatus;
2286 }
Songchun Fan33093982020-09-10 13:12:39 -07002287 return binder::Status::ok();
2288}
2289
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002290bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2291 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2292 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002293}
2294
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002295void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2296 int healthStatus) {
2297 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2298 if (healthListener) {
2299 healthListener->onHealthStatus(id(), healthStatus);
2300 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002301}
2302
Songchun Fan2570ec02020-10-08 17:22:33 -07002303static int adjustHealthStatus(int healthStatus, int streamStatus) {
2304 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2305 // everything is good; no need to change status
2306 return healthStatus;
2307 }
2308 int newHeathStatus = healthStatus;
2309 switch (streamStatus) {
2310 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2311 // storage is limited and storage not healthy
2312 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2313 break;
2314 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2315 // fall through
2316 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2317 // fall through
2318 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2319 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2320 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2321 }
2322 // pending/blocked status due to transportation issues is not regarded as unhealthy
2323 break;
2324 default:
2325 break;
2326 }
2327 return newHeathStatus;
2328}
2329
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002330void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2331 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002332
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002333 int healthStatusToReport = -1;
2334 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002335
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002336 {
2337 std::unique_lock lock(mMutex);
2338 unregisterFromPendingReads();
2339
2340 healthListener = mHealthListener;
2341
2342 // Healthcheck depends on timestamp of the oldest pending read.
2343 // 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 -07002344 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2345 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002346 const auto now = Clock::now();
2347 const auto kernelTsUs = getOldestPendingReadTs();
2348 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002349 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2350 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002351 mHealthBase = {now, kernelTsUs};
2352 }
2353
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002354 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2355 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002356 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2357 registerForPendingReads();
2358 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2359 lock.unlock();
2360 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002361 return;
2362 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002363
2364 resetHealthControl();
2365
2366 // Always make sure the data loader is started.
2367 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2368
2369 // Skip any further processing if health check params are invalid.
2370 if (!isHealthParamsValid()) {
2371 LOG(DEBUG) << id()
2372 << ": Skip any further processing if health check params are invalid.";
2373 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2374 lock.unlock();
2375 onHealthStatus(healthListener, healthStatusToReport);
2376 // Triggering data loader start. This is a one-time action.
2377 fsmStep();
2378 return;
2379 }
2380
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002381 // Don't schedule timer job less than 500ms in advance.
2382 static constexpr auto kTolerance = 500ms;
2383
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002384 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2385 const auto unhealthyTimeout =
2386 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2387 const auto unhealthyMonitoring =
2388 std::max(1000ms,
2389 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2390
2391 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2392 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002393 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002394
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002395 Milliseconds checkBackAfter;
2396 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002397 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002398 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002399 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002400 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002401 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002402 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002403 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2404 } else {
2405 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002406 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002407 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2408 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002409 // Adjust health status based on stream status
2410 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002411 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002412 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002413 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2414 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002415 }
2416
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002417 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002418 if (healthStatusToReport != -1) {
2419 onHealthStatus(healthListener, healthStatusToReport);
2420 }
2421
2422 fsmStep();
2423}
2424
2425const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2426 if (mHealthPath.empty()) {
2427 resetHealthControl();
2428 return mHealthControl;
2429 }
2430 if (mHealthControl.pendingReads() < 0) {
2431 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2432 }
2433 if (mHealthControl.pendingReads() < 0) {
2434 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2435 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2436 << mHealthControl.logs() << ")";
2437 }
2438 return mHealthControl;
2439}
2440
2441void IncrementalService::DataLoaderStub::resetHealthControl() {
2442 mHealthControl = {};
2443}
2444
2445BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2446 auto result = kMaxBootClockTsUs;
2447
2448 const auto& control = initializeHealthControl();
2449 if (control.pendingReads() < 0) {
2450 return result;
2451 }
2452
Songchun Fan6944f1e2020-11-06 15:24:24 -08002453 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002454 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002455 mLastPendingReads.empty()) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002456 return result;
2457 }
2458
2459 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002460 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002461
Songchun Fan6944f1e2020-11-06 15:24:24 -08002462 for (auto&& pendingRead : mLastPendingReads) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002463 result = std::min(result, pendingRead.bootClockTsUs);
2464 }
2465 return result;
2466}
2467
2468void IncrementalService::DataLoaderStub::registerForPendingReads() {
2469 const auto pendingReadsFd = mHealthControl.pendingReads();
2470 if (pendingReadsFd < 0) {
2471 return;
2472 }
2473
2474 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2475
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002476 mService.mLooper->addFd(
2477 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2478 [](int, int, void* data) -> int {
2479 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002480 self->updateHealthStatus(/*baseline=*/true);
2481 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002482 },
2483 this);
2484 mService.mLooper->wake();
2485}
2486
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002487void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002488 const auto pendingReadsFd = mHealthControl.pendingReads();
2489 if (pendingReadsFd < 0) {
2490 return;
2491 }
2492
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002493 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2494
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002495 mService.mLooper->removeFd(pendingReadsFd);
2496 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002497}
2498
Songchun Fan2570ec02020-10-08 17:22:33 -07002499void IncrementalService::DataLoaderStub::setHealthListener(
2500 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2501 std::lock_guard lock(mMutex);
2502 mHealthCheckParams = std::move(healthCheckParams);
2503 if (healthListener == nullptr) {
2504 // reset listener and params
2505 mHealthListener = {};
2506 } else {
2507 mHealthListener = *healthListener;
2508 }
2509}
2510
Songchun Fan6944f1e2020-11-06 15:24:24 -08002511static std::string toHexString(const RawMetadata& metadata) {
2512 int n = metadata.size();
2513 std::string res(n * 2, '\0');
2514 // Same as incfs::toString(fileId)
2515 static constexpr char kHexChar[] = "0123456789abcdef";
2516 for (int i = 0; i < n; ++i) {
2517 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2518 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2519 }
2520 return res;
2521}
2522
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002523void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002524 dprintf(fd, " dataLoader: {\n");
2525 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2526 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2527 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002528 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002529 dprintf(fd, " health: {\n");
2530 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2531 dprintf(fd, " base: %lldmcs (%lld)\n",
2532 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2533 (long long)mHealthBase.kernelTsUs);
2534 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2535 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2536 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2537 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002538 dprintf(fd, " lastPendingReads: \n");
2539 const auto control = mService.mIncFs->openMount(mHealthPath);
2540 for (auto&& pendingRead : mLastPendingReads) {
2541 dprintf(fd, " fileId: %s\n", mService.mIncFs->toString(pendingRead.id).c_str());
2542 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2543 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2544 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2545 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2546 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002547 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002548 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002549 dprintf(fd, " dataLoaderParams: {\n");
2550 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2551 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2552 dprintf(fd, " className: %s\n", params.className.c_str());
2553 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2554 dprintf(fd, " }\n");
2555 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002556}
2557
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002558void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2559 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002560}
2561
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002562binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2563 bool enableReadLogs, int32_t* _aidl_return) {
2564 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2565 return binder::Status::ok();
2566}
2567
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002568FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2569 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2570}
2571
Songchun Fan3c82a302019-11-29 14:23:45 -08002572} // namespace android::incremental