blob: dde70caa797ff376093661d093425b2f8c7f585b [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 Buynytskyyaa8e95e2020-12-14 21:50:04 -0800359 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
360 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700361 }
362 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800363
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700364 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
365 for (auto&& [target, bind] : mnt.bindPoints) {
366 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
367 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
368 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
369 dprintf(fd, " kind: %s\n", toString(bind.kind));
370 }
371 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800372 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700373 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800374 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700375 dprintf(fd, "}\n");
376 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800377 for (auto&& [target, mountPairIt] : mBindsByPath) {
378 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700379 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
380 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
381 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
382 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800383 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700384 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800385}
386
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700387void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800388 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700389 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800390 }
391
392 std::vector<IfsMountPtr> mounts;
393 {
394 std::lock_guard l(mLock);
395 mounts.reserve(mMounts.size());
396 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -0700397 if (ifs->mountId == id &&
398 ifs->dataLoaderStub->params().packageName == Constants::systemPackage) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800399 mounts.push_back(ifs);
400 }
401 }
402 }
403
Alex Buynytskyy69941662020-04-11 21:40:37 -0700404 if (mounts.empty()) {
405 return;
406 }
407
Songchun Fan3c82a302019-11-29 14:23:45 -0800408 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700409 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800410 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700411 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800412 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800413 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800414}
415
416auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
417 for (;;) {
418 if (mNextId == kMaxStorageId) {
419 mNextId = 0;
420 }
421 auto id = ++mNextId;
422 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
423 if (inserted) {
424 return it;
425 }
426 }
427}
428
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800429StorageId IncrementalService::createStorage(
430 std::string_view mountPoint, content::pm::DataLoaderParamsParcel&& dataLoaderParams,
431 CreateOptions options, const DataLoaderStatusListener& statusListener,
432 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener& healthListener,
433 const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
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();
506 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800507 }
508
509 std::unique_lock l(mLock);
510 const auto mountIt = getStorageSlotLocked();
511 const auto mountId = mountIt->first;
512 l.unlock();
513
514 auto ifs =
515 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
516 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
517 // is the removal of the |ifs|.
518 firstCleanupOnFailure.release();
519
520 auto secondCleanup = [this, &l](auto itPtr) {
521 if (!l.owns_lock()) {
522 l.lock();
523 }
524 mMounts.erase(*itPtr);
525 };
526 auto secondCleanupOnFailure =
527 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
528
529 const auto storageIt = ifs->makeStorage(ifs->mountId);
530 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800531 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800532 return kInvalidStorageId;
533 }
534
535 {
536 metadata::Mount m;
537 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700538 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700539 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
540 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
541 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800542 const auto metadata = m.SerializeAsString();
543 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800544 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800545 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800546 if (auto err =
547 mIncFs->makeFile(ifs->control,
548 path::join(ifs->root, constants().mount,
549 constants().infoMdName),
550 0777, idFromMetadata(metadata),
551 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800552 LOG(ERROR) << "Saving mount metadata failed: " << -err;
553 return kInvalidStorageId;
554 }
555 }
556
557 const auto bk =
558 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800559 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
560 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800561 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800562 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800563 return kInvalidStorageId;
564 }
565
566 // Done here as well, all data structures are in good state.
567 secondCleanupOnFailure.release();
568
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800569 // DataLoader.
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700570 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
571 std::move(healthCheckParams), &healthListener);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700572 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800573
574 mountIt->second = std::move(ifs);
575 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700576
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800577 // Per Uid timeouts.
578 if (!perUidReadTimeouts.empty()) {
579 setUidReadTimeouts(mountId, perUidReadTimeouts);
580 }
581
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700582 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700583 // failed to create data loader
584 LOG(ERROR) << "initializeDataLoader() failed";
585 deleteStorage(dataLoaderStub->id());
586 return kInvalidStorageId;
587 }
588
Songchun Fan3c82a302019-11-29 14:23:45 -0800589 LOG(INFO) << "created storage " << mountId;
590 return mountId;
591}
592
593StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
594 StorageId linkedStorage,
595 IncrementalService::CreateOptions options) {
596 if (!isValidMountTarget(mountPoint)) {
597 LOG(ERROR) << "Mount point is invalid or missing";
598 return kInvalidStorageId;
599 }
600
601 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700602 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800603 if (!ifs) {
604 LOG(ERROR) << "Ifs unavailable";
605 return kInvalidStorageId;
606 }
607
608 const auto mountIt = getStorageSlotLocked();
609 const auto storageId = mountIt->first;
610 const auto storageIt = ifs->makeStorage(storageId);
611 if (storageIt == ifs->storages.end()) {
612 LOG(ERROR) << "Can't create a new storage";
613 mMounts.erase(mountIt);
614 return kInvalidStorageId;
615 }
616
617 l.unlock();
618
619 const auto bk =
620 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800621 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
622 std::string(storageIt->second.name), path::normalize(mountPoint),
623 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800624 err < 0) {
625 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700626 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
627 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800628 return kInvalidStorageId;
629 }
630
631 mountIt->second = ifs;
632 return storageId;
633}
634
635IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
636 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700637 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800638}
639
640StorageId IncrementalService::findStorageId(std::string_view path) const {
641 std::lock_guard l(mLock);
642 auto it = findStorageLocked(path);
643 if (it == mBindsByPath.end()) {
644 return kInvalidStorageId;
645 }
646 return it->second->second.storage;
647}
648
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800649void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700650 std::unique_lock l(mLock);
651 const auto ifs = getIfsLocked(storageId);
652 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800653 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700654 return;
655 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800656 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700657 return;
658 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800659 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700660 l.unlock();
661
662 const auto metadata = constants().readLogsDisabledMarkerName;
663 if (auto err = mIncFs->makeFile(ifs->control,
664 path::join(ifs->root, constants().mount,
665 constants().readLogsDisabledMarkerName),
666 0777, idFromMetadata(metadata), {})) {
667 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
668 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
669 return;
670 }
671
672 setStorageParams(storageId, /*enableReadLogs=*/false);
673}
674
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700675int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
676 const auto ifs = getIfs(storageId);
677 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700678 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700679 return -EINVAL;
680 }
681
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700682 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700683 if (enableReadLogs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800684 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700685 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
686 return -EPERM;
687 }
688
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800689 // Check loader usage stats permission and apop.
690 if (auto status = mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700691 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700692 !status.isOk()) {
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800693 LOG(ERROR) << " Permission: " << kLoaderUsageStats
694 << " check failed: " << status.toString8();
695 return fromBinderStatus(status);
696 }
697
698 // Check multiuser permission.
699 if (auto status = mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr,
700 params.packageName.c_str());
701 !status.isOk()) {
702 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
703 << " check failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700704 return fromBinderStatus(status);
705 }
706 }
707
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700708 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
709 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
710 return fromBinderStatus(status);
711 }
712
713 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700714 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700715 }
716
717 return 0;
718}
719
720binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700721 os::incremental::IncrementalFileSystemControlParcel control;
722 control.cmd.reset(dup(ifs.control.cmd()));
723 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700724 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700725 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700726 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700727 }
728
729 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800730 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
731 if (status.isOk()) {
732 // Store enabled state.
733 ifs.setReadLogsEnabled(enableReadLogs);
734 }
735 return status;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700736}
737
Songchun Fan3c82a302019-11-29 14:23:45 -0800738void IncrementalService::deleteStorage(StorageId storageId) {
739 const auto ifs = getIfs(storageId);
740 if (!ifs) {
741 return;
742 }
743 deleteStorage(*ifs);
744}
745
746void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
747 std::unique_lock l(ifs.lock);
748 deleteStorageLocked(ifs, std::move(l));
749}
750
751void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
752 std::unique_lock<std::mutex>&& ifsLock) {
753 const auto storages = std::move(ifs.storages);
754 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
755 const auto bindPoints = ifs.bindPoints;
756 ifsLock.unlock();
757
758 std::lock_guard l(mLock);
759 for (auto&& [id, _] : storages) {
760 if (id != ifs.mountId) {
761 mMounts.erase(id);
762 }
763 }
764 for (auto&& [path, _] : bindPoints) {
765 mBindsByPath.erase(path);
766 }
767 mMounts.erase(ifs.mountId);
768}
769
770StorageId IncrementalService::openStorage(std::string_view pathInMount) {
771 if (!path::isAbsolute(pathInMount)) {
772 return kInvalidStorageId;
773 }
774
775 return findStorageId(path::normalize(pathInMount));
776}
777
Songchun Fan3c82a302019-11-29 14:23:45 -0800778IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
779 std::lock_guard l(mLock);
780 return getIfsLocked(storage);
781}
782
783const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
784 auto it = mMounts.find(storage);
785 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700786 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700787 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800788 }
789 return it->second;
790}
791
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800792int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
793 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800794 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700795 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800796 return -EINVAL;
797 }
798
799 const auto ifs = getIfs(storage);
800 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700801 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800802 return -EINVAL;
803 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800804
Songchun Fan3c82a302019-11-29 14:23:45 -0800805 std::unique_lock l(ifs->lock);
806 const auto storageInfo = ifs->storages.find(storage);
807 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700808 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800809 return -EINVAL;
810 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700811 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700812 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700813 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700814 return -EINVAL;
815 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800816 l.unlock();
817 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800818 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
819 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800820}
821
822int IncrementalService::unbind(StorageId storage, std::string_view target) {
823 if (!path::isAbsolute(target)) {
824 return -EINVAL;
825 }
826
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700827 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800828
829 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
830 // otherwise there's a chance to unmount something completely unrelated
831 const auto norm = path::normalize(target);
832 std::unique_lock l(mLock);
833 const auto storageIt = mBindsByPath.find(norm);
834 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
835 return -EINVAL;
836 }
837 const auto bindIt = storageIt->second;
838 const auto storageId = bindIt->second.storage;
839 const auto ifs = getIfsLocked(storageId);
840 if (!ifs) {
841 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
842 << " is missing";
843 return -EFAULT;
844 }
845 mBindsByPath.erase(storageIt);
846 l.unlock();
847
848 mVold->unmountIncFs(bindIt->first);
849 std::unique_lock l2(ifs->lock);
850 if (ifs->bindPoints.size() <= 1) {
851 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700852 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800853 } else {
854 const std::string savedFile = std::move(bindIt->second.savedFilename);
855 ifs->bindPoints.erase(bindIt);
856 l2.unlock();
857 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800858 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800859 }
860 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700861
Songchun Fan3c82a302019-11-29 14:23:45 -0800862 return 0;
863}
864
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700865std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700866 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700867 std::string_view path) const {
868 if (!path::isAbsolute(path)) {
869 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700870 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700871 auto normPath = path::normalize(path);
872 if (path::startsWith(normPath, storageIt->second.name)) {
873 return normPath;
874 }
875 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700876 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
877 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700878 return {};
879 }
880 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700881}
882
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700883std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700884 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700885 std::unique_lock l(ifs.lock);
886 const auto storageInfo = ifs.storages.find(storage);
887 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800888 return {};
889 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700890 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800891}
892
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800893int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700894 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800895 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700896 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800897 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700898 LOG(ERROR) << "Internal error: storageId " << storage
899 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800900 return -EINVAL;
901 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700902 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700903 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800904 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800905 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700906 if (!data.empty()) {
907 if (auto err = setFileContent(ifs, id, path, data); err) {
908 return err;
909 }
910 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800911 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800912 }
913 return -EINVAL;
914}
915
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800916int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800917 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700918 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800919 if (normPath.empty()) {
920 return -EINVAL;
921 }
922 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800923 }
924 return -EINVAL;
925}
926
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800927int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800928 const auto ifs = getIfs(storageId);
929 if (!ifs) {
930 return -EINVAL;
931 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700932 return makeDirs(*ifs, storageId, path, mode);
933}
934
935int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
936 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800937 std::string normPath = normalizePathToStorage(ifs, storageId, path);
938 if (normPath.empty()) {
939 return -EINVAL;
940 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700941 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800942}
943
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800944int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
945 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700946 std::unique_lock l(mLock);
947 auto ifsSrc = getIfsLocked(sourceStorageId);
948 if (!ifsSrc) {
949 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800950 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700951 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
952 return -EINVAL;
953 }
954 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700955 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
956 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700957 if (normOldPath.empty() || normNewPath.empty()) {
958 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
959 return -EINVAL;
960 }
961 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800962}
963
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800964int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800965 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700966 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800967 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800968 }
969 return -EINVAL;
970}
971
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800972int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
973 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800974 std::string&& target, BindKind kind,
975 std::unique_lock<std::mutex>& mainLock) {
976 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700977 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800978 return -EINVAL;
979 }
980
981 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700982 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800983 if (kind != BindKind::Temporary) {
984 metadata::BindPoint bp;
985 bp.set_storage_id(storage);
986 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800987 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800988 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800989 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800990 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800991 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700992 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
993 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
994 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800995 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700996 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800997 return int(node);
998 }
999 }
1000
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001001 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1002 std::move(target), kind, mainLock);
1003 if (res) {
1004 mIncFs->unlink(ifs.control, metadataFullPath);
1005 }
1006 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001007}
1008
1009int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001010 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001011 std::string&& target, BindKind kind,
1012 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001013 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001014 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001015 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001016 if (!status.isOk()) {
1017 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1018 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1019 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1020 : status.serviceSpecificErrorCode() == 0
1021 ? -EFAULT
1022 : status.serviceSpecificErrorCode()
1023 : -EIO;
1024 }
1025 }
1026
1027 if (!mainLock.owns_lock()) {
1028 mainLock.lock();
1029 }
1030 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001031 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1032 std::move(target), kind);
1033 return 0;
1034}
1035
1036void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1037 std::string&& metadataName, std::string&& source,
1038 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001039 const auto [it, _] =
1040 ifs.bindPoints.insert_or_assign(target,
1041 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001042 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001043 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001044}
1045
1046RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1047 const auto ifs = getIfs(storage);
1048 if (!ifs) {
1049 return {};
1050 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001051 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001052 if (normPath.empty()) {
1053 return {};
1054 }
1055 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001056}
1057
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001058RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001059 const auto ifs = getIfs(storage);
1060 if (!ifs) {
1061 return {};
1062 }
1063 return mIncFs->getMetadata(ifs->control, node);
1064}
1065
Songchun Fan3c82a302019-11-29 14:23:45 -08001066bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001067 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001068 {
1069 std::unique_lock l(mLock);
1070 const auto& ifs = getIfsLocked(storage);
1071 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001072 return false;
1073 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001074 dataLoaderStub = ifs->dataLoaderStub;
1075 if (!dataLoaderStub) {
1076 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001077 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001078 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001079 dataLoaderStub->requestStart();
1080 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001081}
1082
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001083void IncrementalService::setUidReadTimeouts(
1084 StorageId storage, const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
1085 using microseconds = std::chrono::microseconds;
1086 using milliseconds = std::chrono::milliseconds;
1087
1088 auto maxPendingTimeUs = microseconds(0);
1089 for (const auto& timeouts : perUidReadTimeouts) {
1090 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1091 }
1092 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
1093 return;
1094 }
1095
1096 const auto ifs = getIfs(storage);
1097 if (!ifs) {
1098 return;
1099 }
1100
1101 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1102 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1103 return;
1104 }
1105
1106 const auto timeout = std::chrono::duration_cast<milliseconds>(maxPendingTimeUs) -
1107 Constants::perUidTimeoutOffset;
1108 updateUidReadTimeouts(storage, Clock::now() + timeout);
1109}
1110
1111void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1112 const auto ifs = getIfs(storage);
1113 if (!ifs) {
1114 return;
1115 }
1116
1117 mIncFs->setUidReadTimeouts(ifs->control, {});
1118}
1119
1120void IncrementalService::updateUidReadTimeouts(StorageId storage, Clock::time_point timeLimit) {
1121 // Reached maximum timeout.
1122 if (Clock::now() >= timeLimit) {
1123 return clearUidReadTimeouts(storage);
1124 }
1125
1126 // Still loading?
1127 const auto progress = getLoadingProgress(storage);
1128 if (progress.isError()) {
1129 // Something is wrong, abort.
1130 return clearUidReadTimeouts(storage);
1131 }
1132
1133 if (progress.started() && progress.fullyLoaded()) {
1134 // Fully loaded, check readLogs collection.
1135 const auto ifs = getIfs(storage);
1136 if (!ifs->readLogsEnabled()) {
1137 return clearUidReadTimeouts(storage);
1138 }
1139 }
1140
1141 const auto timeLeft = timeLimit - Clock::now();
1142 if (timeLeft < Constants::progressUpdateInterval) {
1143 // Don't bother.
1144 return clearUidReadTimeouts(storage);
1145 }
1146
1147 addTimedJob(*mTimedQueue, storage, Constants::progressUpdateInterval,
1148 [this, storage, timeLimit]() { updateUidReadTimeouts(storage, timeLimit); });
1149}
1150
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001151std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1152 std::unordered_set<std::string_view> mountedRootNames;
1153 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1154 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1155 for (auto [source, target] : binds) {
1156 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1157 LOG(INFO) << " " << path::join(root, source);
1158 }
1159
1160 // Ensure it's a kind of a mount that's managed by IncrementalService
1161 if (path::basename(root) != constants().mount ||
1162 path::basename(backingDir) != constants().backing) {
1163 return;
1164 }
1165 const auto expectedRoot = path::dirname(root);
1166 if (path::dirname(backingDir) != expectedRoot) {
1167 return;
1168 }
1169 if (path::dirname(expectedRoot) != mIncrementalDir) {
1170 return;
1171 }
1172 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1173 return;
1174 }
1175
1176 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1177
1178 // make sure we clean up the mount if it happens to be a bad one.
1179 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1180 auto cleanupFiles = makeCleanup([&]() {
1181 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1182 IncFsMount::cleanupFilesystem(expectedRoot);
1183 });
1184 auto cleanupMounts = makeCleanup([&]() {
1185 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1186 for (auto&& [_, target] : binds) {
1187 mVold->unmountIncFs(std::string(target));
1188 }
1189 mVold->unmountIncFs(std::string(root));
1190 });
1191
1192 auto control = mIncFs->openMount(root);
1193 if (!control) {
1194 LOG(INFO) << "failed to open mount " << root;
1195 return;
1196 }
1197
1198 auto mountRecord =
1199 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1200 path::join(root, constants().infoMdName));
1201 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1202 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1203 return;
1204 }
1205
1206 auto mountId = mountRecord.storage().id();
1207 mNextId = std::max(mNextId, mountId + 1);
1208
1209 DataLoaderParamsParcel dataLoaderParams;
1210 {
1211 const auto& loader = mountRecord.loader();
1212 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1213 dataLoaderParams.packageName = loader.package_name();
1214 dataLoaderParams.className = loader.class_name();
1215 dataLoaderParams.arguments = loader.arguments();
1216 }
1217
1218 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1219 std::move(control), *this);
1220 cleanupFiles.release(); // ifs will take care of that now
1221
Alex Buynytskyy04035452020-06-06 20:15:58 -07001222 // Check if marker file present.
1223 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001224 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001225 }
1226
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001227 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1228 auto d = openDir(root);
1229 while (auto e = ::readdir(d.get())) {
1230 if (e->d_type == DT_REG) {
1231 auto name = std::string_view(e->d_name);
1232 if (name.starts_with(constants().mountpointMdPrefix)) {
1233 permanentBindPoints
1234 .emplace_back(name,
1235 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1236 ifs->control,
1237 path::join(root,
1238 name)));
1239 if (permanentBindPoints.back().second.dest_path().empty() ||
1240 permanentBindPoints.back().second.source_subdir().empty()) {
1241 permanentBindPoints.pop_back();
1242 mIncFs->unlink(ifs->control, path::join(root, name));
1243 } else {
1244 LOG(INFO) << "Permanent bind record: '"
1245 << permanentBindPoints.back().second.source_subdir() << "'->'"
1246 << permanentBindPoints.back().second.dest_path() << "'";
1247 }
1248 }
1249 } else if (e->d_type == DT_DIR) {
1250 if (e->d_name == "."sv || e->d_name == ".."sv) {
1251 continue;
1252 }
1253 auto name = std::string_view(e->d_name);
1254 if (name.starts_with(constants().storagePrefix)) {
1255 int storageId;
1256 const auto res =
1257 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1258 name.data() + name.size(), storageId);
1259 if (res.ec != std::errc{} || *res.ptr != '_') {
1260 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1261 << "' for mount " << expectedRoot;
1262 continue;
1263 }
1264 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1265 if (!inserted) {
1266 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1267 << " for mount " << expectedRoot;
1268 continue;
1269 }
1270 ifs->storages.insert_or_assign(storageId,
1271 IncFsMount::Storage{path::join(root, name)});
1272 mNextId = std::max(mNextId, storageId + 1);
1273 }
1274 }
1275 }
1276
1277 if (ifs->storages.empty()) {
1278 LOG(WARNING) << "No valid storages in mount " << root;
1279 return;
1280 }
1281
1282 // now match the mounted directories with what we expect to have in the metadata
1283 {
1284 std::unique_lock l(mLock, std::defer_lock);
1285 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1286 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1287 [&, bindRecord = bindRecord](auto&& bind) {
1288 return bind.second == bindRecord.dest_path() &&
1289 path::join(root, bind.first) ==
1290 bindRecord.source_subdir();
1291 });
1292 if (mountedIt != binds.end()) {
1293 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1294 << " to mount " << mountedIt->first;
1295 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1296 std::move(*bindRecord.mutable_source_subdir()),
1297 std::move(*bindRecord.mutable_dest_path()),
1298 BindKind::Permanent);
1299 if (mountedIt != binds.end() - 1) {
1300 std::iter_swap(mountedIt, binds.end() - 1);
1301 }
1302 binds = binds.first(binds.size() - 1);
1303 } else {
1304 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1305 << ", mounting";
1306 // doesn't exist - try mounting back
1307 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1308 std::move(*bindRecord.mutable_source_subdir()),
1309 std::move(*bindRecord.mutable_dest_path()),
1310 BindKind::Permanent, l)) {
1311 mIncFs->unlink(ifs->control, metadataFile);
1312 }
1313 }
1314 }
1315 }
1316
1317 // if anything stays in |binds| those are probably temporary binds; system restarted since
1318 // they were mounted - so let's unmount them all.
1319 for (auto&& [source, target] : binds) {
1320 if (source.empty()) {
1321 continue;
1322 }
1323 mVold->unmountIncFs(std::string(target));
1324 }
1325 cleanupMounts.release(); // ifs now manages everything
1326
1327 if (ifs->bindPoints.empty()) {
1328 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1329 deleteStorage(*ifs);
1330 return;
1331 }
1332
1333 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1334 CHECK(ifs->dataLoaderStub);
1335
1336 mountedRootNames.insert(path::basename(ifs->root));
1337
1338 // not locking here at all: we're still in the constructor, no other calls can happen
1339 mMounts[ifs->mountId] = std::move(ifs);
1340 });
1341
1342 return mountedRootNames;
1343}
1344
1345void IncrementalService::mountExistingImages(
1346 const std::unordered_set<std::string_view>& mountedRootNames) {
1347 auto dir = openDir(mIncrementalDir);
1348 if (!dir) {
1349 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1350 return;
1351 }
1352 while (auto entry = ::readdir(dir.get())) {
1353 if (entry->d_type != DT_DIR) {
1354 continue;
1355 }
1356 std::string_view name = entry->d_name;
1357 if (!name.starts_with(constants().mountKeyPrefix)) {
1358 continue;
1359 }
1360 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001361 continue;
1362 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001363 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001364 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001365 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001366 }
1367 }
1368}
1369
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001370bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001371 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001372 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001373
Songchun Fan3c82a302019-11-29 14:23:45 -08001374 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001375 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001376 if (!status.isOk()) {
1377 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1378 return false;
1379 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001380
1381 int cmd = controlParcel.cmd.release().release();
1382 int pendingReads = controlParcel.pendingReads.release().release();
1383 int logs = controlParcel.log.release().release();
1384 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001385
1386 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1387
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001388 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1389 path::join(mountTarget, constants().infoMdName));
1390 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001391 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1392 return false;
1393 }
1394
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001395 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001396 mNextId = std::max(mNextId, ifs->mountId + 1);
1397
Alex Buynytskyy04035452020-06-06 20:15:58 -07001398 // Check if marker file present.
1399 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001400 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001401 }
1402
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001403 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001404 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001405 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001406 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001407 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001408 dataLoaderParams.packageName = loader.package_name();
1409 dataLoaderParams.className = loader.class_name();
1410 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001411 }
1412
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001413 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001414 CHECK(ifs->dataLoaderStub);
1415
Songchun Fan3c82a302019-11-29 14:23:45 -08001416 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001417 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001418 while (auto e = ::readdir(d.get())) {
1419 if (e->d_type == DT_REG) {
1420 auto name = std::string_view(e->d_name);
1421 if (name.starts_with(constants().mountpointMdPrefix)) {
1422 bindPoints.emplace_back(name,
1423 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1424 ifs->control,
1425 path::join(mountTarget,
1426 name)));
1427 if (bindPoints.back().second.dest_path().empty() ||
1428 bindPoints.back().second.source_subdir().empty()) {
1429 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001430 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001431 }
1432 }
1433 } else if (e->d_type == DT_DIR) {
1434 if (e->d_name == "."sv || e->d_name == ".."sv) {
1435 continue;
1436 }
1437 auto name = std::string_view(e->d_name);
1438 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001439 int storageId;
1440 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1441 name.data() + name.size(), storageId);
1442 if (res.ec != std::errc{} || *res.ptr != '_') {
1443 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1444 << root;
1445 continue;
1446 }
1447 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001448 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001449 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001450 << " for mount " << root;
1451 continue;
1452 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001453 ifs->storages.insert_or_assign(storageId,
1454 IncFsMount::Storage{
1455 path::join(root, constants().mount, name)});
1456 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001457 }
1458 }
1459 }
1460
1461 if (ifs->storages.empty()) {
1462 LOG(WARNING) << "No valid storages in mount " << root;
1463 return false;
1464 }
1465
1466 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001467 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001468 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001469 for (auto&& bp : bindPoints) {
1470 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1471 std::move(*bp.second.mutable_source_subdir()),
1472 std::move(*bp.second.mutable_dest_path()),
1473 BindKind::Permanent, l);
1474 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001475 }
1476
1477 if (bindCount == 0) {
1478 LOG(WARNING) << "No valid bind points for mount " << root;
1479 deleteStorage(*ifs);
1480 return false;
1481 }
1482
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001483 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001484 mMounts[ifs->mountId] = std::move(ifs);
1485 return true;
1486}
1487
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001488void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001489 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001490 while (mRunning.load(std::memory_order_relaxed)) {
1491 mLooper->pollAll(kTimeoutMsecs);
1492 }
1493}
1494
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001495IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001496 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001497 const DataLoaderStatusListener* statusListener,
1498 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001499 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001500 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1501 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001502 return ifs.dataLoaderStub;
1503}
1504
1505void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001506 const DataLoaderStatusListener* statusListener,
1507 StorageHealthCheckParams&& healthCheckParams,
1508 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001509 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001510 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001511 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001512 }
1513
Songchun Fan3c82a302019-11-29 14:23:45 -08001514 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001515 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001516 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1517 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1518 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001519 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001520
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001521 ifs.dataLoaderStub =
1522 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001523 statusListener, std::move(healthCheckParams), healthListener,
1524 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001525}
1526
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001527template <class Duration>
1528static long elapsedMcs(Duration start, Duration end) {
1529 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1530}
1531
1532// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001533// Lib files should be placed next to the APK file in the following matter:
1534// Example:
1535// /path/to/base.apk
1536// /path/to/lib/arm/first.so
1537// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001538bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1539 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001540 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001541 auto start = Clock::now();
1542
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001543 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001544 if (!ifs) {
1545 LOG(ERROR) << "Invalid storage " << storage;
1546 return false;
1547 }
1548
Songchun Fanc8975312020-07-13 12:14:37 -07001549 const auto targetLibPathRelativeToStorage =
1550 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1551 libDirRelativePath);
1552
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001553 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001554 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1555 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001556 << " errno: " << res;
1557 return false;
1558 }
1559
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001560 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001561 ZipArchiveHandle zipFileHandle;
1562 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001563 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1564 return false;
1565 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001566
1567 // Need a shared pointer: will be passing it into all unpacking jobs.
1568 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001569 void* cookie = nullptr;
Songchun Fan2ff2a482020-09-29 11:45:18 -07001570 const auto libFilePrefix = path::join(constants().libDir, abi) + "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001571 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001572 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1573 return false;
1574 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001575 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001576 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1577
1578 auto openZipTs = Clock::now();
1579
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001580 std::vector<Job> jobQueue;
1581 ZipEntry entry;
1582 std::string_view fileName;
1583 while (!Next(cookie, &entry, &fileName)) {
1584 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001585 continue;
1586 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001587
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001588 if (!extractNativeLibs) {
1589 // ensure the file is properly aligned and unpacked
1590 if (entry.method != kCompressStored) {
1591 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1592 return false;
1593 }
1594 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1595 LOG(WARNING) << "Library " << fileName
1596 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1597 << entry.offset;
1598 return false;
1599 }
1600 continue;
1601 }
1602
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001603 auto startFileTs = Clock::now();
1604
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001605 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001606 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001607 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001608 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001609 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001610 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001611 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1612 << "; skipping extraction, spent "
1613 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1614 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001615 continue;
1616 }
1617
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001618 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001619 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001620 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001621 .signature = {},
1622 // Metadata of the new lib file is its relative path
1623 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1624 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001625 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001626 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1627 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001628 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001629 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001630 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001631 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001632
1633 auto makeFileTs = Clock::now();
1634
Songchun Fanafaf6e92020-03-18 14:12:20 -07001635 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001636 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001637 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001638 LOG(INFO) << "incfs: Extracted " << libName
1639 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001640 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001641 continue;
1642 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001643
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001644 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1645 libFileId, libPath = std::move(targetLibPath),
1646 makeFileTs]() mutable {
1647 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001648 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001649
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001650 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001651 auto prepareJobTs = Clock::now();
1652 LOG(INFO) << "incfs: Processed " << libName << ": "
1653 << elapsedMcs(startFileTs, prepareJobTs)
1654 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1655 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001656 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001657 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001658
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001659 auto processedTs = Clock::now();
1660
1661 if (!jobQueue.empty()) {
1662 {
1663 std::lock_guard lock(mJobMutex);
1664 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001665 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001666 if (existingJobs.empty()) {
1667 existingJobs = std::move(jobQueue);
1668 } else {
1669 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1670 std::move_iterator(jobQueue.end()));
1671 }
1672 }
1673 }
1674 mJobCondition.notify_all();
1675 }
1676
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001677 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001678 auto end = Clock::now();
1679 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1680 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1681 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001682 << " make files: " << elapsedMcs(openZipTs, processedTs)
1683 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001684 }
1685
1686 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001687}
1688
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001689void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1690 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001691 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001692 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001693 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001694 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001695 return;
1696 }
1697
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001698 auto startedTs = Clock::now();
1699
1700 // Write extracted data to new file
1701 // NOTE: don't zero-initialize memory, it may take a while for nothing
1702 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1703 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001704 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001705 return;
1706 }
1707
1708 auto extractFileTs = Clock::now();
1709
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001710 if (setFileContent(ifs, libFileId, debugLibPath,
1711 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001712 return;
1713 }
1714
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001715 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001716 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001717 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1718 << entry.compressed_length << " -> " << entry.uncompressed_length
1719 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001720 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1721 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001722 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001723 }
1724}
1725
1726bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001727 struct WaitPrinter {
1728 const Clock::time_point startTs = Clock::now();
1729 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001730 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001731 const auto endTs = Clock::now();
1732 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1733 << elapsedMcs(startTs, endTs) << "mcs";
1734 }
1735 }
1736 } waitPrinter;
1737
1738 MountId mount;
1739 {
1740 auto ifs = getIfs(storage);
1741 if (!ifs) {
1742 return true;
1743 }
1744 mount = ifs->mountId;
1745 }
1746
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001747 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001748 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001749 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001750 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001751 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001752 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001753}
1754
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001755int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1756 std::string_view debugFilePath,
1757 std::span<const uint8_t> data) const {
1758 auto startTs = Clock::now();
1759
1760 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1761 if (!writeFd.ok()) {
1762 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1763 << " errno: " << writeFd.get();
1764 return writeFd.get();
1765 }
1766
1767 const auto dataLength = data.size();
1768
1769 auto openFileTs = Clock::now();
1770 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1771 std::vector<IncFsDataBlock> instructions(numBlocks);
1772 for (int i = 0; i < numBlocks; i++) {
1773 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1774 instructions[i] = IncFsDataBlock{
1775 .fileFd = writeFd.get(),
1776 .pageIndex = static_cast<IncFsBlockIndex>(i),
1777 .compression = INCFS_COMPRESSION_KIND_NONE,
1778 .kind = INCFS_BLOCK_KIND_DATA,
1779 .dataSize = static_cast<uint32_t>(blockSize),
1780 .data = reinterpret_cast<const char*>(data.data()),
1781 };
1782 data = data.subspan(blockSize);
1783 }
1784 auto prepareInstsTs = Clock::now();
1785
1786 size_t res = mIncFs->writeBlocks(instructions);
1787 if (res != instructions.size()) {
1788 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1789 return res;
1790 }
1791
1792 if (perfLoggingEnabled()) {
1793 auto endTs = Clock::now();
1794 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1795 << " bytes): " << elapsedMcs(startTs, endTs)
1796 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1797 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1798 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1799 }
1800
1801 return 0;
1802}
1803
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001804int IncrementalService::isFileFullyLoaded(StorageId storage, std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001805 std::unique_lock l(mLock);
1806 const auto ifs = getIfsLocked(storage);
1807 if (!ifs) {
1808 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1809 return -EINVAL;
1810 }
1811 const auto storageInfo = ifs->storages.find(storage);
1812 if (storageInfo == ifs->storages.end()) {
1813 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1814 return -EINVAL;
1815 }
1816 l.unlock();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001817 return isFileFullyLoadedFromPath(*ifs, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001818}
1819
1820int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1821 std::string_view filePath) const {
1822 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1823 if (filledBlocks < 0) {
1824 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1825 << filePath << " errno: " << filledBlocks;
1826 return filledBlocks;
1827 }
1828 if (totalBlocks < filledBlocks) {
1829 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1830 return -EINVAL;
1831 }
1832 return totalBlocks - filledBlocks;
1833}
1834
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001835IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
1836 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07001837 std::unique_lock l(mLock);
1838 const auto ifs = getIfsLocked(storage);
1839 if (!ifs) {
1840 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001841 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001842 }
1843 const auto storageInfo = ifs->storages.find(storage);
1844 if (storageInfo == ifs->storages.end()) {
1845 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001846 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001847 }
1848 l.unlock();
1849 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
1850}
1851
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001852IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
1853 const IncFsMount& ifs, std::string_view storagePath) const {
1854 ssize_t totalBlocks = 0, filledBlocks = 0;
Songchun Fan374f7652020-08-20 08:40:29 -07001855 const auto filePaths = mFs->listFilesRecursive(storagePath);
1856 for (const auto& filePath : filePaths) {
1857 const auto [filledBlocksCount, totalBlocksCount] =
1858 mIncFs->countFilledBlocks(ifs.control, filePath);
1859 if (filledBlocksCount < 0) {
1860 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1861 << " errno: " << filledBlocksCount;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001862 return {filledBlocksCount, filledBlocksCount};
Songchun Fan374f7652020-08-20 08:40:29 -07001863 }
1864 totalBlocks += totalBlocksCount;
1865 filledBlocks += filledBlocksCount;
1866 }
1867
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001868 return {filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07001869}
1870
Songchun Fana7098592020-09-03 11:45:53 -07001871bool IncrementalService::updateLoadingProgress(
1872 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1873 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001874 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07001875 // Failed to get progress from incfs, abort.
1876 return false;
1877 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001878 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
1879 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07001880 // Stop updating progress once it is fully loaded
1881 return true;
1882 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001883 addTimedJob(*mProgressUpdateJobQueue, storage,
1884 Constants::progressUpdateInterval /* repeat after 1s */,
Songchun Fana7098592020-09-03 11:45:53 -07001885 [storage, progressListener, this]() {
1886 updateLoadingProgress(storage, progressListener);
1887 });
1888 return true;
1889}
1890
1891bool IncrementalService::registerLoadingProgressListener(
1892 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1893 return updateLoadingProgress(storage, progressListener);
1894}
1895
1896bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
1897 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
1898}
1899
Songchun Fan2570ec02020-10-08 17:22:33 -07001900bool IncrementalService::registerStorageHealthListener(
1901 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
1902 const StorageHealthListener& healthListener) {
1903 DataLoaderStubPtr dataLoaderStub;
1904 {
1905 std::unique_lock l(mLock);
1906 const auto& ifs = getIfsLocked(storage);
1907 if (!ifs) {
1908 return false;
1909 }
1910 dataLoaderStub = ifs->dataLoaderStub;
1911 if (!dataLoaderStub) {
1912 return false;
1913 }
1914 }
1915 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
1916 return true;
1917}
1918
1919void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
1920 StorageHealthCheckParams invalidCheckParams;
1921 invalidCheckParams.blockedTimeoutMs = -1;
1922 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
1923}
1924
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001925bool IncrementalService::perfLoggingEnabled() {
1926 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1927 return enabled;
1928}
1929
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001930void IncrementalService::runJobProcessing() {
1931 for (;;) {
1932 std::unique_lock lock(mJobMutex);
1933 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1934 if (!mRunning) {
1935 return;
1936 }
1937
1938 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001939 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001940 auto queue = std::move(it->second);
1941 mJobQueue.erase(it);
1942 lock.unlock();
1943
1944 for (auto&& job : queue) {
1945 job();
1946 }
1947
1948 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001949 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001950 lock.unlock();
1951 mJobCondition.notify_all();
1952 }
1953}
1954
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001955void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001956 sp<IAppOpsCallback> listener;
1957 {
1958 std::unique_lock lock{mCallbacksLock};
1959 auto& cb = mCallbackRegistered[packageName];
1960 if (cb) {
1961 return;
1962 }
1963 cb = new AppOpsListener(*this, packageName);
1964 listener = cb;
1965 }
1966
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001967 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1968 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001969}
1970
1971bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1972 sp<IAppOpsCallback> listener;
1973 {
1974 std::unique_lock lock{mCallbacksLock};
1975 auto found = mCallbackRegistered.find(packageName);
1976 if (found == mCallbackRegistered.end()) {
1977 return false;
1978 }
1979 listener = found->second;
1980 mCallbackRegistered.erase(found);
1981 }
1982
1983 mAppOpsManager->stopWatchingMode(listener);
1984 return true;
1985}
1986
1987void IncrementalService::onAppOpChanged(const std::string& packageName) {
1988 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001989 return;
1990 }
1991
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001992 std::vector<IfsMountPtr> affected;
1993 {
1994 std::lock_guard l(mLock);
1995 affected.reserve(mMounts.size());
1996 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001997 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001998 affected.push_back(ifs);
1999 }
2000 }
2001 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002002 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002003 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002004 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002005}
2006
Songchun Fana7098592020-09-03 11:45:53 -07002007bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2008 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002009 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002010 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002011 }
Songchun Fana7098592020-09-03 11:45:53 -07002012 timedQueue.addJob(id, after, std::move(what));
2013 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002014}
2015
Songchun Fana7098592020-09-03 11:45:53 -07002016bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002017 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002018 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002019 }
Songchun Fana7098592020-09-03 11:45:53 -07002020 timedQueue.removeJobs(id);
2021 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002022}
2023
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002024IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
2025 DataLoaderParamsParcel&& params,
2026 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002027 const DataLoaderStatusListener* statusListener,
2028 StorageHealthCheckParams&& healthCheckParams,
2029 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002030 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002031 : mService(service),
2032 mId(id),
2033 mParams(std::move(params)),
2034 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002035 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
2036 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002037 mHealthPath(std::move(healthPath)),
2038 mHealthCheckParams(std::move(healthCheckParams)) {
2039 if (mHealthListener) {
2040 if (!isHealthParamsValid()) {
2041 mHealthListener = {};
2042 }
2043 } else {
2044 // Disable advanced health check statuses.
2045 mHealthCheckParams.blockedTimeoutMs = -1;
2046 }
2047 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002048}
2049
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002050IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002051 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002052 cleanupResources();
2053 }
2054}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002055
2056void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002057 auto now = Clock::now();
2058 {
2059 std::unique_lock lock(mMutex);
2060 mHealthPath.clear();
2061 unregisterFromPendingReads();
2062 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002063 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002064 }
2065
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002066 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002067
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002068 {
2069 std::unique_lock lock(mMutex);
2070 mParams = {};
2071 mControl = {};
2072 mHealthControl = {};
2073 mHealthListener = {};
2074 mStatusCondition.wait_until(lock, now + 60s, [this] {
2075 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2076 });
2077 mStatusListener = {};
2078 mId = kInvalidStorageId;
2079 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002080}
2081
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002082sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2083 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002084 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002085 if (!status.isOk()) {
2086 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2087 return {};
2088 }
2089 if (!dataloader) {
2090 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2091 return {};
2092 }
2093 return dataloader;
2094}
2095
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002096bool IncrementalService::DataLoaderStub::requestCreate() {
2097 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2098}
2099
2100bool IncrementalService::DataLoaderStub::requestStart() {
2101 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2102}
2103
2104bool IncrementalService::DataLoaderStub::requestDestroy() {
2105 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2106}
2107
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002108bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002109 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002110 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002111 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002112 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002113 return fsmStep();
2114}
2115
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002116void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002117 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002118 mTargetStatus = status;
2119 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002120 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002121 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002122}
2123
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002124bool IncrementalService::DataLoaderStub::bind() {
2125 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002126 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002127 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002128 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002129 return false;
2130 }
2131 return true;
2132}
2133
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002134bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002135 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002136 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002137 return false;
2138 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002139 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002140 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002141 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002142 return false;
2143 }
2144 return true;
2145}
2146
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002147bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002148 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002149 if (!dataloader) {
2150 return false;
2151 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002152 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002153 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002154 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002155 return false;
2156 }
2157 return true;
2158}
2159
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002160bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002161 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002162}
2163
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002164bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002165 if (!isValid()) {
2166 return false;
2167 }
2168
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002169 int currentStatus;
2170 int targetStatus;
2171 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002172 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002173 currentStatus = mCurrentStatus;
2174 targetStatus = mTargetStatus;
2175 }
2176
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002177 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002178
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002179 if (currentStatus == targetStatus) {
2180 return true;
2181 }
2182
2183 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002184 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2185 // Do nothing, this is a reset state.
2186 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002187 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
2188 return destroy();
2189 }
2190 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2191 switch (currentStatus) {
2192 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2193 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2194 return start();
2195 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002196 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002197 }
2198 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2199 switch (currentStatus) {
2200 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002201 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002202 return bind();
2203 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002204 return create();
2205 }
2206 break;
2207 default:
2208 LOG(ERROR) << "Invalid target status: " << targetStatus
2209 << ", current status: " << currentStatus;
2210 break;
2211 }
2212 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002213}
2214
2215binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002216 if (!isValid()) {
2217 return binder::Status::
2218 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2219 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002220 if (id() != mountId) {
2221 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002222 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2223 }
2224
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002225 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002226 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002227 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002228 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002229 if (mCurrentStatus == newStatus) {
2230 return binder::Status::ok();
2231 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002232
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002233 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002234 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002235 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002236
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002237 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002238
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002239 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002240 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2241 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002242 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002243 }
2244
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002245 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002246 << newStatus << " (target " << targetStatus << ")";
2247
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002248 if (listener) {
2249 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002250 }
2251
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002252 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002253
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002254 mStatusCondition.notify_all();
2255
Songchun Fan3c82a302019-11-29 14:23:45 -08002256 return binder::Status::ok();
2257}
2258
Songchun Fan33093982020-09-10 13:12:39 -07002259binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2260 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002261 if (!isValid()) {
2262 return binder::Status::
2263 fromServiceSpecificError(-EINVAL,
2264 "reportStreamHealth came to invalid DataLoaderStub");
2265 }
2266 if (id() != mountId) {
2267 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
2268 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2269 }
2270 {
2271 std::lock_guard lock(mMutex);
2272 mStreamStatus = newStatus;
2273 }
Songchun Fan33093982020-09-10 13:12:39 -07002274 return binder::Status::ok();
2275}
2276
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002277bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2278 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2279 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002280}
2281
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002282void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2283 int healthStatus) {
2284 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2285 if (healthListener) {
2286 healthListener->onHealthStatus(id(), healthStatus);
2287 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002288}
2289
Songchun Fan2570ec02020-10-08 17:22:33 -07002290static int adjustHealthStatus(int healthStatus, int streamStatus) {
2291 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2292 // everything is good; no need to change status
2293 return healthStatus;
2294 }
2295 int newHeathStatus = healthStatus;
2296 switch (streamStatus) {
2297 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2298 // storage is limited and storage not healthy
2299 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2300 break;
2301 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2302 // fall through
2303 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2304 // fall through
2305 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2306 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2307 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2308 }
2309 // pending/blocked status due to transportation issues is not regarded as unhealthy
2310 break;
2311 default:
2312 break;
2313 }
2314 return newHeathStatus;
2315}
2316
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002317void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2318 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002319
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002320 int healthStatusToReport = -1;
2321 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002322
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002323 {
2324 std::unique_lock lock(mMutex);
2325 unregisterFromPendingReads();
2326
2327 healthListener = mHealthListener;
2328
2329 // Healthcheck depends on timestamp of the oldest pending read.
2330 // 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 -07002331 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2332 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002333 const auto now = Clock::now();
2334 const auto kernelTsUs = getOldestPendingReadTs();
2335 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002336 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2337 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002338 mHealthBase = {now, kernelTsUs};
2339 }
2340
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002341 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2342 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002343 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2344 registerForPendingReads();
2345 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2346 lock.unlock();
2347 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002348 return;
2349 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002350
2351 resetHealthControl();
2352
2353 // Always make sure the data loader is started.
2354 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2355
2356 // Skip any further processing if health check params are invalid.
2357 if (!isHealthParamsValid()) {
2358 LOG(DEBUG) << id()
2359 << ": Skip any further processing if health check params are invalid.";
2360 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2361 lock.unlock();
2362 onHealthStatus(healthListener, healthStatusToReport);
2363 // Triggering data loader start. This is a one-time action.
2364 fsmStep();
2365 return;
2366 }
2367
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002368 // Don't schedule timer job less than 500ms in advance.
2369 static constexpr auto kTolerance = 500ms;
2370
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002371 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2372 const auto unhealthyTimeout =
2373 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2374 const auto unhealthyMonitoring =
2375 std::max(1000ms,
2376 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2377
2378 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2379 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002380 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002381
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002382 Milliseconds checkBackAfter;
2383 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002384 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002385 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002386 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002387 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002388 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002389 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002390 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2391 } else {
2392 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002393 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002394 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2395 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002396 // Adjust health status based on stream status
2397 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002398 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002399 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002400 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2401 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002402 }
2403
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002404 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002405 if (healthStatusToReport != -1) {
2406 onHealthStatus(healthListener, healthStatusToReport);
2407 }
2408
2409 fsmStep();
2410}
2411
2412const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2413 if (mHealthPath.empty()) {
2414 resetHealthControl();
2415 return mHealthControl;
2416 }
2417 if (mHealthControl.pendingReads() < 0) {
2418 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2419 }
2420 if (mHealthControl.pendingReads() < 0) {
2421 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2422 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2423 << mHealthControl.logs() << ")";
2424 }
2425 return mHealthControl;
2426}
2427
2428void IncrementalService::DataLoaderStub::resetHealthControl() {
2429 mHealthControl = {};
2430}
2431
2432BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2433 auto result = kMaxBootClockTsUs;
2434
2435 const auto& control = initializeHealthControl();
2436 if (control.pendingReads() < 0) {
2437 return result;
2438 }
2439
Songchun Fan6944f1e2020-11-06 15:24:24 -08002440 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002441 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002442 mLastPendingReads.empty()) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002443 return result;
2444 }
2445
2446 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002447 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002448
Songchun Fan6944f1e2020-11-06 15:24:24 -08002449 for (auto&& pendingRead : mLastPendingReads) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002450 result = std::min(result, pendingRead.bootClockTsUs);
2451 }
2452 return result;
2453}
2454
2455void IncrementalService::DataLoaderStub::registerForPendingReads() {
2456 const auto pendingReadsFd = mHealthControl.pendingReads();
2457 if (pendingReadsFd < 0) {
2458 return;
2459 }
2460
2461 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2462
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002463 mService.mLooper->addFd(
2464 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2465 [](int, int, void* data) -> int {
2466 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002467 self->updateHealthStatus(/*baseline=*/true);
2468 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002469 },
2470 this);
2471 mService.mLooper->wake();
2472}
2473
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002474void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002475 const auto pendingReadsFd = mHealthControl.pendingReads();
2476 if (pendingReadsFd < 0) {
2477 return;
2478 }
2479
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002480 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2481
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002482 mService.mLooper->removeFd(pendingReadsFd);
2483 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002484}
2485
Songchun Fan2570ec02020-10-08 17:22:33 -07002486void IncrementalService::DataLoaderStub::setHealthListener(
2487 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2488 std::lock_guard lock(mMutex);
2489 mHealthCheckParams = std::move(healthCheckParams);
2490 if (healthListener == nullptr) {
2491 // reset listener and params
2492 mHealthListener = {};
2493 } else {
2494 mHealthListener = *healthListener;
2495 }
2496}
2497
Songchun Fan6944f1e2020-11-06 15:24:24 -08002498static std::string toHexString(const RawMetadata& metadata) {
2499 int n = metadata.size();
2500 std::string res(n * 2, '\0');
2501 // Same as incfs::toString(fileId)
2502 static constexpr char kHexChar[] = "0123456789abcdef";
2503 for (int i = 0; i < n; ++i) {
2504 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2505 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2506 }
2507 return res;
2508}
2509
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002510void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002511 dprintf(fd, " dataLoader: {\n");
2512 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2513 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2514 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002515 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002516 dprintf(fd, " health: {\n");
2517 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2518 dprintf(fd, " base: %lldmcs (%lld)\n",
2519 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2520 (long long)mHealthBase.kernelTsUs);
2521 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2522 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2523 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2524 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002525 dprintf(fd, " lastPendingReads: \n");
2526 const auto control = mService.mIncFs->openMount(mHealthPath);
2527 for (auto&& pendingRead : mLastPendingReads) {
2528 dprintf(fd, " fileId: %s\n", mService.mIncFs->toString(pendingRead.id).c_str());
2529 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2530 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2531 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2532 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2533 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002534 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002535 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002536 dprintf(fd, " dataLoaderParams: {\n");
2537 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2538 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2539 dprintf(fd, " className: %s\n", params.className.c_str());
2540 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2541 dprintf(fd, " }\n");
2542 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002543}
2544
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002545void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2546 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002547}
2548
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002549binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2550 bool enableReadLogs, int32_t* _aidl_return) {
2551 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2552 return binder::Status::ok();
2553}
2554
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002555FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2556 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2557}
2558
Songchun Fan3c82a302019-11-29 14:23:45 -08002559} // namespace android::incremental