blob: c9c5489a50df59560741c1c0121305d8a812fd49 [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();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800506 int blocksWritten =
507 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
508 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800509 }
510
511 std::unique_lock l(mLock);
512 const auto mountIt = getStorageSlotLocked();
513 const auto mountId = mountIt->first;
514 l.unlock();
515
516 auto ifs =
517 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
518 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
519 // is the removal of the |ifs|.
520 firstCleanupOnFailure.release();
521
522 auto secondCleanup = [this, &l](auto itPtr) {
523 if (!l.owns_lock()) {
524 l.lock();
525 }
526 mMounts.erase(*itPtr);
527 };
528 auto secondCleanupOnFailure =
529 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
530
531 const auto storageIt = ifs->makeStorage(ifs->mountId);
532 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800533 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800534 return kInvalidStorageId;
535 }
536
537 {
538 metadata::Mount m;
539 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700540 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700541 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
542 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
543 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800544 const auto metadata = m.SerializeAsString();
545 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800546 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800547 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800548 if (auto err =
549 mIncFs->makeFile(ifs->control,
550 path::join(ifs->root, constants().mount,
551 constants().infoMdName),
552 0777, idFromMetadata(metadata),
553 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800554 LOG(ERROR) << "Saving mount metadata failed: " << -err;
555 return kInvalidStorageId;
556 }
557 }
558
559 const auto bk =
560 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800561 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
562 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800563 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800564 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800565 return kInvalidStorageId;
566 }
567
568 // Done here as well, all data structures are in good state.
569 secondCleanupOnFailure.release();
570
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800571 // DataLoader.
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700572 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
573 std::move(healthCheckParams), &healthListener);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700574 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800575
576 mountIt->second = std::move(ifs);
577 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700578
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800579 // Per Uid timeouts.
580 if (!perUidReadTimeouts.empty()) {
581 setUidReadTimeouts(mountId, perUidReadTimeouts);
582 }
583
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700584 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700585 // failed to create data loader
586 LOG(ERROR) << "initializeDataLoader() failed";
587 deleteStorage(dataLoaderStub->id());
588 return kInvalidStorageId;
589 }
590
Songchun Fan3c82a302019-11-29 14:23:45 -0800591 LOG(INFO) << "created storage " << mountId;
592 return mountId;
593}
594
595StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
596 StorageId linkedStorage,
597 IncrementalService::CreateOptions options) {
598 if (!isValidMountTarget(mountPoint)) {
599 LOG(ERROR) << "Mount point is invalid or missing";
600 return kInvalidStorageId;
601 }
602
603 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700604 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800605 if (!ifs) {
606 LOG(ERROR) << "Ifs unavailable";
607 return kInvalidStorageId;
608 }
609
610 const auto mountIt = getStorageSlotLocked();
611 const auto storageId = mountIt->first;
612 const auto storageIt = ifs->makeStorage(storageId);
613 if (storageIt == ifs->storages.end()) {
614 LOG(ERROR) << "Can't create a new storage";
615 mMounts.erase(mountIt);
616 return kInvalidStorageId;
617 }
618
619 l.unlock();
620
621 const auto bk =
622 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800623 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
624 std::string(storageIt->second.name), path::normalize(mountPoint),
625 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800626 err < 0) {
627 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700628 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
629 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800630 return kInvalidStorageId;
631 }
632
633 mountIt->second = ifs;
634 return storageId;
635}
636
637IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
638 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700639 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800640}
641
642StorageId IncrementalService::findStorageId(std::string_view path) const {
643 std::lock_guard l(mLock);
644 auto it = findStorageLocked(path);
645 if (it == mBindsByPath.end()) {
646 return kInvalidStorageId;
647 }
648 return it->second->second.storage;
649}
650
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800651void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700652 std::unique_lock l(mLock);
653 const auto ifs = getIfsLocked(storageId);
654 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800655 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700656 return;
657 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800658 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700659 return;
660 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800661 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700662 l.unlock();
663
664 const auto metadata = constants().readLogsDisabledMarkerName;
665 if (auto err = mIncFs->makeFile(ifs->control,
666 path::join(ifs->root, constants().mount,
667 constants().readLogsDisabledMarkerName),
668 0777, idFromMetadata(metadata), {})) {
669 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
670 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
671 return;
672 }
673
674 setStorageParams(storageId, /*enableReadLogs=*/false);
675}
676
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700677int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
678 const auto ifs = getIfs(storageId);
679 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700680 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700681 return -EINVAL;
682 }
683
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700684 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700685 if (enableReadLogs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800686 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700687 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
688 return -EPERM;
689 }
690
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800691 // Check loader usage stats permission and apop.
692 if (auto status = mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700693 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700694 !status.isOk()) {
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800695 LOG(ERROR) << " Permission: " << kLoaderUsageStats
696 << " check failed: " << status.toString8();
697 return fromBinderStatus(status);
698 }
699
700 // Check multiuser permission.
701 if (auto status = mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr,
702 params.packageName.c_str());
703 !status.isOk()) {
704 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
705 << " check failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700706 return fromBinderStatus(status);
707 }
708 }
709
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700710 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
711 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
712 return fromBinderStatus(status);
713 }
714
715 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700716 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700717 }
718
719 return 0;
720}
721
722binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700723 os::incremental::IncrementalFileSystemControlParcel control;
724 control.cmd.reset(dup(ifs.control.cmd()));
725 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700726 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700727 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700728 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700729 }
730
731 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800732 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
733 if (status.isOk()) {
734 // Store enabled state.
735 ifs.setReadLogsEnabled(enableReadLogs);
736 }
737 return status;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700738}
739
Songchun Fan3c82a302019-11-29 14:23:45 -0800740void IncrementalService::deleteStorage(StorageId storageId) {
741 const auto ifs = getIfs(storageId);
742 if (!ifs) {
743 return;
744 }
745 deleteStorage(*ifs);
746}
747
748void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
749 std::unique_lock l(ifs.lock);
750 deleteStorageLocked(ifs, std::move(l));
751}
752
753void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
754 std::unique_lock<std::mutex>&& ifsLock) {
755 const auto storages = std::move(ifs.storages);
756 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
757 const auto bindPoints = ifs.bindPoints;
758 ifsLock.unlock();
759
760 std::lock_guard l(mLock);
761 for (auto&& [id, _] : storages) {
762 if (id != ifs.mountId) {
763 mMounts.erase(id);
764 }
765 }
766 for (auto&& [path, _] : bindPoints) {
767 mBindsByPath.erase(path);
768 }
769 mMounts.erase(ifs.mountId);
770}
771
772StorageId IncrementalService::openStorage(std::string_view pathInMount) {
773 if (!path::isAbsolute(pathInMount)) {
774 return kInvalidStorageId;
775 }
776
777 return findStorageId(path::normalize(pathInMount));
778}
779
Songchun Fan3c82a302019-11-29 14:23:45 -0800780IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
781 std::lock_guard l(mLock);
782 return getIfsLocked(storage);
783}
784
785const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
786 auto it = mMounts.find(storage);
787 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700788 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700789 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800790 }
791 return it->second;
792}
793
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800794int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
795 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800796 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700797 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800798 return -EINVAL;
799 }
800
801 const auto ifs = getIfs(storage);
802 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700803 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800804 return -EINVAL;
805 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800806
Songchun Fan3c82a302019-11-29 14:23:45 -0800807 std::unique_lock l(ifs->lock);
808 const auto storageInfo = ifs->storages.find(storage);
809 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700810 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800811 return -EINVAL;
812 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700813 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700814 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700815 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700816 return -EINVAL;
817 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800818 l.unlock();
819 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800820 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
821 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800822}
823
824int IncrementalService::unbind(StorageId storage, std::string_view target) {
825 if (!path::isAbsolute(target)) {
826 return -EINVAL;
827 }
828
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700829 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800830
831 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
832 // otherwise there's a chance to unmount something completely unrelated
833 const auto norm = path::normalize(target);
834 std::unique_lock l(mLock);
835 const auto storageIt = mBindsByPath.find(norm);
836 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
837 return -EINVAL;
838 }
839 const auto bindIt = storageIt->second;
840 const auto storageId = bindIt->second.storage;
841 const auto ifs = getIfsLocked(storageId);
842 if (!ifs) {
843 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
844 << " is missing";
845 return -EFAULT;
846 }
847 mBindsByPath.erase(storageIt);
848 l.unlock();
849
850 mVold->unmountIncFs(bindIt->first);
851 std::unique_lock l2(ifs->lock);
852 if (ifs->bindPoints.size() <= 1) {
853 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700854 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800855 } else {
856 const std::string savedFile = std::move(bindIt->second.savedFilename);
857 ifs->bindPoints.erase(bindIt);
858 l2.unlock();
859 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800860 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800861 }
862 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700863
Songchun Fan3c82a302019-11-29 14:23:45 -0800864 return 0;
865}
866
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700867std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700868 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700869 std::string_view path) const {
870 if (!path::isAbsolute(path)) {
871 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700872 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700873 auto normPath = path::normalize(path);
874 if (path::startsWith(normPath, storageIt->second.name)) {
875 return normPath;
876 }
877 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700878 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
879 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700880 return {};
881 }
882 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700883}
884
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700885std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700886 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700887 std::unique_lock l(ifs.lock);
888 const auto storageInfo = ifs.storages.find(storage);
889 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800890 return {};
891 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700892 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800893}
894
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800895int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700896 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800897 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700898 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800899 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700900 LOG(ERROR) << "Internal error: storageId " << storage
901 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800902 return -EINVAL;
903 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700904 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700905 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800906 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800907 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700908 if (!data.empty()) {
909 if (auto err = setFileContent(ifs, id, path, data); err) {
910 return err;
911 }
912 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800913 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800914 }
915 return -EINVAL;
916}
917
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800918int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800919 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700920 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800921 if (normPath.empty()) {
922 return -EINVAL;
923 }
924 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800925 }
926 return -EINVAL;
927}
928
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800929int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800930 const auto ifs = getIfs(storageId);
931 if (!ifs) {
932 return -EINVAL;
933 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700934 return makeDirs(*ifs, storageId, path, mode);
935}
936
937int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
938 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800939 std::string normPath = normalizePathToStorage(ifs, storageId, path);
940 if (normPath.empty()) {
941 return -EINVAL;
942 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700943 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800944}
945
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800946int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
947 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700948 std::unique_lock l(mLock);
949 auto ifsSrc = getIfsLocked(sourceStorageId);
950 if (!ifsSrc) {
951 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800952 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700953 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
954 return -EINVAL;
955 }
956 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700957 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
958 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700959 if (normOldPath.empty() || normNewPath.empty()) {
960 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
961 return -EINVAL;
962 }
963 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800964}
965
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800966int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800967 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700968 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800969 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800970 }
971 return -EINVAL;
972}
973
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800974int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
975 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800976 std::string&& target, BindKind kind,
977 std::unique_lock<std::mutex>& mainLock) {
978 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700979 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800980 return -EINVAL;
981 }
982
983 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700984 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800985 if (kind != BindKind::Temporary) {
986 metadata::BindPoint bp;
987 bp.set_storage_id(storage);
988 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800989 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800990 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800991 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800992 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800993 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700994 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
995 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
996 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800997 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700998 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800999 return int(node);
1000 }
1001 }
1002
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001003 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1004 std::move(target), kind, mainLock);
1005 if (res) {
1006 mIncFs->unlink(ifs.control, metadataFullPath);
1007 }
1008 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001009}
1010
1011int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001012 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001013 std::string&& target, BindKind kind,
1014 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001015 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001016 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001017 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001018 if (!status.isOk()) {
1019 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1020 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1021 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1022 : status.serviceSpecificErrorCode() == 0
1023 ? -EFAULT
1024 : status.serviceSpecificErrorCode()
1025 : -EIO;
1026 }
1027 }
1028
1029 if (!mainLock.owns_lock()) {
1030 mainLock.lock();
1031 }
1032 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001033 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1034 std::move(target), kind);
1035 return 0;
1036}
1037
1038void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1039 std::string&& metadataName, std::string&& source,
1040 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001041 const auto [it, _] =
1042 ifs.bindPoints.insert_or_assign(target,
1043 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001044 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001045 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001046}
1047
1048RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1049 const auto ifs = getIfs(storage);
1050 if (!ifs) {
1051 return {};
1052 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001053 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001054 if (normPath.empty()) {
1055 return {};
1056 }
1057 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001058}
1059
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001060RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001061 const auto ifs = getIfs(storage);
1062 if (!ifs) {
1063 return {};
1064 }
1065 return mIncFs->getMetadata(ifs->control, node);
1066}
1067
Songchun Fan3c82a302019-11-29 14:23:45 -08001068bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001069 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001070 {
1071 std::unique_lock l(mLock);
1072 const auto& ifs = getIfsLocked(storage);
1073 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001074 return false;
1075 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001076 dataLoaderStub = ifs->dataLoaderStub;
1077 if (!dataLoaderStub) {
1078 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001079 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001080 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001081 dataLoaderStub->requestStart();
1082 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001083}
1084
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001085void IncrementalService::setUidReadTimeouts(
1086 StorageId storage, const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
1087 using microseconds = std::chrono::microseconds;
1088 using milliseconds = std::chrono::milliseconds;
1089
1090 auto maxPendingTimeUs = microseconds(0);
1091 for (const auto& timeouts : perUidReadTimeouts) {
1092 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1093 }
1094 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
1095 return;
1096 }
1097
1098 const auto ifs = getIfs(storage);
1099 if (!ifs) {
1100 return;
1101 }
1102
1103 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1104 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1105 return;
1106 }
1107
1108 const auto timeout = std::chrono::duration_cast<milliseconds>(maxPendingTimeUs) -
1109 Constants::perUidTimeoutOffset;
1110 updateUidReadTimeouts(storage, Clock::now() + timeout);
1111}
1112
1113void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1114 const auto ifs = getIfs(storage);
1115 if (!ifs) {
1116 return;
1117 }
1118
1119 mIncFs->setUidReadTimeouts(ifs->control, {});
1120}
1121
1122void IncrementalService::updateUidReadTimeouts(StorageId storage, Clock::time_point timeLimit) {
1123 // Reached maximum timeout.
1124 if (Clock::now() >= timeLimit) {
1125 return clearUidReadTimeouts(storage);
1126 }
1127
1128 // Still loading?
1129 const auto progress = getLoadingProgress(storage);
1130 if (progress.isError()) {
1131 // Something is wrong, abort.
1132 return clearUidReadTimeouts(storage);
1133 }
1134
1135 if (progress.started() && progress.fullyLoaded()) {
1136 // Fully loaded, check readLogs collection.
1137 const auto ifs = getIfs(storage);
1138 if (!ifs->readLogsEnabled()) {
1139 return clearUidReadTimeouts(storage);
1140 }
1141 }
1142
1143 const auto timeLeft = timeLimit - Clock::now();
1144 if (timeLeft < Constants::progressUpdateInterval) {
1145 // Don't bother.
1146 return clearUidReadTimeouts(storage);
1147 }
1148
1149 addTimedJob(*mTimedQueue, storage, Constants::progressUpdateInterval,
1150 [this, storage, timeLimit]() { updateUidReadTimeouts(storage, timeLimit); });
1151}
1152
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001153std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1154 std::unordered_set<std::string_view> mountedRootNames;
1155 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1156 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1157 for (auto [source, target] : binds) {
1158 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1159 LOG(INFO) << " " << path::join(root, source);
1160 }
1161
1162 // Ensure it's a kind of a mount that's managed by IncrementalService
1163 if (path::basename(root) != constants().mount ||
1164 path::basename(backingDir) != constants().backing) {
1165 return;
1166 }
1167 const auto expectedRoot = path::dirname(root);
1168 if (path::dirname(backingDir) != expectedRoot) {
1169 return;
1170 }
1171 if (path::dirname(expectedRoot) != mIncrementalDir) {
1172 return;
1173 }
1174 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1175 return;
1176 }
1177
1178 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1179
1180 // make sure we clean up the mount if it happens to be a bad one.
1181 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1182 auto cleanupFiles = makeCleanup([&]() {
1183 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1184 IncFsMount::cleanupFilesystem(expectedRoot);
1185 });
1186 auto cleanupMounts = makeCleanup([&]() {
1187 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1188 for (auto&& [_, target] : binds) {
1189 mVold->unmountIncFs(std::string(target));
1190 }
1191 mVold->unmountIncFs(std::string(root));
1192 });
1193
1194 auto control = mIncFs->openMount(root);
1195 if (!control) {
1196 LOG(INFO) << "failed to open mount " << root;
1197 return;
1198 }
1199
1200 auto mountRecord =
1201 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1202 path::join(root, constants().infoMdName));
1203 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1204 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1205 return;
1206 }
1207
1208 auto mountId = mountRecord.storage().id();
1209 mNextId = std::max(mNextId, mountId + 1);
1210
1211 DataLoaderParamsParcel dataLoaderParams;
1212 {
1213 const auto& loader = mountRecord.loader();
1214 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1215 dataLoaderParams.packageName = loader.package_name();
1216 dataLoaderParams.className = loader.class_name();
1217 dataLoaderParams.arguments = loader.arguments();
1218 }
1219
1220 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1221 std::move(control), *this);
1222 cleanupFiles.release(); // ifs will take care of that now
1223
Alex Buynytskyy04035452020-06-06 20:15:58 -07001224 // Check if marker file present.
1225 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001226 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001227 }
1228
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001229 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1230 auto d = openDir(root);
1231 while (auto e = ::readdir(d.get())) {
1232 if (e->d_type == DT_REG) {
1233 auto name = std::string_view(e->d_name);
1234 if (name.starts_with(constants().mountpointMdPrefix)) {
1235 permanentBindPoints
1236 .emplace_back(name,
1237 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1238 ifs->control,
1239 path::join(root,
1240 name)));
1241 if (permanentBindPoints.back().second.dest_path().empty() ||
1242 permanentBindPoints.back().second.source_subdir().empty()) {
1243 permanentBindPoints.pop_back();
1244 mIncFs->unlink(ifs->control, path::join(root, name));
1245 } else {
1246 LOG(INFO) << "Permanent bind record: '"
1247 << permanentBindPoints.back().second.source_subdir() << "'->'"
1248 << permanentBindPoints.back().second.dest_path() << "'";
1249 }
1250 }
1251 } else if (e->d_type == DT_DIR) {
1252 if (e->d_name == "."sv || e->d_name == ".."sv) {
1253 continue;
1254 }
1255 auto name = std::string_view(e->d_name);
1256 if (name.starts_with(constants().storagePrefix)) {
1257 int storageId;
1258 const auto res =
1259 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1260 name.data() + name.size(), storageId);
1261 if (res.ec != std::errc{} || *res.ptr != '_') {
1262 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1263 << "' for mount " << expectedRoot;
1264 continue;
1265 }
1266 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1267 if (!inserted) {
1268 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1269 << " for mount " << expectedRoot;
1270 continue;
1271 }
1272 ifs->storages.insert_or_assign(storageId,
1273 IncFsMount::Storage{path::join(root, name)});
1274 mNextId = std::max(mNextId, storageId + 1);
1275 }
1276 }
1277 }
1278
1279 if (ifs->storages.empty()) {
1280 LOG(WARNING) << "No valid storages in mount " << root;
1281 return;
1282 }
1283
1284 // now match the mounted directories with what we expect to have in the metadata
1285 {
1286 std::unique_lock l(mLock, std::defer_lock);
1287 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1288 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1289 [&, bindRecord = bindRecord](auto&& bind) {
1290 return bind.second == bindRecord.dest_path() &&
1291 path::join(root, bind.first) ==
1292 bindRecord.source_subdir();
1293 });
1294 if (mountedIt != binds.end()) {
1295 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1296 << " to mount " << mountedIt->first;
1297 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1298 std::move(*bindRecord.mutable_source_subdir()),
1299 std::move(*bindRecord.mutable_dest_path()),
1300 BindKind::Permanent);
1301 if (mountedIt != binds.end() - 1) {
1302 std::iter_swap(mountedIt, binds.end() - 1);
1303 }
1304 binds = binds.first(binds.size() - 1);
1305 } else {
1306 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1307 << ", mounting";
1308 // doesn't exist - try mounting back
1309 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1310 std::move(*bindRecord.mutable_source_subdir()),
1311 std::move(*bindRecord.mutable_dest_path()),
1312 BindKind::Permanent, l)) {
1313 mIncFs->unlink(ifs->control, metadataFile);
1314 }
1315 }
1316 }
1317 }
1318
1319 // if anything stays in |binds| those are probably temporary binds; system restarted since
1320 // they were mounted - so let's unmount them all.
1321 for (auto&& [source, target] : binds) {
1322 if (source.empty()) {
1323 continue;
1324 }
1325 mVold->unmountIncFs(std::string(target));
1326 }
1327 cleanupMounts.release(); // ifs now manages everything
1328
1329 if (ifs->bindPoints.empty()) {
1330 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1331 deleteStorage(*ifs);
1332 return;
1333 }
1334
1335 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1336 CHECK(ifs->dataLoaderStub);
1337
1338 mountedRootNames.insert(path::basename(ifs->root));
1339
1340 // not locking here at all: we're still in the constructor, no other calls can happen
1341 mMounts[ifs->mountId] = std::move(ifs);
1342 });
1343
1344 return mountedRootNames;
1345}
1346
1347void IncrementalService::mountExistingImages(
1348 const std::unordered_set<std::string_view>& mountedRootNames) {
1349 auto dir = openDir(mIncrementalDir);
1350 if (!dir) {
1351 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1352 return;
1353 }
1354 while (auto entry = ::readdir(dir.get())) {
1355 if (entry->d_type != DT_DIR) {
1356 continue;
1357 }
1358 std::string_view name = entry->d_name;
1359 if (!name.starts_with(constants().mountKeyPrefix)) {
1360 continue;
1361 }
1362 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001363 continue;
1364 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001365 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001366 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001367 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001368 }
1369 }
1370}
1371
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001372bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001373 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001374 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001375
Songchun Fan3c82a302019-11-29 14:23:45 -08001376 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001377 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001378 if (!status.isOk()) {
1379 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1380 return false;
1381 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001382
1383 int cmd = controlParcel.cmd.release().release();
1384 int pendingReads = controlParcel.pendingReads.release().release();
1385 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001386 int blocksWritten =
1387 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1388 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001389
1390 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1391
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001392 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1393 path::join(mountTarget, constants().infoMdName));
1394 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001395 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1396 return false;
1397 }
1398
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001399 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001400 mNextId = std::max(mNextId, ifs->mountId + 1);
1401
Alex Buynytskyy04035452020-06-06 20:15:58 -07001402 // Check if marker file present.
1403 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001404 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001405 }
1406
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001407 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001408 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001409 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001410 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001411 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001412 dataLoaderParams.packageName = loader.package_name();
1413 dataLoaderParams.className = loader.class_name();
1414 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001415 }
1416
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001417 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001418 CHECK(ifs->dataLoaderStub);
1419
Songchun Fan3c82a302019-11-29 14:23:45 -08001420 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001421 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001422 while (auto e = ::readdir(d.get())) {
1423 if (e->d_type == DT_REG) {
1424 auto name = std::string_view(e->d_name);
1425 if (name.starts_with(constants().mountpointMdPrefix)) {
1426 bindPoints.emplace_back(name,
1427 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1428 ifs->control,
1429 path::join(mountTarget,
1430 name)));
1431 if (bindPoints.back().second.dest_path().empty() ||
1432 bindPoints.back().second.source_subdir().empty()) {
1433 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001434 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001435 }
1436 }
1437 } else if (e->d_type == DT_DIR) {
1438 if (e->d_name == "."sv || e->d_name == ".."sv) {
1439 continue;
1440 }
1441 auto name = std::string_view(e->d_name);
1442 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001443 int storageId;
1444 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1445 name.data() + name.size(), storageId);
1446 if (res.ec != std::errc{} || *res.ptr != '_') {
1447 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1448 << root;
1449 continue;
1450 }
1451 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001452 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001453 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001454 << " for mount " << root;
1455 continue;
1456 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001457 ifs->storages.insert_or_assign(storageId,
1458 IncFsMount::Storage{
1459 path::join(root, constants().mount, name)});
1460 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001461 }
1462 }
1463 }
1464
1465 if (ifs->storages.empty()) {
1466 LOG(WARNING) << "No valid storages in mount " << root;
1467 return false;
1468 }
1469
1470 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001471 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001472 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001473 for (auto&& bp : bindPoints) {
1474 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1475 std::move(*bp.second.mutable_source_subdir()),
1476 std::move(*bp.second.mutable_dest_path()),
1477 BindKind::Permanent, l);
1478 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001479 }
1480
1481 if (bindCount == 0) {
1482 LOG(WARNING) << "No valid bind points for mount " << root;
1483 deleteStorage(*ifs);
1484 return false;
1485 }
1486
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001487 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001488 mMounts[ifs->mountId] = std::move(ifs);
1489 return true;
1490}
1491
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001492void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001493 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001494 while (mRunning.load(std::memory_order_relaxed)) {
1495 mLooper->pollAll(kTimeoutMsecs);
1496 }
1497}
1498
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001499IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001500 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001501 const DataLoaderStatusListener* statusListener,
1502 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001503 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001504 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1505 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001506 return ifs.dataLoaderStub;
1507}
1508
1509void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001510 const DataLoaderStatusListener* statusListener,
1511 StorageHealthCheckParams&& healthCheckParams,
1512 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001513 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001514 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001515 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001516 }
1517
Songchun Fan3c82a302019-11-29 14:23:45 -08001518 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001519 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001520 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1521 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1522 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001523 if (ifs.control.blocksWritten() >= 0) {
1524 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1525 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001526 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001527
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001528 ifs.dataLoaderStub =
1529 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001530 statusListener, std::move(healthCheckParams), healthListener,
1531 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001532}
1533
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001534template <class Duration>
1535static long elapsedMcs(Duration start, Duration end) {
1536 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1537}
1538
1539// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001540// Lib files should be placed next to the APK file in the following matter:
1541// Example:
1542// /path/to/base.apk
1543// /path/to/lib/arm/first.so
1544// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001545bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1546 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001547 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001548 auto start = Clock::now();
1549
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001550 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001551 if (!ifs) {
1552 LOG(ERROR) << "Invalid storage " << storage;
1553 return false;
1554 }
1555
Songchun Fanc8975312020-07-13 12:14:37 -07001556 const auto targetLibPathRelativeToStorage =
1557 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1558 libDirRelativePath);
1559
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001560 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001561 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1562 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001563 << " errno: " << res;
1564 return false;
1565 }
1566
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001567 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001568 ZipArchiveHandle zipFileHandle;
1569 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001570 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1571 return false;
1572 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001573
1574 // Need a shared pointer: will be passing it into all unpacking jobs.
1575 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001576 void* cookie = nullptr;
Songchun Fan2ff2a482020-09-29 11:45:18 -07001577 const auto libFilePrefix = path::join(constants().libDir, abi) + "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001578 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001579 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1580 return false;
1581 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001582 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001583 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1584
1585 auto openZipTs = Clock::now();
1586
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001587 std::vector<Job> jobQueue;
1588 ZipEntry entry;
1589 std::string_view fileName;
1590 while (!Next(cookie, &entry, &fileName)) {
1591 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001592 continue;
1593 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001594
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001595 if (!extractNativeLibs) {
1596 // ensure the file is properly aligned and unpacked
1597 if (entry.method != kCompressStored) {
1598 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1599 return false;
1600 }
1601 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1602 LOG(WARNING) << "Library " << fileName
1603 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1604 << entry.offset;
1605 return false;
1606 }
1607 continue;
1608 }
1609
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001610 auto startFileTs = Clock::now();
1611
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001612 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001613 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001614 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001615 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001616 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001617 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001618 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1619 << "; skipping extraction, spent "
1620 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1621 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001622 continue;
1623 }
1624
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001625 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001626 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001627 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001628 .signature = {},
1629 // Metadata of the new lib file is its relative path
1630 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1631 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001632 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001633 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1634 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001635 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001636 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001637 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001638 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001639
1640 auto makeFileTs = Clock::now();
1641
Songchun Fanafaf6e92020-03-18 14:12:20 -07001642 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001643 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001644 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001645 LOG(INFO) << "incfs: Extracted " << libName
1646 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001647 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001648 continue;
1649 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001650
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001651 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1652 libFileId, libPath = std::move(targetLibPath),
1653 makeFileTs]() mutable {
1654 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001655 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001656
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001657 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001658 auto prepareJobTs = Clock::now();
1659 LOG(INFO) << "incfs: Processed " << libName << ": "
1660 << elapsedMcs(startFileTs, prepareJobTs)
1661 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1662 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001663 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001664 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001665
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001666 auto processedTs = Clock::now();
1667
1668 if (!jobQueue.empty()) {
1669 {
1670 std::lock_guard lock(mJobMutex);
1671 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001672 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001673 if (existingJobs.empty()) {
1674 existingJobs = std::move(jobQueue);
1675 } else {
1676 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1677 std::move_iterator(jobQueue.end()));
1678 }
1679 }
1680 }
1681 mJobCondition.notify_all();
1682 }
1683
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001684 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001685 auto end = Clock::now();
1686 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1687 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1688 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001689 << " make files: " << elapsedMcs(openZipTs, processedTs)
1690 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001691 }
1692
1693 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001694}
1695
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001696void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1697 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001698 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001699 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001700 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001701 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001702 return;
1703 }
1704
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001705 auto startedTs = Clock::now();
1706
1707 // Write extracted data to new file
1708 // NOTE: don't zero-initialize memory, it may take a while for nothing
1709 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1710 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001711 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001712 return;
1713 }
1714
1715 auto extractFileTs = Clock::now();
1716
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001717 if (setFileContent(ifs, libFileId, debugLibPath,
1718 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001719 return;
1720 }
1721
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001722 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001723 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001724 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1725 << entry.compressed_length << " -> " << entry.uncompressed_length
1726 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001727 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1728 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001729 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001730 }
1731}
1732
1733bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001734 struct WaitPrinter {
1735 const Clock::time_point startTs = Clock::now();
1736 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001737 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001738 const auto endTs = Clock::now();
1739 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1740 << elapsedMcs(startTs, endTs) << "mcs";
1741 }
1742 }
1743 } waitPrinter;
1744
1745 MountId mount;
1746 {
1747 auto ifs = getIfs(storage);
1748 if (!ifs) {
1749 return true;
1750 }
1751 mount = ifs->mountId;
1752 }
1753
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001754 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001755 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001756 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001757 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001758 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001759 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001760}
1761
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001762int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1763 std::string_view debugFilePath,
1764 std::span<const uint8_t> data) const {
1765 auto startTs = Clock::now();
1766
1767 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1768 if (!writeFd.ok()) {
1769 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1770 << " errno: " << writeFd.get();
1771 return writeFd.get();
1772 }
1773
1774 const auto dataLength = data.size();
1775
1776 auto openFileTs = Clock::now();
1777 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1778 std::vector<IncFsDataBlock> instructions(numBlocks);
1779 for (int i = 0; i < numBlocks; i++) {
1780 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1781 instructions[i] = IncFsDataBlock{
1782 .fileFd = writeFd.get(),
1783 .pageIndex = static_cast<IncFsBlockIndex>(i),
1784 .compression = INCFS_COMPRESSION_KIND_NONE,
1785 .kind = INCFS_BLOCK_KIND_DATA,
1786 .dataSize = static_cast<uint32_t>(blockSize),
1787 .data = reinterpret_cast<const char*>(data.data()),
1788 };
1789 data = data.subspan(blockSize);
1790 }
1791 auto prepareInstsTs = Clock::now();
1792
1793 size_t res = mIncFs->writeBlocks(instructions);
1794 if (res != instructions.size()) {
1795 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1796 return res;
1797 }
1798
1799 if (perfLoggingEnabled()) {
1800 auto endTs = Clock::now();
1801 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1802 << " bytes): " << elapsedMcs(startTs, endTs)
1803 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1804 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1805 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1806 }
1807
1808 return 0;
1809}
1810
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001811int IncrementalService::isFileFullyLoaded(StorageId storage, std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001812 std::unique_lock l(mLock);
1813 const auto ifs = getIfsLocked(storage);
1814 if (!ifs) {
1815 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1816 return -EINVAL;
1817 }
1818 const auto storageInfo = ifs->storages.find(storage);
1819 if (storageInfo == ifs->storages.end()) {
1820 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1821 return -EINVAL;
1822 }
1823 l.unlock();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001824 return isFileFullyLoadedFromPath(*ifs, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001825}
1826
1827int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1828 std::string_view filePath) const {
1829 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1830 if (filledBlocks < 0) {
1831 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1832 << filePath << " errno: " << filledBlocks;
1833 return filledBlocks;
1834 }
1835 if (totalBlocks < filledBlocks) {
1836 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1837 return -EINVAL;
1838 }
1839 return totalBlocks - filledBlocks;
1840}
1841
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001842IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
1843 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07001844 std::unique_lock l(mLock);
1845 const auto ifs = getIfsLocked(storage);
1846 if (!ifs) {
1847 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001848 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001849 }
1850 const auto storageInfo = ifs->storages.find(storage);
1851 if (storageInfo == ifs->storages.end()) {
1852 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001853 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001854 }
1855 l.unlock();
1856 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
1857}
1858
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001859IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
1860 const IncFsMount& ifs, std::string_view storagePath) const {
1861 ssize_t totalBlocks = 0, filledBlocks = 0;
Songchun Fan374f7652020-08-20 08:40:29 -07001862 const auto filePaths = mFs->listFilesRecursive(storagePath);
1863 for (const auto& filePath : filePaths) {
1864 const auto [filledBlocksCount, totalBlocksCount] =
1865 mIncFs->countFilledBlocks(ifs.control, filePath);
1866 if (filledBlocksCount < 0) {
1867 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1868 << " errno: " << filledBlocksCount;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001869 return {filledBlocksCount, filledBlocksCount};
Songchun Fan374f7652020-08-20 08:40:29 -07001870 }
1871 totalBlocks += totalBlocksCount;
1872 filledBlocks += filledBlocksCount;
1873 }
1874
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001875 return {filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07001876}
1877
Songchun Fana7098592020-09-03 11:45:53 -07001878bool IncrementalService::updateLoadingProgress(
1879 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1880 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001881 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07001882 // Failed to get progress from incfs, abort.
1883 return false;
1884 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001885 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
1886 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07001887 // Stop updating progress once it is fully loaded
1888 return true;
1889 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001890 addTimedJob(*mProgressUpdateJobQueue, storage,
1891 Constants::progressUpdateInterval /* repeat after 1s */,
Songchun Fana7098592020-09-03 11:45:53 -07001892 [storage, progressListener, this]() {
1893 updateLoadingProgress(storage, progressListener);
1894 });
1895 return true;
1896}
1897
1898bool IncrementalService::registerLoadingProgressListener(
1899 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1900 return updateLoadingProgress(storage, progressListener);
1901}
1902
1903bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
1904 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
1905}
1906
Songchun Fan2570ec02020-10-08 17:22:33 -07001907bool IncrementalService::registerStorageHealthListener(
1908 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
1909 const StorageHealthListener& healthListener) {
1910 DataLoaderStubPtr dataLoaderStub;
1911 {
1912 std::unique_lock l(mLock);
1913 const auto& ifs = getIfsLocked(storage);
1914 if (!ifs) {
1915 return false;
1916 }
1917 dataLoaderStub = ifs->dataLoaderStub;
1918 if (!dataLoaderStub) {
1919 return false;
1920 }
1921 }
1922 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
1923 return true;
1924}
1925
1926void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
1927 StorageHealthCheckParams invalidCheckParams;
1928 invalidCheckParams.blockedTimeoutMs = -1;
1929 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
1930}
1931
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001932bool IncrementalService::perfLoggingEnabled() {
1933 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1934 return enabled;
1935}
1936
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001937void IncrementalService::runJobProcessing() {
1938 for (;;) {
1939 std::unique_lock lock(mJobMutex);
1940 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1941 if (!mRunning) {
1942 return;
1943 }
1944
1945 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001946 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001947 auto queue = std::move(it->second);
1948 mJobQueue.erase(it);
1949 lock.unlock();
1950
1951 for (auto&& job : queue) {
1952 job();
1953 }
1954
1955 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001956 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001957 lock.unlock();
1958 mJobCondition.notify_all();
1959 }
1960}
1961
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001962void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001963 sp<IAppOpsCallback> listener;
1964 {
1965 std::unique_lock lock{mCallbacksLock};
1966 auto& cb = mCallbackRegistered[packageName];
1967 if (cb) {
1968 return;
1969 }
1970 cb = new AppOpsListener(*this, packageName);
1971 listener = cb;
1972 }
1973
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001974 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1975 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001976}
1977
1978bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1979 sp<IAppOpsCallback> listener;
1980 {
1981 std::unique_lock lock{mCallbacksLock};
1982 auto found = mCallbackRegistered.find(packageName);
1983 if (found == mCallbackRegistered.end()) {
1984 return false;
1985 }
1986 listener = found->second;
1987 mCallbackRegistered.erase(found);
1988 }
1989
1990 mAppOpsManager->stopWatchingMode(listener);
1991 return true;
1992}
1993
1994void IncrementalService::onAppOpChanged(const std::string& packageName) {
1995 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001996 return;
1997 }
1998
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001999 std::vector<IfsMountPtr> affected;
2000 {
2001 std::lock_guard l(mLock);
2002 affected.reserve(mMounts.size());
2003 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002004 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002005 affected.push_back(ifs);
2006 }
2007 }
2008 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002009 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002010 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002011 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002012}
2013
Songchun Fana7098592020-09-03 11:45:53 -07002014bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2015 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002016 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002017 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002018 }
Songchun Fana7098592020-09-03 11:45:53 -07002019 timedQueue.addJob(id, after, std::move(what));
2020 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002021}
2022
Songchun Fana7098592020-09-03 11:45:53 -07002023bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002024 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002025 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002026 }
Songchun Fana7098592020-09-03 11:45:53 -07002027 timedQueue.removeJobs(id);
2028 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002029}
2030
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002031IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
2032 DataLoaderParamsParcel&& params,
2033 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002034 const DataLoaderStatusListener* statusListener,
2035 StorageHealthCheckParams&& healthCheckParams,
2036 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002037 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002038 : mService(service),
2039 mId(id),
2040 mParams(std::move(params)),
2041 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002042 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
2043 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002044 mHealthPath(std::move(healthPath)),
2045 mHealthCheckParams(std::move(healthCheckParams)) {
2046 if (mHealthListener) {
2047 if (!isHealthParamsValid()) {
2048 mHealthListener = {};
2049 }
2050 } else {
2051 // Disable advanced health check statuses.
2052 mHealthCheckParams.blockedTimeoutMs = -1;
2053 }
2054 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002055}
2056
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002057IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002058 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002059 cleanupResources();
2060 }
2061}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002062
2063void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002064 auto now = Clock::now();
2065 {
2066 std::unique_lock lock(mMutex);
2067 mHealthPath.clear();
2068 unregisterFromPendingReads();
2069 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002070 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002071 }
2072
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002073 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002074
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002075 {
2076 std::unique_lock lock(mMutex);
2077 mParams = {};
2078 mControl = {};
2079 mHealthControl = {};
2080 mHealthListener = {};
2081 mStatusCondition.wait_until(lock, now + 60s, [this] {
2082 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2083 });
2084 mStatusListener = {};
2085 mId = kInvalidStorageId;
2086 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002087}
2088
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002089sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2090 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002091 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002092 if (!status.isOk()) {
2093 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2094 return {};
2095 }
2096 if (!dataloader) {
2097 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2098 return {};
2099 }
2100 return dataloader;
2101}
2102
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002103bool IncrementalService::DataLoaderStub::requestCreate() {
2104 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2105}
2106
2107bool IncrementalService::DataLoaderStub::requestStart() {
2108 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2109}
2110
2111bool IncrementalService::DataLoaderStub::requestDestroy() {
2112 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2113}
2114
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002115bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002116 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002117 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002118 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002119 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002120 return fsmStep();
2121}
2122
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002123void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002124 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002125 mTargetStatus = status;
2126 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002127 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002128 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002129}
2130
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002131bool IncrementalService::DataLoaderStub::bind() {
2132 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002133 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002134 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002135 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002136 return false;
2137 }
2138 return true;
2139}
2140
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002141bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002142 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002143 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002144 return false;
2145 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002146 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002147 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002148 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002149 return false;
2150 }
2151 return true;
2152}
2153
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002154bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002155 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002156 if (!dataloader) {
2157 return false;
2158 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002159 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002160 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002161 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002162 return false;
2163 }
2164 return true;
2165}
2166
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002167bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002168 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002169}
2170
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002171bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002172 if (!isValid()) {
2173 return false;
2174 }
2175
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002176 int currentStatus;
2177 int targetStatus;
2178 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002179 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002180 currentStatus = mCurrentStatus;
2181 targetStatus = mTargetStatus;
2182 }
2183
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002184 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002185
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002186 if (currentStatus == targetStatus) {
2187 return true;
2188 }
2189
2190 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002191 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2192 // Do nothing, this is a reset state.
2193 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002194 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
2195 return destroy();
2196 }
2197 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2198 switch (currentStatus) {
2199 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2200 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2201 return start();
2202 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002203 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002204 }
2205 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2206 switch (currentStatus) {
2207 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002208 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002209 return bind();
2210 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002211 return create();
2212 }
2213 break;
2214 default:
2215 LOG(ERROR) << "Invalid target status: " << targetStatus
2216 << ", current status: " << currentStatus;
2217 break;
2218 }
2219 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002220}
2221
2222binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002223 if (!isValid()) {
2224 return binder::Status::
2225 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2226 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002227 if (id() != mountId) {
2228 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002229 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2230 }
2231
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002232 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002233 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002234 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002235 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002236 if (mCurrentStatus == newStatus) {
2237 return binder::Status::ok();
2238 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002239
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002240 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002241 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002242 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002243
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002244 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002245
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002246 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002247 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2248 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002249 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002250 }
2251
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002252 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002253 << newStatus << " (target " << targetStatus << ")";
2254
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002255 if (listener) {
2256 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002257 }
2258
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002259 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002260
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002261 mStatusCondition.notify_all();
2262
Songchun Fan3c82a302019-11-29 14:23:45 -08002263 return binder::Status::ok();
2264}
2265
Songchun Fan33093982020-09-10 13:12:39 -07002266binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2267 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002268 if (!isValid()) {
2269 return binder::Status::
2270 fromServiceSpecificError(-EINVAL,
2271 "reportStreamHealth came to invalid DataLoaderStub");
2272 }
2273 if (id() != mountId) {
2274 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
2275 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2276 }
2277 {
2278 std::lock_guard lock(mMutex);
2279 mStreamStatus = newStatus;
2280 }
Songchun Fan33093982020-09-10 13:12:39 -07002281 return binder::Status::ok();
2282}
2283
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002284bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2285 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2286 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002287}
2288
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002289void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2290 int healthStatus) {
2291 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2292 if (healthListener) {
2293 healthListener->onHealthStatus(id(), healthStatus);
2294 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002295}
2296
Songchun Fan2570ec02020-10-08 17:22:33 -07002297static int adjustHealthStatus(int healthStatus, int streamStatus) {
2298 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2299 // everything is good; no need to change status
2300 return healthStatus;
2301 }
2302 int newHeathStatus = healthStatus;
2303 switch (streamStatus) {
2304 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2305 // storage is limited and storage not healthy
2306 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2307 break;
2308 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2309 // fall through
2310 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2311 // fall through
2312 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2313 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2314 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2315 }
2316 // pending/blocked status due to transportation issues is not regarded as unhealthy
2317 break;
2318 default:
2319 break;
2320 }
2321 return newHeathStatus;
2322}
2323
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002324void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2325 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002326
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002327 int healthStatusToReport = -1;
2328 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002329
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002330 {
2331 std::unique_lock lock(mMutex);
2332 unregisterFromPendingReads();
2333
2334 healthListener = mHealthListener;
2335
2336 // Healthcheck depends on timestamp of the oldest pending read.
2337 // 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 -07002338 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2339 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002340 const auto now = Clock::now();
2341 const auto kernelTsUs = getOldestPendingReadTs();
2342 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002343 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2344 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002345 mHealthBase = {now, kernelTsUs};
2346 }
2347
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002348 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2349 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002350 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2351 registerForPendingReads();
2352 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2353 lock.unlock();
2354 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002355 return;
2356 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002357
2358 resetHealthControl();
2359
2360 // Always make sure the data loader is started.
2361 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2362
2363 // Skip any further processing if health check params are invalid.
2364 if (!isHealthParamsValid()) {
2365 LOG(DEBUG) << id()
2366 << ": Skip any further processing if health check params are invalid.";
2367 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2368 lock.unlock();
2369 onHealthStatus(healthListener, healthStatusToReport);
2370 // Triggering data loader start. This is a one-time action.
2371 fsmStep();
2372 return;
2373 }
2374
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002375 // Don't schedule timer job less than 500ms in advance.
2376 static constexpr auto kTolerance = 500ms;
2377
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002378 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2379 const auto unhealthyTimeout =
2380 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2381 const auto unhealthyMonitoring =
2382 std::max(1000ms,
2383 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2384
2385 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2386 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002387 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002388
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002389 Milliseconds checkBackAfter;
2390 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002391 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002392 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002393 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002394 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002395 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002396 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002397 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2398 } else {
2399 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002400 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002401 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2402 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002403 // Adjust health status based on stream status
2404 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002405 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002406 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002407 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2408 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002409 }
2410
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002411 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002412 if (healthStatusToReport != -1) {
2413 onHealthStatus(healthListener, healthStatusToReport);
2414 }
2415
2416 fsmStep();
2417}
2418
2419const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2420 if (mHealthPath.empty()) {
2421 resetHealthControl();
2422 return mHealthControl;
2423 }
2424 if (mHealthControl.pendingReads() < 0) {
2425 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2426 }
2427 if (mHealthControl.pendingReads() < 0) {
2428 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2429 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2430 << mHealthControl.logs() << ")";
2431 }
2432 return mHealthControl;
2433}
2434
2435void IncrementalService::DataLoaderStub::resetHealthControl() {
2436 mHealthControl = {};
2437}
2438
2439BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2440 auto result = kMaxBootClockTsUs;
2441
2442 const auto& control = initializeHealthControl();
2443 if (control.pendingReads() < 0) {
2444 return result;
2445 }
2446
Songchun Fan6944f1e2020-11-06 15:24:24 -08002447 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002448 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002449 mLastPendingReads.empty()) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002450 return result;
2451 }
2452
2453 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002454 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002455
Songchun Fan6944f1e2020-11-06 15:24:24 -08002456 for (auto&& pendingRead : mLastPendingReads) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002457 result = std::min(result, pendingRead.bootClockTsUs);
2458 }
2459 return result;
2460}
2461
2462void IncrementalService::DataLoaderStub::registerForPendingReads() {
2463 const auto pendingReadsFd = mHealthControl.pendingReads();
2464 if (pendingReadsFd < 0) {
2465 return;
2466 }
2467
2468 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2469
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002470 mService.mLooper->addFd(
2471 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2472 [](int, int, void* data) -> int {
2473 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002474 self->updateHealthStatus(/*baseline=*/true);
2475 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002476 },
2477 this);
2478 mService.mLooper->wake();
2479}
2480
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002481void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002482 const auto pendingReadsFd = mHealthControl.pendingReads();
2483 if (pendingReadsFd < 0) {
2484 return;
2485 }
2486
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002487 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2488
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002489 mService.mLooper->removeFd(pendingReadsFd);
2490 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002491}
2492
Songchun Fan2570ec02020-10-08 17:22:33 -07002493void IncrementalService::DataLoaderStub::setHealthListener(
2494 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2495 std::lock_guard lock(mMutex);
2496 mHealthCheckParams = std::move(healthCheckParams);
2497 if (healthListener == nullptr) {
2498 // reset listener and params
2499 mHealthListener = {};
2500 } else {
2501 mHealthListener = *healthListener;
2502 }
2503}
2504
Songchun Fan6944f1e2020-11-06 15:24:24 -08002505static std::string toHexString(const RawMetadata& metadata) {
2506 int n = metadata.size();
2507 std::string res(n * 2, '\0');
2508 // Same as incfs::toString(fileId)
2509 static constexpr char kHexChar[] = "0123456789abcdef";
2510 for (int i = 0; i < n; ++i) {
2511 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2512 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2513 }
2514 return res;
2515}
2516
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002517void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002518 dprintf(fd, " dataLoader: {\n");
2519 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2520 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2521 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002522 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002523 dprintf(fd, " health: {\n");
2524 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2525 dprintf(fd, " base: %lldmcs (%lld)\n",
2526 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2527 (long long)mHealthBase.kernelTsUs);
2528 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2529 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2530 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2531 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002532 dprintf(fd, " lastPendingReads: \n");
2533 const auto control = mService.mIncFs->openMount(mHealthPath);
2534 for (auto&& pendingRead : mLastPendingReads) {
2535 dprintf(fd, " fileId: %s\n", mService.mIncFs->toString(pendingRead.id).c_str());
2536 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2537 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2538 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2539 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2540 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002541 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002542 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002543 dprintf(fd, " dataLoaderParams: {\n");
2544 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2545 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2546 dprintf(fd, " className: %s\n", params.className.c_str());
2547 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2548 dprintf(fd, " }\n");
2549 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002550}
2551
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002552void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2553 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002554}
2555
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002556binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2557 bool enableReadLogs, int32_t* _aidl_return) {
2558 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2559 return binder::Status::ok();
2560}
2561
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002562FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2563 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2564}
2565
Songchun Fan3c82a302019-11-29 14:23:45 -08002566} // namespace android::incremental