blob: 886c1e5b98ea6b250b2fc69c25a7918d09538e21 [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;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080072
73 // If DL was up and not crashing for 10mins, we consider it healthy and reset all delays.
74 static constexpr auto healthyDataLoaderUptime = 10min;
75 // 10s, 100s (~2min), 1000s (~15min), 10000s (~3hrs)
76 static constexpr auto minBindDelay = 10s;
77 static constexpr auto maxBindDelay = 10000s;
78 static constexpr auto bindDelayMultiplier = 10;
79 static constexpr auto bindDelayJitterDivider = 10;
Songchun Fan3c82a302019-11-29 14:23:45 -080080};
81
82static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070083 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080084 return c;
85}
86
87template <base::LogSeverity level = base::ERROR>
88bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
89 auto cstr = path::c_str(name);
90 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080091 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080092 PLOG(level) << "Can't create directory '" << name << '\'';
93 return false;
94 }
95 struct stat st;
96 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
97 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
98 return false;
99 }
100 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800101 if (::chmod(cstr, mode)) {
102 PLOG(level) << "Changing permission failed for '" << name << '\'';
103 return false;
104 }
105
Songchun Fan3c82a302019-11-29 14:23:45 -0800106 return true;
107}
108
109static std::string toMountKey(std::string_view path) {
110 if (path.empty()) {
111 return "@none";
112 }
113 if (path == "/"sv) {
114 return "@root";
115 }
116 if (path::isAbsolute(path)) {
117 path.remove_prefix(1);
118 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700119 if (path.size() > 16) {
120 path = path.substr(0, 16);
121 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800122 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700123 std::replace_if(
124 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
125 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800126}
127
128static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
129 std::string_view path) {
130 auto mountKey = toMountKey(path);
131 const auto prefixSize = mountKey.size();
132 for (int counter = 0; counter < 1000;
133 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
134 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800135 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800136 return {mountKey, mountRoot};
137 }
138 }
139 return {};
140}
141
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700142template <class Map>
143typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
144 const auto nextIt = map.upper_bound(path);
145 if (nextIt == map.begin()) {
146 return map.end();
147 }
148 const auto suspectIt = std::prev(nextIt);
149 if (!path::startsWith(path, suspectIt->first)) {
150 return map.end();
151 }
152 return suspectIt;
153}
154
155static base::unique_fd dup(base::borrowed_fd fd) {
156 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
157 return base::unique_fd(res);
158}
159
Songchun Fan3c82a302019-11-29 14:23:45 -0800160template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700161static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800162 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800163 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800164 ProtoMessage message;
165 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
166}
167
168static bool isValidMountTarget(std::string_view path) {
169 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
170}
171
172std::string makeBindMdName() {
173 static constexpr auto uuidStringSize = 36;
174
175 uuid_t guid;
176 uuid_generate(guid);
177
178 std::string name;
179 const auto prefixSize = constants().mountpointMdPrefix.size();
180 name.reserve(prefixSize + uuidStringSize);
181
182 name = constants().mountpointMdPrefix;
183 name.resize(prefixSize + uuidStringSize);
184 uuid_unparse(guid, name.data() + prefixSize);
185
186 return name;
187}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700188
189static bool checkReadLogsDisabledMarker(std::string_view root) {
190 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
191 struct stat st;
192 return (::stat(markerPath, &st) == 0);
193}
194
Songchun Fan3c82a302019-11-29 14:23:45 -0800195} // namespace
196
197IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700198 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700199 dataLoaderStub->cleanupResources();
200 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700201 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700202 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800203 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
204 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700205 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800206 incrementalService.mVold->unmountIncFs(target);
207 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700208 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800209 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
210 cleanupFilesystem(root);
211}
212
213auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800214 std::string name;
215 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
216 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
217 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800218 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
219 constants().storagePrefix.data(), id, no);
220 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800221 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800222 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800223 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
224 } else if (err != EEXIST) {
225 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
226 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800227 }
228 }
229 nextStorageDirNo = 0;
230 return storages.end();
231}
232
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700233template <class Func>
234static auto makeCleanup(Func&& f) {
235 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700236 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700237 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
238}
239
240static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
241 return {::opendir(dir), ::closedir};
242}
243
244static auto openDir(std::string_view dir) {
245 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800246}
247
248static int rmDirContent(const char* path) {
249 auto dir = openDir(path);
250 if (!dir) {
251 return -EINVAL;
252 }
253 while (auto entry = ::readdir(dir.get())) {
254 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
255 continue;
256 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700257 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800258 if (entry->d_type == DT_DIR) {
259 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
260 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
261 return err;
262 }
263 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
264 PLOG(WARNING) << "Failed to rmdir " << fullPath;
265 return err;
266 }
267 } else {
268 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
269 PLOG(WARNING) << "Failed to delete " << fullPath;
270 return err;
271 }
272 }
273 }
274 return 0;
275}
276
Songchun Fan3c82a302019-11-29 14:23:45 -0800277void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800278 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800279 ::rmdir(path::join(root, constants().backing).c_str());
280 ::rmdir(path::join(root, constants().mount).c_str());
281 ::rmdir(path::c_str(root));
282}
283
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800284IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800285 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800286 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800287 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700288 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700289 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700290 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700291 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700292 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700293 mFs(sm.getFs()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800294 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700295 CHECK(mVold) << "Vold service is unavailable";
296 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
297 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
298 CHECK(mJni) << "JNI is unavailable";
299 CHECK(mLooper) << "Looper is unavailable";
300 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700301 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700302 CHECK(mFs) << "Fs is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700303
304 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700305 mJobProcessor = std::thread([this]() {
306 mJni->initializeForCurrentThread();
307 runJobProcessing();
308 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700309 mCmdLooperThread = std::thread([this]() {
310 mJni->initializeForCurrentThread();
311 runCmdLooper();
312 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700313
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700314 const auto mountedRootNames = adoptMountedInstances();
315 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800316}
317
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700318IncrementalService::~IncrementalService() {
319 {
320 std::lock_guard lock(mJobMutex);
321 mRunning = false;
322 }
323 mJobCondition.notify_all();
324 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700325 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700326 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700327 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700328 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700329 // Ensure that mounts are destroyed while the service is still valid.
330 mBindsByPath.clear();
331 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700332}
Songchun Fan3c82a302019-11-29 14:23:45 -0800333
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700334static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800335 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800336 case IncrementalService::BindKind::Temporary:
337 return "Temporary";
338 case IncrementalService::BindKind::Permanent:
339 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800340 }
341}
342
343void IncrementalService::onDump(int fd) {
344 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
345 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
346
347 std::unique_lock l(mLock);
348
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700349 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800350 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700351 const IncFsMount& mnt = *ifs;
352 dprintf(fd, " [%d]: {\n", id);
353 if (id != mnt.mountId) {
354 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
355 } else {
356 dprintf(fd, " mountId: %d\n", mnt.mountId);
357 dprintf(fd, " root: %s\n", mnt.root.c_str());
358 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
359 if (mnt.dataLoaderStub) {
360 mnt.dataLoaderStub->onDump(fd);
361 } else {
362 dprintf(fd, " dataLoader: null\n");
363 }
364 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
365 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700366 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800367 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str(),
368 /*stopOnFirstIncomplete=*/false)
369 .getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800370 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700371 }
372 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800373
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700374 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
375 for (auto&& [target, bind] : mnt.bindPoints) {
376 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
377 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
378 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
379 dprintf(fd, " kind: %s\n", toString(bind.kind));
380 }
381 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800382 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700383 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800384 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700385 dprintf(fd, "}\n");
386 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800387 for (auto&& [target, mountPairIt] : mBindsByPath) {
388 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700389 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
390 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
391 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
392 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800393 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700394 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800395}
396
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800397bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
398 if (ifs.dataLoaderStub->params().packageName == Constants::systemPackage) {
399 return true;
400 }
401
402 // Check all permanent binds.
403 for (auto&& [_, bindPoint] : ifs.bindPoints) {
404 if (bindPoint.kind != BindKind::Permanent) {
405 continue;
406 }
407 const auto progress = getLoadingProgressFromPath(ifs, bindPoint.sourceDir,
408 /*stopOnFirstIncomplete=*/true);
409 if (!progress.isError() && !progress.fullyLoaded()) {
410 LOG(INFO) << "Non system mount: [" << bindPoint.sourceDir
411 << "], partial progress: " << progress.getProgress() * 100 << "%";
412 return true;
413 }
414 }
415
416 return false;
417}
418
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700419void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800420 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700421 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800422 }
423
424 std::vector<IfsMountPtr> mounts;
425 {
426 std::lock_guard l(mLock);
427 mounts.reserve(mMounts.size());
428 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800429 if (ifs->mountId != id) {
430 continue;
431 }
432
433 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800434 mounts.push_back(ifs);
435 }
436 }
437 }
438
Alex Buynytskyy69941662020-04-11 21:40:37 -0700439 if (mounts.empty()) {
440 return;
441 }
442
Songchun Fan3c82a302019-11-29 14:23:45 -0800443 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700444 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800445 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700446 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800447 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800448 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800449}
450
451auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
452 for (;;) {
453 if (mNextId == kMaxStorageId) {
454 mNextId = 0;
455 }
456 auto id = ++mNextId;
457 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
458 if (inserted) {
459 return it;
460 }
461 }
462}
463
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800464StorageId IncrementalService::createStorage(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800465 std::string_view mountPoint, const content::pm::DataLoaderParamsParcel& dataLoaderParams,
466 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800467 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
468 if (!path::isAbsolute(mountPoint)) {
469 LOG(ERROR) << "path is not absolute: " << mountPoint;
470 return kInvalidStorageId;
471 }
472
473 auto mountNorm = path::normalize(mountPoint);
474 {
475 const auto id = findStorageId(mountNorm);
476 if (id != kInvalidStorageId) {
477 if (options & CreateOptions::OpenExisting) {
478 LOG(INFO) << "Opened existing storage " << id;
479 return id;
480 }
481 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
482 return kInvalidStorageId;
483 }
484 }
485
486 if (!(options & CreateOptions::CreateNew)) {
487 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
488 return kInvalidStorageId;
489 }
490
491 if (!path::isEmptyDir(mountNorm)) {
492 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
493 return kInvalidStorageId;
494 }
495 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
496 if (mountRoot.empty()) {
497 LOG(ERROR) << "Bad mount point";
498 return kInvalidStorageId;
499 }
500 // Make sure the code removes all crap it may create while still failing.
501 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
502 auto firstCleanupOnFailure =
503 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
504
505 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800506 const auto backing = path::join(mountRoot, constants().backing);
507 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800508 return kInvalidStorageId;
509 }
510
Songchun Fan3c82a302019-11-29 14:23:45 -0800511 IncFsMount::Control control;
512 {
513 std::lock_guard l(mMountOperationLock);
514 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800515
516 if (auto err = rmDirContent(backing.c_str())) {
517 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
518 return kInvalidStorageId;
519 }
520 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
521 return kInvalidStorageId;
522 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800523 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
524 return kInvalidStorageId;
525 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800526 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800527 if (!status.isOk()) {
528 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
529 return kInvalidStorageId;
530 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800531 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
532 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800533 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
534 return kInvalidStorageId;
535 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800536 int cmd = controlParcel.cmd.release().release();
537 int pendingReads = controlParcel.pendingReads.release().release();
538 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800539 int blocksWritten =
540 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
541 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800542 }
543
544 std::unique_lock l(mLock);
545 const auto mountIt = getStorageSlotLocked();
546 const auto mountId = mountIt->first;
547 l.unlock();
548
549 auto ifs =
550 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
551 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
552 // is the removal of the |ifs|.
553 firstCleanupOnFailure.release();
554
555 auto secondCleanup = [this, &l](auto itPtr) {
556 if (!l.owns_lock()) {
557 l.lock();
558 }
559 mMounts.erase(*itPtr);
560 };
561 auto secondCleanupOnFailure =
562 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
563
564 const auto storageIt = ifs->makeStorage(ifs->mountId);
565 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800566 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800567 return kInvalidStorageId;
568 }
569
570 {
571 metadata::Mount m;
572 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700573 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800574 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
575 m.mutable_loader()->set_class_name(dataLoaderParams.className);
576 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800577 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800578 if (auto err =
579 mIncFs->makeFile(ifs->control,
580 path::join(ifs->root, constants().mount,
581 constants().infoMdName),
582 0777, idFromMetadata(metadata),
583 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800584 LOG(ERROR) << "Saving mount metadata failed: " << -err;
585 return kInvalidStorageId;
586 }
587 }
588
589 const auto bk =
590 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800591 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
592 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800593 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800594 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800595 return kInvalidStorageId;
596 }
597
598 // Done here as well, all data structures are in good state.
599 secondCleanupOnFailure.release();
600
Songchun Fan3c82a302019-11-29 14:23:45 -0800601 mountIt->second = std::move(ifs);
602 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700603
Songchun Fan3c82a302019-11-29 14:23:45 -0800604 LOG(INFO) << "created storage " << mountId;
605 return mountId;
606}
607
608StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
609 StorageId linkedStorage,
610 IncrementalService::CreateOptions options) {
611 if (!isValidMountTarget(mountPoint)) {
612 LOG(ERROR) << "Mount point is invalid or missing";
613 return kInvalidStorageId;
614 }
615
616 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700617 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800618 if (!ifs) {
619 LOG(ERROR) << "Ifs unavailable";
620 return kInvalidStorageId;
621 }
622
623 const auto mountIt = getStorageSlotLocked();
624 const auto storageId = mountIt->first;
625 const auto storageIt = ifs->makeStorage(storageId);
626 if (storageIt == ifs->storages.end()) {
627 LOG(ERROR) << "Can't create a new storage";
628 mMounts.erase(mountIt);
629 return kInvalidStorageId;
630 }
631
632 l.unlock();
633
634 const auto bk =
635 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800636 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
637 std::string(storageIt->second.name), path::normalize(mountPoint),
638 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800639 err < 0) {
640 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700641 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
642 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800643 return kInvalidStorageId;
644 }
645
646 mountIt->second = ifs;
647 return storageId;
648}
649
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800650bool IncrementalService::startLoading(StorageId storage,
651 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
652 const DataLoaderStatusListener& statusListener,
653 StorageHealthCheckParams&& healthCheckParams,
654 const StorageHealthListener& healthListener,
655 const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
656 // Per Uid timeouts.
657 if (!perUidReadTimeouts.empty()) {
658 setUidReadTimeouts(storage, perUidReadTimeouts);
659 }
660
661 // Re-initialize DataLoader.
662 std::unique_lock l(mLock);
663 const auto ifs = getIfsLocked(storage);
664 if (!ifs) {
665 return false;
666 }
667 if (ifs->dataLoaderStub) {
668 ifs->dataLoaderStub->cleanupResources();
669 ifs->dataLoaderStub = {};
670 }
671 l.unlock();
672
673 // DataLoader.
674 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
675 std::move(healthCheckParams), &healthListener);
676 CHECK(dataLoaderStub);
677
678 return dataLoaderStub->requestStart();
679}
680
Songchun Fan3c82a302019-11-29 14:23:45 -0800681IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
682 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700683 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800684}
685
686StorageId IncrementalService::findStorageId(std::string_view path) const {
687 std::lock_guard l(mLock);
688 auto it = findStorageLocked(path);
689 if (it == mBindsByPath.end()) {
690 return kInvalidStorageId;
691 }
692 return it->second->second.storage;
693}
694
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800695void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700696 std::unique_lock l(mLock);
697 const auto ifs = getIfsLocked(storageId);
698 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800699 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700700 return;
701 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800702 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700703 return;
704 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800705 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700706 l.unlock();
707
708 const auto metadata = constants().readLogsDisabledMarkerName;
709 if (auto err = mIncFs->makeFile(ifs->control,
710 path::join(ifs->root, constants().mount,
711 constants().readLogsDisabledMarkerName),
712 0777, idFromMetadata(metadata), {})) {
713 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
714 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
715 return;
716 }
717
718 setStorageParams(storageId, /*enableReadLogs=*/false);
719}
720
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700721int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
722 const auto ifs = getIfs(storageId);
723 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700724 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700725 return -EINVAL;
726 }
727
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700728 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700729 if (enableReadLogs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800730 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700731 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
732 return -EPERM;
733 }
734
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800735 // Check loader usage stats permission and apop.
736 if (auto status = mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700737 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700738 !status.isOk()) {
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800739 LOG(ERROR) << " Permission: " << kLoaderUsageStats
740 << " check failed: " << status.toString8();
741 return fromBinderStatus(status);
742 }
743
744 // Check multiuser permission.
745 if (auto status = mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr,
746 params.packageName.c_str());
747 !status.isOk()) {
748 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
749 << " check failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700750 return fromBinderStatus(status);
751 }
752 }
753
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700754 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
755 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
756 return fromBinderStatus(status);
757 }
758
759 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700760 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700761 }
762
763 return 0;
764}
765
766binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700767 os::incremental::IncrementalFileSystemControlParcel control;
768 control.cmd.reset(dup(ifs.control.cmd()));
769 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700770 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700771 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700772 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700773 }
774
775 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800776 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
777 if (status.isOk()) {
778 // Store enabled state.
779 ifs.setReadLogsEnabled(enableReadLogs);
780 }
781 return status;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700782}
783
Songchun Fan3c82a302019-11-29 14:23:45 -0800784void IncrementalService::deleteStorage(StorageId storageId) {
785 const auto ifs = getIfs(storageId);
786 if (!ifs) {
787 return;
788 }
789 deleteStorage(*ifs);
790}
791
792void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
793 std::unique_lock l(ifs.lock);
794 deleteStorageLocked(ifs, std::move(l));
795}
796
797void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
798 std::unique_lock<std::mutex>&& ifsLock) {
799 const auto storages = std::move(ifs.storages);
800 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
801 const auto bindPoints = ifs.bindPoints;
802 ifsLock.unlock();
803
804 std::lock_guard l(mLock);
805 for (auto&& [id, _] : storages) {
806 if (id != ifs.mountId) {
807 mMounts.erase(id);
808 }
809 }
810 for (auto&& [path, _] : bindPoints) {
811 mBindsByPath.erase(path);
812 }
813 mMounts.erase(ifs.mountId);
814}
815
816StorageId IncrementalService::openStorage(std::string_view pathInMount) {
817 if (!path::isAbsolute(pathInMount)) {
818 return kInvalidStorageId;
819 }
820
821 return findStorageId(path::normalize(pathInMount));
822}
823
Songchun Fan3c82a302019-11-29 14:23:45 -0800824IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
825 std::lock_guard l(mLock);
826 return getIfsLocked(storage);
827}
828
829const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
830 auto it = mMounts.find(storage);
831 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700832 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700833 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800834 }
835 return it->second;
836}
837
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800838int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
839 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800840 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700841 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800842 return -EINVAL;
843 }
844
845 const auto ifs = getIfs(storage);
846 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700847 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800848 return -EINVAL;
849 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800850
Songchun Fan3c82a302019-11-29 14:23:45 -0800851 std::unique_lock l(ifs->lock);
852 const auto storageInfo = ifs->storages.find(storage);
853 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700854 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800855 return -EINVAL;
856 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700857 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700858 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700859 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700860 return -EINVAL;
861 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800862 l.unlock();
863 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800864 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
865 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800866}
867
868int IncrementalService::unbind(StorageId storage, std::string_view target) {
869 if (!path::isAbsolute(target)) {
870 return -EINVAL;
871 }
872
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700873 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800874
875 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
876 // otherwise there's a chance to unmount something completely unrelated
877 const auto norm = path::normalize(target);
878 std::unique_lock l(mLock);
879 const auto storageIt = mBindsByPath.find(norm);
880 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
881 return -EINVAL;
882 }
883 const auto bindIt = storageIt->second;
884 const auto storageId = bindIt->second.storage;
885 const auto ifs = getIfsLocked(storageId);
886 if (!ifs) {
887 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
888 << " is missing";
889 return -EFAULT;
890 }
891 mBindsByPath.erase(storageIt);
892 l.unlock();
893
894 mVold->unmountIncFs(bindIt->first);
895 std::unique_lock l2(ifs->lock);
896 if (ifs->bindPoints.size() <= 1) {
897 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700898 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800899 } else {
900 const std::string savedFile = std::move(bindIt->second.savedFilename);
901 ifs->bindPoints.erase(bindIt);
902 l2.unlock();
903 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800904 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800905 }
906 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700907
Songchun Fan3c82a302019-11-29 14:23:45 -0800908 return 0;
909}
910
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700911std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700912 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700913 std::string_view path) const {
914 if (!path::isAbsolute(path)) {
915 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700916 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700917 auto normPath = path::normalize(path);
918 if (path::startsWith(normPath, storageIt->second.name)) {
919 return normPath;
920 }
921 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700922 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
923 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700924 return {};
925 }
926 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700927}
928
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700929std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700930 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700931 std::unique_lock l(ifs.lock);
932 const auto storageInfo = ifs.storages.find(storage);
933 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800934 return {};
935 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700936 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800937}
938
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800939int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700940 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800941 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700942 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800943 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700944 LOG(ERROR) << "Internal error: storageId " << storage
945 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800946 return -EINVAL;
947 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700948 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700949 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800950 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800951 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700952 if (!data.empty()) {
953 if (auto err = setFileContent(ifs, id, path, data); err) {
954 return err;
955 }
956 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800957 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800958 }
959 return -EINVAL;
960}
961
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800962int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800963 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700964 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800965 if (normPath.empty()) {
966 return -EINVAL;
967 }
968 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800969 }
970 return -EINVAL;
971}
972
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800973int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800974 const auto ifs = getIfs(storageId);
975 if (!ifs) {
976 return -EINVAL;
977 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700978 return makeDirs(*ifs, storageId, path, mode);
979}
980
981int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
982 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800983 std::string normPath = normalizePathToStorage(ifs, storageId, path);
984 if (normPath.empty()) {
985 return -EINVAL;
986 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700987 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800988}
989
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800990int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
991 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700992 std::unique_lock l(mLock);
993 auto ifsSrc = getIfsLocked(sourceStorageId);
994 if (!ifsSrc) {
995 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800996 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700997 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
998 return -EINVAL;
999 }
1000 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001001 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1002 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001003 if (normOldPath.empty() || normNewPath.empty()) {
1004 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1005 return -EINVAL;
1006 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001007 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1008 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1009 << " to " << newPath << "[" << normNewPath << "]";
1010 return err;
1011 }
1012 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001013}
1014
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001015int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001016 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001017 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001018 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001019 }
1020 return -EINVAL;
1021}
1022
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001023int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1024 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001025 std::string&& target, BindKind kind,
1026 std::unique_lock<std::mutex>& mainLock) {
1027 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001028 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001029 return -EINVAL;
1030 }
1031
1032 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001033 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001034 if (kind != BindKind::Temporary) {
1035 metadata::BindPoint bp;
1036 bp.set_storage_id(storage);
1037 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001038 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001039 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001040 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001041 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001042 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001043 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1044 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1045 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001046 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001047 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001048 return int(node);
1049 }
1050 }
1051
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001052 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1053 std::move(target), kind, mainLock);
1054 if (res) {
1055 mIncFs->unlink(ifs.control, metadataFullPath);
1056 }
1057 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001058}
1059
1060int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001061 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001062 std::string&& target, BindKind kind,
1063 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001064 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001065 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001066 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001067 if (!status.isOk()) {
1068 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1069 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1070 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1071 : status.serviceSpecificErrorCode() == 0
1072 ? -EFAULT
1073 : status.serviceSpecificErrorCode()
1074 : -EIO;
1075 }
1076 }
1077
1078 if (!mainLock.owns_lock()) {
1079 mainLock.lock();
1080 }
1081 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001082 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1083 std::move(target), kind);
1084 return 0;
1085}
1086
1087void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1088 std::string&& metadataName, std::string&& source,
1089 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001090 const auto [it, _] =
1091 ifs.bindPoints.insert_or_assign(target,
1092 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001093 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001094 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001095}
1096
1097RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1098 const auto ifs = getIfs(storage);
1099 if (!ifs) {
1100 return {};
1101 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001102 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001103 if (normPath.empty()) {
1104 return {};
1105 }
1106 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001107}
1108
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001109RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001110 const auto ifs = getIfs(storage);
1111 if (!ifs) {
1112 return {};
1113 }
1114 return mIncFs->getMetadata(ifs->control, node);
1115}
1116
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001117void IncrementalService::setUidReadTimeouts(
1118 StorageId storage, const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
1119 using microseconds = std::chrono::microseconds;
1120 using milliseconds = std::chrono::milliseconds;
1121
1122 auto maxPendingTimeUs = microseconds(0);
1123 for (const auto& timeouts : perUidReadTimeouts) {
1124 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1125 }
1126 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001127 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001128 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1129 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001130 return;
1131 }
1132
1133 const auto ifs = getIfs(storage);
1134 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001135 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001136 return;
1137 }
1138
1139 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1140 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1141 return;
1142 }
1143
1144 const auto timeout = std::chrono::duration_cast<milliseconds>(maxPendingTimeUs) -
1145 Constants::perUidTimeoutOffset;
1146 updateUidReadTimeouts(storage, Clock::now() + timeout);
1147}
1148
1149void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1150 const auto ifs = getIfs(storage);
1151 if (!ifs) {
1152 return;
1153 }
1154
1155 mIncFs->setUidReadTimeouts(ifs->control, {});
1156}
1157
1158void IncrementalService::updateUidReadTimeouts(StorageId storage, Clock::time_point timeLimit) {
1159 // Reached maximum timeout.
1160 if (Clock::now() >= timeLimit) {
1161 return clearUidReadTimeouts(storage);
1162 }
1163
1164 // Still loading?
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001165 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/true);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001166 if (progress.isError()) {
1167 // Something is wrong, abort.
1168 return clearUidReadTimeouts(storage);
1169 }
1170
1171 if (progress.started() && progress.fullyLoaded()) {
1172 // Fully loaded, check readLogs collection.
1173 const auto ifs = getIfs(storage);
1174 if (!ifs->readLogsEnabled()) {
1175 return clearUidReadTimeouts(storage);
1176 }
1177 }
1178
1179 const auto timeLeft = timeLimit - Clock::now();
1180 if (timeLeft < Constants::progressUpdateInterval) {
1181 // Don't bother.
1182 return clearUidReadTimeouts(storage);
1183 }
1184
1185 addTimedJob(*mTimedQueue, storage, Constants::progressUpdateInterval,
1186 [this, storage, timeLimit]() { updateUidReadTimeouts(storage, timeLimit); });
1187}
1188
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001189std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1190 std::unordered_set<std::string_view> mountedRootNames;
1191 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1192 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1193 for (auto [source, target] : binds) {
1194 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1195 LOG(INFO) << " " << path::join(root, source);
1196 }
1197
1198 // Ensure it's a kind of a mount that's managed by IncrementalService
1199 if (path::basename(root) != constants().mount ||
1200 path::basename(backingDir) != constants().backing) {
1201 return;
1202 }
1203 const auto expectedRoot = path::dirname(root);
1204 if (path::dirname(backingDir) != expectedRoot) {
1205 return;
1206 }
1207 if (path::dirname(expectedRoot) != mIncrementalDir) {
1208 return;
1209 }
1210 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1211 return;
1212 }
1213
1214 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1215
1216 // make sure we clean up the mount if it happens to be a bad one.
1217 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1218 auto cleanupFiles = makeCleanup([&]() {
1219 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1220 IncFsMount::cleanupFilesystem(expectedRoot);
1221 });
1222 auto cleanupMounts = makeCleanup([&]() {
1223 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1224 for (auto&& [_, target] : binds) {
1225 mVold->unmountIncFs(std::string(target));
1226 }
1227 mVold->unmountIncFs(std::string(root));
1228 });
1229
1230 auto control = mIncFs->openMount(root);
1231 if (!control) {
1232 LOG(INFO) << "failed to open mount " << root;
1233 return;
1234 }
1235
1236 auto mountRecord =
1237 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1238 path::join(root, constants().infoMdName));
1239 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1240 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1241 return;
1242 }
1243
1244 auto mountId = mountRecord.storage().id();
1245 mNextId = std::max(mNextId, mountId + 1);
1246
1247 DataLoaderParamsParcel dataLoaderParams;
1248 {
1249 const auto& loader = mountRecord.loader();
1250 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1251 dataLoaderParams.packageName = loader.package_name();
1252 dataLoaderParams.className = loader.class_name();
1253 dataLoaderParams.arguments = loader.arguments();
1254 }
1255
1256 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1257 std::move(control), *this);
1258 cleanupFiles.release(); // ifs will take care of that now
1259
Alex Buynytskyy04035452020-06-06 20:15:58 -07001260 // Check if marker file present.
1261 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001262 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001263 }
1264
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001265 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1266 auto d = openDir(root);
1267 while (auto e = ::readdir(d.get())) {
1268 if (e->d_type == DT_REG) {
1269 auto name = std::string_view(e->d_name);
1270 if (name.starts_with(constants().mountpointMdPrefix)) {
1271 permanentBindPoints
1272 .emplace_back(name,
1273 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1274 ifs->control,
1275 path::join(root,
1276 name)));
1277 if (permanentBindPoints.back().second.dest_path().empty() ||
1278 permanentBindPoints.back().second.source_subdir().empty()) {
1279 permanentBindPoints.pop_back();
1280 mIncFs->unlink(ifs->control, path::join(root, name));
1281 } else {
1282 LOG(INFO) << "Permanent bind record: '"
1283 << permanentBindPoints.back().second.source_subdir() << "'->'"
1284 << permanentBindPoints.back().second.dest_path() << "'";
1285 }
1286 }
1287 } else if (e->d_type == DT_DIR) {
1288 if (e->d_name == "."sv || e->d_name == ".."sv) {
1289 continue;
1290 }
1291 auto name = std::string_view(e->d_name);
1292 if (name.starts_with(constants().storagePrefix)) {
1293 int storageId;
1294 const auto res =
1295 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1296 name.data() + name.size(), storageId);
1297 if (res.ec != std::errc{} || *res.ptr != '_') {
1298 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1299 << "' for mount " << expectedRoot;
1300 continue;
1301 }
1302 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1303 if (!inserted) {
1304 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1305 << " for mount " << expectedRoot;
1306 continue;
1307 }
1308 ifs->storages.insert_or_assign(storageId,
1309 IncFsMount::Storage{path::join(root, name)});
1310 mNextId = std::max(mNextId, storageId + 1);
1311 }
1312 }
1313 }
1314
1315 if (ifs->storages.empty()) {
1316 LOG(WARNING) << "No valid storages in mount " << root;
1317 return;
1318 }
1319
1320 // now match the mounted directories with what we expect to have in the metadata
1321 {
1322 std::unique_lock l(mLock, std::defer_lock);
1323 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1324 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1325 [&, bindRecord = bindRecord](auto&& bind) {
1326 return bind.second == bindRecord.dest_path() &&
1327 path::join(root, bind.first) ==
1328 bindRecord.source_subdir();
1329 });
1330 if (mountedIt != binds.end()) {
1331 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1332 << " to mount " << mountedIt->first;
1333 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1334 std::move(*bindRecord.mutable_source_subdir()),
1335 std::move(*bindRecord.mutable_dest_path()),
1336 BindKind::Permanent);
1337 if (mountedIt != binds.end() - 1) {
1338 std::iter_swap(mountedIt, binds.end() - 1);
1339 }
1340 binds = binds.first(binds.size() - 1);
1341 } else {
1342 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1343 << ", mounting";
1344 // doesn't exist - try mounting back
1345 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1346 std::move(*bindRecord.mutable_source_subdir()),
1347 std::move(*bindRecord.mutable_dest_path()),
1348 BindKind::Permanent, l)) {
1349 mIncFs->unlink(ifs->control, metadataFile);
1350 }
1351 }
1352 }
1353 }
1354
1355 // if anything stays in |binds| those are probably temporary binds; system restarted since
1356 // they were mounted - so let's unmount them all.
1357 for (auto&& [source, target] : binds) {
1358 if (source.empty()) {
1359 continue;
1360 }
1361 mVold->unmountIncFs(std::string(target));
1362 }
1363 cleanupMounts.release(); // ifs now manages everything
1364
1365 if (ifs->bindPoints.empty()) {
1366 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1367 deleteStorage(*ifs);
1368 return;
1369 }
1370
1371 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1372 CHECK(ifs->dataLoaderStub);
1373
1374 mountedRootNames.insert(path::basename(ifs->root));
1375
1376 // not locking here at all: we're still in the constructor, no other calls can happen
1377 mMounts[ifs->mountId] = std::move(ifs);
1378 });
1379
1380 return mountedRootNames;
1381}
1382
1383void IncrementalService::mountExistingImages(
1384 const std::unordered_set<std::string_view>& mountedRootNames) {
1385 auto dir = openDir(mIncrementalDir);
1386 if (!dir) {
1387 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1388 return;
1389 }
1390 while (auto entry = ::readdir(dir.get())) {
1391 if (entry->d_type != DT_DIR) {
1392 continue;
1393 }
1394 std::string_view name = entry->d_name;
1395 if (!name.starts_with(constants().mountKeyPrefix)) {
1396 continue;
1397 }
1398 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001399 continue;
1400 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001401 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001402 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001403 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001404 }
1405 }
1406}
1407
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001408bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001409 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001410 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001411
Songchun Fan3c82a302019-11-29 14:23:45 -08001412 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001413 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001414 if (!status.isOk()) {
1415 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1416 return false;
1417 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001418
1419 int cmd = controlParcel.cmd.release().release();
1420 int pendingReads = controlParcel.pendingReads.release().release();
1421 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001422 int blocksWritten =
1423 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1424 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001425
1426 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1427
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001428 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1429 path::join(mountTarget, constants().infoMdName));
1430 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001431 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1432 return false;
1433 }
1434
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001435 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001436 mNextId = std::max(mNextId, ifs->mountId + 1);
1437
Alex Buynytskyy04035452020-06-06 20:15:58 -07001438 // Check if marker file present.
1439 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001440 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001441 }
1442
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001443 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001444 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001445 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001446 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001447 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001448 dataLoaderParams.packageName = loader.package_name();
1449 dataLoaderParams.className = loader.class_name();
1450 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001451 }
1452
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001453 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001454 CHECK(ifs->dataLoaderStub);
1455
Songchun Fan3c82a302019-11-29 14:23:45 -08001456 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001457 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001458 while (auto e = ::readdir(d.get())) {
1459 if (e->d_type == DT_REG) {
1460 auto name = std::string_view(e->d_name);
1461 if (name.starts_with(constants().mountpointMdPrefix)) {
1462 bindPoints.emplace_back(name,
1463 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1464 ifs->control,
1465 path::join(mountTarget,
1466 name)));
1467 if (bindPoints.back().second.dest_path().empty() ||
1468 bindPoints.back().second.source_subdir().empty()) {
1469 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001470 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001471 }
1472 }
1473 } else if (e->d_type == DT_DIR) {
1474 if (e->d_name == "."sv || e->d_name == ".."sv) {
1475 continue;
1476 }
1477 auto name = std::string_view(e->d_name);
1478 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001479 int storageId;
1480 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1481 name.data() + name.size(), storageId);
1482 if (res.ec != std::errc{} || *res.ptr != '_') {
1483 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1484 << root;
1485 continue;
1486 }
1487 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001488 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001489 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001490 << " for mount " << root;
1491 continue;
1492 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001493 ifs->storages.insert_or_assign(storageId,
1494 IncFsMount::Storage{
1495 path::join(root, constants().mount, name)});
1496 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001497 }
1498 }
1499 }
1500
1501 if (ifs->storages.empty()) {
1502 LOG(WARNING) << "No valid storages in mount " << root;
1503 return false;
1504 }
1505
1506 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001507 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001508 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001509 for (auto&& bp : bindPoints) {
1510 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1511 std::move(*bp.second.mutable_source_subdir()),
1512 std::move(*bp.second.mutable_dest_path()),
1513 BindKind::Permanent, l);
1514 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001515 }
1516
1517 if (bindCount == 0) {
1518 LOG(WARNING) << "No valid bind points for mount " << root;
1519 deleteStorage(*ifs);
1520 return false;
1521 }
1522
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001523 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001524 mMounts[ifs->mountId] = std::move(ifs);
1525 return true;
1526}
1527
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001528void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001529 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001530 while (mRunning.load(std::memory_order_relaxed)) {
1531 mLooper->pollAll(kTimeoutMsecs);
1532 }
1533}
1534
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001535IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001536 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001537 const DataLoaderStatusListener* statusListener,
1538 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001539 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001540 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1541 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001542 return ifs.dataLoaderStub;
1543}
1544
1545void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001546 const DataLoaderStatusListener* statusListener,
1547 StorageHealthCheckParams&& healthCheckParams,
1548 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001549 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001550 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001551 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001552 }
1553
Songchun Fan3c82a302019-11-29 14:23:45 -08001554 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001555 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001556 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1557 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1558 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001559 if (ifs.control.blocksWritten() >= 0) {
1560 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1561 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001562 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001563
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001564 ifs.dataLoaderStub =
1565 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001566 statusListener, std::move(healthCheckParams), healthListener,
1567 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001568}
1569
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001570template <class Duration>
1571static long elapsedMcs(Duration start, Duration end) {
1572 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1573}
1574
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001575template <class Duration>
1576static constexpr auto castToMs(Duration d) {
1577 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1578}
1579
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001580// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001581// Lib files should be placed next to the APK file in the following matter:
1582// Example:
1583// /path/to/base.apk
1584// /path/to/lib/arm/first.so
1585// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001586bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1587 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001588 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001589 auto start = Clock::now();
1590
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001591 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001592 if (!ifs) {
1593 LOG(ERROR) << "Invalid storage " << storage;
1594 return false;
1595 }
1596
Songchun Fanc8975312020-07-13 12:14:37 -07001597 const auto targetLibPathRelativeToStorage =
1598 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1599 libDirRelativePath);
1600
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001601 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001602 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1603 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001604 << " errno: " << res;
1605 return false;
1606 }
1607
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001608 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001609 ZipArchiveHandle zipFileHandle;
1610 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001611 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1612 return false;
1613 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001614
1615 // Need a shared pointer: will be passing it into all unpacking jobs.
1616 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001617 void* cookie = nullptr;
Songchun Fan2ff2a482020-09-29 11:45:18 -07001618 const auto libFilePrefix = path::join(constants().libDir, abi) + "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001619 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001620 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1621 return false;
1622 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001623 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001624 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1625
1626 auto openZipTs = Clock::now();
1627
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001628 std::vector<Job> jobQueue;
1629 ZipEntry entry;
1630 std::string_view fileName;
1631 while (!Next(cookie, &entry, &fileName)) {
1632 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001633 continue;
1634 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001635
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001636 if (!extractNativeLibs) {
1637 // ensure the file is properly aligned and unpacked
1638 if (entry.method != kCompressStored) {
1639 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1640 return false;
1641 }
1642 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1643 LOG(WARNING) << "Library " << fileName
1644 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1645 << entry.offset;
1646 return false;
1647 }
1648 continue;
1649 }
1650
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001651 auto startFileTs = Clock::now();
1652
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001653 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001654 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001655 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001656 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001657 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001658 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001659 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1660 << "; skipping extraction, spent "
1661 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1662 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001663 continue;
1664 }
1665
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001666 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001667 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001668 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001669 .signature = {},
1670 // Metadata of the new lib file is its relative path
1671 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1672 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001673 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001674 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1675 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001676 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001677 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001678 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001679 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001680
1681 auto makeFileTs = Clock::now();
1682
Songchun Fanafaf6e92020-03-18 14:12:20 -07001683 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001684 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001685 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001686 LOG(INFO) << "incfs: Extracted " << libName
1687 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001688 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001689 continue;
1690 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001691
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001692 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1693 libFileId, libPath = std::move(targetLibPath),
1694 makeFileTs]() mutable {
1695 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001696 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001697
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001698 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001699 auto prepareJobTs = Clock::now();
1700 LOG(INFO) << "incfs: Processed " << libName << ": "
1701 << elapsedMcs(startFileTs, prepareJobTs)
1702 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1703 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001704 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001705 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001706
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001707 auto processedTs = Clock::now();
1708
1709 if (!jobQueue.empty()) {
1710 {
1711 std::lock_guard lock(mJobMutex);
1712 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001713 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001714 if (existingJobs.empty()) {
1715 existingJobs = std::move(jobQueue);
1716 } else {
1717 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1718 std::move_iterator(jobQueue.end()));
1719 }
1720 }
1721 }
1722 mJobCondition.notify_all();
1723 }
1724
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001725 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001726 auto end = Clock::now();
1727 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1728 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1729 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001730 << " make files: " << elapsedMcs(openZipTs, processedTs)
1731 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001732 }
1733
1734 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001735}
1736
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001737void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1738 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001739 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001740 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001741 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001742 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001743 return;
1744 }
1745
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001746 auto startedTs = Clock::now();
1747
1748 // Write extracted data to new file
1749 // NOTE: don't zero-initialize memory, it may take a while for nothing
1750 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1751 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001752 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001753 return;
1754 }
1755
1756 auto extractFileTs = Clock::now();
1757
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001758 if (setFileContent(ifs, libFileId, debugLibPath,
1759 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001760 return;
1761 }
1762
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001763 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001764 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001765 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1766 << entry.compressed_length << " -> " << entry.uncompressed_length
1767 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001768 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1769 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001770 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001771 }
1772}
1773
1774bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001775 struct WaitPrinter {
1776 const Clock::time_point startTs = Clock::now();
1777 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001778 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001779 const auto endTs = Clock::now();
1780 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1781 << elapsedMcs(startTs, endTs) << "mcs";
1782 }
1783 }
1784 } waitPrinter;
1785
1786 MountId mount;
1787 {
1788 auto ifs = getIfs(storage);
1789 if (!ifs) {
1790 return true;
1791 }
1792 mount = ifs->mountId;
1793 }
1794
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001795 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001796 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001797 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001798 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001799 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001800 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001801}
1802
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001803int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1804 std::string_view debugFilePath,
1805 std::span<const uint8_t> data) const {
1806 auto startTs = Clock::now();
1807
1808 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1809 if (!writeFd.ok()) {
1810 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1811 << " errno: " << writeFd.get();
1812 return writeFd.get();
1813 }
1814
1815 const auto dataLength = data.size();
1816
1817 auto openFileTs = Clock::now();
1818 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1819 std::vector<IncFsDataBlock> instructions(numBlocks);
1820 for (int i = 0; i < numBlocks; i++) {
1821 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1822 instructions[i] = IncFsDataBlock{
1823 .fileFd = writeFd.get(),
1824 .pageIndex = static_cast<IncFsBlockIndex>(i),
1825 .compression = INCFS_COMPRESSION_KIND_NONE,
1826 .kind = INCFS_BLOCK_KIND_DATA,
1827 .dataSize = static_cast<uint32_t>(blockSize),
1828 .data = reinterpret_cast<const char*>(data.data()),
1829 };
1830 data = data.subspan(blockSize);
1831 }
1832 auto prepareInstsTs = Clock::now();
1833
1834 size_t res = mIncFs->writeBlocks(instructions);
1835 if (res != instructions.size()) {
1836 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1837 return res;
1838 }
1839
1840 if (perfLoggingEnabled()) {
1841 auto endTs = Clock::now();
1842 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1843 << " bytes): " << elapsedMcs(startTs, endTs)
1844 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1845 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1846 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1847 }
1848
1849 return 0;
1850}
1851
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001852int IncrementalService::isFileFullyLoaded(StorageId storage, std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001853 std::unique_lock l(mLock);
1854 const auto ifs = getIfsLocked(storage);
1855 if (!ifs) {
1856 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1857 return -EINVAL;
1858 }
1859 const auto storageInfo = ifs->storages.find(storage);
1860 if (storageInfo == ifs->storages.end()) {
1861 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1862 return -EINVAL;
1863 }
1864 l.unlock();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001865 return isFileFullyLoadedFromPath(*ifs, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001866}
1867
1868int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1869 std::string_view filePath) const {
1870 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1871 if (filledBlocks < 0) {
1872 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1873 << filePath << " errno: " << filledBlocks;
1874 return filledBlocks;
1875 }
1876 if (totalBlocks < filledBlocks) {
1877 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1878 return -EINVAL;
1879 }
1880 return totalBlocks - filledBlocks;
1881}
1882
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001883IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001884 StorageId storage, bool stopOnFirstIncomplete) const {
Songchun Fan374f7652020-08-20 08:40:29 -07001885 std::unique_lock l(mLock);
1886 const auto ifs = getIfsLocked(storage);
1887 if (!ifs) {
1888 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001889 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001890 }
1891 const auto storageInfo = ifs->storages.find(storage);
1892 if (storageInfo == ifs->storages.end()) {
1893 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001894 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001895 }
1896 l.unlock();
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001897 return getLoadingProgressFromPath(*ifs, storageInfo->second.name, stopOnFirstIncomplete);
Songchun Fan374f7652020-08-20 08:40:29 -07001898}
1899
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001900IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001901 const IncFsMount& ifs, std::string_view storagePath, bool stopOnFirstIncomplete) const {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001902 ssize_t totalBlocks = 0, filledBlocks = 0;
Songchun Fan374f7652020-08-20 08:40:29 -07001903 const auto filePaths = mFs->listFilesRecursive(storagePath);
1904 for (const auto& filePath : filePaths) {
1905 const auto [filledBlocksCount, totalBlocksCount] =
1906 mIncFs->countFilledBlocks(ifs.control, filePath);
1907 if (filledBlocksCount < 0) {
1908 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1909 << " errno: " << filledBlocksCount;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001910 return {filledBlocksCount, filledBlocksCount};
Songchun Fan374f7652020-08-20 08:40:29 -07001911 }
1912 totalBlocks += totalBlocksCount;
1913 filledBlocks += filledBlocksCount;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001914 if (stopOnFirstIncomplete && filledBlocks < totalBlocks) {
1915 break;
1916 }
Songchun Fan374f7652020-08-20 08:40:29 -07001917 }
1918
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001919 return {filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07001920}
1921
Songchun Fana7098592020-09-03 11:45:53 -07001922bool IncrementalService::updateLoadingProgress(
1923 StorageId storage, const StorageLoadingProgressListener& progressListener) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001924 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/false);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001925 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07001926 // Failed to get progress from incfs, abort.
1927 return false;
1928 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001929 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
1930 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07001931 // Stop updating progress once it is fully loaded
1932 return true;
1933 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001934 addTimedJob(*mProgressUpdateJobQueue, storage,
1935 Constants::progressUpdateInterval /* repeat after 1s */,
Songchun Fana7098592020-09-03 11:45:53 -07001936 [storage, progressListener, this]() {
1937 updateLoadingProgress(storage, progressListener);
1938 });
1939 return true;
1940}
1941
1942bool IncrementalService::registerLoadingProgressListener(
1943 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1944 return updateLoadingProgress(storage, progressListener);
1945}
1946
1947bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
1948 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
1949}
1950
Songchun Fan2570ec02020-10-08 17:22:33 -07001951bool IncrementalService::registerStorageHealthListener(
1952 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
1953 const StorageHealthListener& healthListener) {
1954 DataLoaderStubPtr dataLoaderStub;
1955 {
1956 std::unique_lock l(mLock);
1957 const auto& ifs = getIfsLocked(storage);
1958 if (!ifs) {
1959 return false;
1960 }
1961 dataLoaderStub = ifs->dataLoaderStub;
1962 if (!dataLoaderStub) {
1963 return false;
1964 }
1965 }
1966 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
1967 return true;
1968}
1969
1970void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
1971 StorageHealthCheckParams invalidCheckParams;
1972 invalidCheckParams.blockedTimeoutMs = -1;
1973 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
1974}
1975
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001976bool IncrementalService::perfLoggingEnabled() {
1977 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1978 return enabled;
1979}
1980
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001981void IncrementalService::runJobProcessing() {
1982 for (;;) {
1983 std::unique_lock lock(mJobMutex);
1984 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1985 if (!mRunning) {
1986 return;
1987 }
1988
1989 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001990 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001991 auto queue = std::move(it->second);
1992 mJobQueue.erase(it);
1993 lock.unlock();
1994
1995 for (auto&& job : queue) {
1996 job();
1997 }
1998
1999 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002000 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002001 lock.unlock();
2002 mJobCondition.notify_all();
2003 }
2004}
2005
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002006void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002007 sp<IAppOpsCallback> listener;
2008 {
2009 std::unique_lock lock{mCallbacksLock};
2010 auto& cb = mCallbackRegistered[packageName];
2011 if (cb) {
2012 return;
2013 }
2014 cb = new AppOpsListener(*this, packageName);
2015 listener = cb;
2016 }
2017
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002018 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2019 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002020}
2021
2022bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2023 sp<IAppOpsCallback> listener;
2024 {
2025 std::unique_lock lock{mCallbacksLock};
2026 auto found = mCallbackRegistered.find(packageName);
2027 if (found == mCallbackRegistered.end()) {
2028 return false;
2029 }
2030 listener = found->second;
2031 mCallbackRegistered.erase(found);
2032 }
2033
2034 mAppOpsManager->stopWatchingMode(listener);
2035 return true;
2036}
2037
2038void IncrementalService::onAppOpChanged(const std::string& packageName) {
2039 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002040 return;
2041 }
2042
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002043 std::vector<IfsMountPtr> affected;
2044 {
2045 std::lock_guard l(mLock);
2046 affected.reserve(mMounts.size());
2047 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002048 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002049 affected.push_back(ifs);
2050 }
2051 }
2052 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002053 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002054 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002055 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002056}
2057
Songchun Fana7098592020-09-03 11:45:53 -07002058bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2059 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002060 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002061 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002062 }
Songchun Fana7098592020-09-03 11:45:53 -07002063 timedQueue.addJob(id, after, std::move(what));
2064 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002065}
2066
Songchun Fana7098592020-09-03 11:45:53 -07002067bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002068 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002069 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002070 }
Songchun Fana7098592020-09-03 11:45:53 -07002071 timedQueue.removeJobs(id);
2072 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002073}
2074
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002075IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
2076 DataLoaderParamsParcel&& params,
2077 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002078 const DataLoaderStatusListener* statusListener,
2079 StorageHealthCheckParams&& healthCheckParams,
2080 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002081 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002082 : mService(service),
2083 mId(id),
2084 mParams(std::move(params)),
2085 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002086 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
2087 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002088 mHealthPath(std::move(healthPath)),
2089 mHealthCheckParams(std::move(healthCheckParams)) {
2090 if (mHealthListener) {
2091 if (!isHealthParamsValid()) {
2092 mHealthListener = {};
2093 }
2094 } else {
2095 // Disable advanced health check statuses.
2096 mHealthCheckParams.blockedTimeoutMs = -1;
2097 }
2098 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002099}
2100
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002101IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002102 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002103 cleanupResources();
2104 }
2105}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002106
2107void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002108 auto now = Clock::now();
2109 {
2110 std::unique_lock lock(mMutex);
2111 mHealthPath.clear();
2112 unregisterFromPendingReads();
2113 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002114 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002115 }
2116
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002117 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002118
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002119 {
2120 std::unique_lock lock(mMutex);
2121 mParams = {};
2122 mControl = {};
2123 mHealthControl = {};
2124 mHealthListener = {};
2125 mStatusCondition.wait_until(lock, now + 60s, [this] {
2126 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2127 });
2128 mStatusListener = {};
2129 mId = kInvalidStorageId;
2130 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002131}
2132
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002133sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2134 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002135 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002136 if (!status.isOk()) {
2137 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2138 return {};
2139 }
2140 if (!dataloader) {
2141 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2142 return {};
2143 }
2144 return dataloader;
2145}
2146
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002147bool IncrementalService::DataLoaderStub::requestCreate() {
2148 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2149}
2150
2151bool IncrementalService::DataLoaderStub::requestStart() {
2152 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2153}
2154
2155bool IncrementalService::DataLoaderStub::requestDestroy() {
2156 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2157}
2158
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002159bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002160 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002161 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002162 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002163 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002164 return fsmStep();
2165}
2166
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002167void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002168 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002169 mTargetStatus = status;
2170 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002171 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002172 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002173}
2174
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002175Milliseconds IncrementalService::DataLoaderStub::updateBindDelay() {
2176 std::unique_lock lock(mMutex);
2177 const auto previousBindTs = mPreviousBindTs;
2178 const auto now = Clock::now();
2179 mPreviousBindTs = now;
2180
2181 const auto nonCrashingInterval = std::max(castToMs(now - previousBindTs), 100ms);
2182 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2183 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2184 mPreviousBindDelay = 0ms;
2185 return mPreviousBindDelay;
2186 }
2187
2188 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2189 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2190
2191 const auto bindDelayMs =
2192 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2193 maxBindDelayMs)
2194 .count();
2195 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2196 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2197 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
2198
2199 return mPreviousBindDelay;
2200}
2201
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002202bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002203 const auto bindDelay = updateBindDelay();
2204 if (bindDelay > 1s) {
2205 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
2206 << bindDelay.count() / 1000 << "s";
2207 }
2208
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002209 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002210 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2211 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002212 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002213 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002214 return false;
2215 }
2216 return true;
2217}
2218
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002219bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002220 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002221 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002222 return false;
2223 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002224 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002225 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002226 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002227 return false;
2228 }
2229 return true;
2230}
2231
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002232bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002233 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002234 if (!dataloader) {
2235 return false;
2236 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002237 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002238 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002239 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002240 return false;
2241 }
2242 return true;
2243}
2244
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002245bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002246 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002247}
2248
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002249bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002250 if (!isValid()) {
2251 return false;
2252 }
2253
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002254 int currentStatus;
2255 int targetStatus;
2256 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002257 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002258 currentStatus = mCurrentStatus;
2259 targetStatus = mTargetStatus;
2260 }
2261
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002262 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002263
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002264 if (currentStatus == targetStatus) {
2265 return true;
2266 }
2267
2268 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002269 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2270 // Do nothing, this is a reset state.
2271 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002272 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
2273 return destroy();
2274 }
2275 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2276 switch (currentStatus) {
2277 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2278 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2279 return start();
2280 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002281 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002282 }
2283 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2284 switch (currentStatus) {
2285 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002286 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002287 return bind();
2288 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002289 return create();
2290 }
2291 break;
2292 default:
2293 LOG(ERROR) << "Invalid target status: " << targetStatus
2294 << ", current status: " << currentStatus;
2295 break;
2296 }
2297 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002298}
2299
2300binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002301 if (!isValid()) {
2302 return binder::Status::
2303 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2304 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002305 if (id() != mountId) {
2306 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002307 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2308 }
2309
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002310 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002311 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002312 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002313 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002314 if (mCurrentStatus == newStatus) {
2315 return binder::Status::ok();
2316 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002317
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002318 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002319 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002320 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002321
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002322 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002323
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002324 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2325 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002326 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2327 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002328 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002329 }
2330
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002331 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002332 << newStatus << " (target " << targetStatus << ")";
2333
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002334 if (listener) {
2335 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002336 }
2337
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002338 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002339
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002340 mStatusCondition.notify_all();
2341
Songchun Fan3c82a302019-11-29 14:23:45 -08002342 return binder::Status::ok();
2343}
2344
Songchun Fan33093982020-09-10 13:12:39 -07002345binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2346 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002347 if (!isValid()) {
2348 return binder::Status::
2349 fromServiceSpecificError(-EINVAL,
2350 "reportStreamHealth came to invalid DataLoaderStub");
2351 }
2352 if (id() != mountId) {
2353 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
2354 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2355 }
2356 {
2357 std::lock_guard lock(mMutex);
2358 mStreamStatus = newStatus;
2359 }
Songchun Fan33093982020-09-10 13:12:39 -07002360 return binder::Status::ok();
2361}
2362
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002363bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2364 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2365 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002366}
2367
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002368void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2369 int healthStatus) {
2370 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2371 if (healthListener) {
2372 healthListener->onHealthStatus(id(), healthStatus);
2373 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002374}
2375
Songchun Fan2570ec02020-10-08 17:22:33 -07002376static int adjustHealthStatus(int healthStatus, int streamStatus) {
2377 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2378 // everything is good; no need to change status
2379 return healthStatus;
2380 }
2381 int newHeathStatus = healthStatus;
2382 switch (streamStatus) {
2383 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2384 // storage is limited and storage not healthy
2385 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2386 break;
2387 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2388 // fall through
2389 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2390 // fall through
2391 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2392 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2393 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2394 }
2395 // pending/blocked status due to transportation issues is not regarded as unhealthy
2396 break;
2397 default:
2398 break;
2399 }
2400 return newHeathStatus;
2401}
2402
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002403void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2404 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002405
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002406 int healthStatusToReport = -1;
2407 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002408
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002409 {
2410 std::unique_lock lock(mMutex);
2411 unregisterFromPendingReads();
2412
2413 healthListener = mHealthListener;
2414
2415 // Healthcheck depends on timestamp of the oldest pending read.
2416 // 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 -07002417 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2418 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002419 const auto now = Clock::now();
2420 const auto kernelTsUs = getOldestPendingReadTs();
2421 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002422 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2423 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002424 mHealthBase = {now, kernelTsUs};
2425 }
2426
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002427 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2428 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002429 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2430 registerForPendingReads();
2431 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2432 lock.unlock();
2433 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002434 return;
2435 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002436
2437 resetHealthControl();
2438
2439 // Always make sure the data loader is started.
2440 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2441
2442 // Skip any further processing if health check params are invalid.
2443 if (!isHealthParamsValid()) {
2444 LOG(DEBUG) << id()
2445 << ": Skip any further processing if health check params are invalid.";
2446 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2447 lock.unlock();
2448 onHealthStatus(healthListener, healthStatusToReport);
2449 // Triggering data loader start. This is a one-time action.
2450 fsmStep();
2451 return;
2452 }
2453
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002454 // Don't schedule timer job less than 500ms in advance.
2455 static constexpr auto kTolerance = 500ms;
2456
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002457 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2458 const auto unhealthyTimeout =
2459 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2460 const auto unhealthyMonitoring =
2461 std::max(1000ms,
2462 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2463
2464 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2465 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002466 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002467
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002468 Milliseconds checkBackAfter;
2469 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002470 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002471 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002472 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002473 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002474 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002475 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002476 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2477 } else {
2478 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002479 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002480 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2481 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002482 // Adjust health status based on stream status
2483 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002484 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002485 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002486 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2487 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002488 }
2489
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002490 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002491 if (healthStatusToReport != -1) {
2492 onHealthStatus(healthListener, healthStatusToReport);
2493 }
2494
2495 fsmStep();
2496}
2497
2498const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2499 if (mHealthPath.empty()) {
2500 resetHealthControl();
2501 return mHealthControl;
2502 }
2503 if (mHealthControl.pendingReads() < 0) {
2504 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2505 }
2506 if (mHealthControl.pendingReads() < 0) {
2507 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2508 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2509 << mHealthControl.logs() << ")";
2510 }
2511 return mHealthControl;
2512}
2513
2514void IncrementalService::DataLoaderStub::resetHealthControl() {
2515 mHealthControl = {};
2516}
2517
2518BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2519 auto result = kMaxBootClockTsUs;
2520
2521 const auto& control = initializeHealthControl();
2522 if (control.pendingReads() < 0) {
2523 return result;
2524 }
2525
Songchun Fan6944f1e2020-11-06 15:24:24 -08002526 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002527 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002528 mLastPendingReads.empty()) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002529 return result;
2530 }
2531
2532 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002533 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002534
Songchun Fan6944f1e2020-11-06 15:24:24 -08002535 for (auto&& pendingRead : mLastPendingReads) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002536 result = std::min(result, pendingRead.bootClockTsUs);
2537 }
2538 return result;
2539}
2540
2541void IncrementalService::DataLoaderStub::registerForPendingReads() {
2542 const auto pendingReadsFd = mHealthControl.pendingReads();
2543 if (pendingReadsFd < 0) {
2544 return;
2545 }
2546
2547 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2548
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002549 mService.mLooper->addFd(
2550 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2551 [](int, int, void* data) -> int {
2552 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002553 self->updateHealthStatus(/*baseline=*/true);
2554 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002555 },
2556 this);
2557 mService.mLooper->wake();
2558}
2559
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002560void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002561 const auto pendingReadsFd = mHealthControl.pendingReads();
2562 if (pendingReadsFd < 0) {
2563 return;
2564 }
2565
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002566 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2567
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002568 mService.mLooper->removeFd(pendingReadsFd);
2569 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002570}
2571
Songchun Fan2570ec02020-10-08 17:22:33 -07002572void IncrementalService::DataLoaderStub::setHealthListener(
2573 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2574 std::lock_guard lock(mMutex);
2575 mHealthCheckParams = std::move(healthCheckParams);
2576 if (healthListener == nullptr) {
2577 // reset listener and params
2578 mHealthListener = {};
2579 } else {
2580 mHealthListener = *healthListener;
2581 }
2582}
2583
Songchun Fan6944f1e2020-11-06 15:24:24 -08002584static std::string toHexString(const RawMetadata& metadata) {
2585 int n = metadata.size();
2586 std::string res(n * 2, '\0');
2587 // Same as incfs::toString(fileId)
2588 static constexpr char kHexChar[] = "0123456789abcdef";
2589 for (int i = 0; i < n; ++i) {
2590 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2591 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2592 }
2593 return res;
2594}
2595
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002596void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002597 dprintf(fd, " dataLoader: {\n");
2598 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2599 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2600 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002601 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002602 dprintf(fd, " health: {\n");
2603 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2604 dprintf(fd, " base: %lldmcs (%lld)\n",
2605 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2606 (long long)mHealthBase.kernelTsUs);
2607 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2608 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2609 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2610 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002611 dprintf(fd, " lastPendingReads: \n");
2612 const auto control = mService.mIncFs->openMount(mHealthPath);
2613 for (auto&& pendingRead : mLastPendingReads) {
2614 dprintf(fd, " fileId: %s\n", mService.mIncFs->toString(pendingRead.id).c_str());
2615 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2616 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2617 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2618 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2619 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002620 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
2621 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
2622 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002623 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002624 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002625 dprintf(fd, " dataLoaderParams: {\n");
2626 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2627 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2628 dprintf(fd, " className: %s\n", params.className.c_str());
2629 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2630 dprintf(fd, " }\n");
2631 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002632}
2633
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002634void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2635 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002636}
2637
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002638binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2639 bool enableReadLogs, int32_t* _aidl_return) {
2640 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2641 return binder::Status::ok();
2642}
2643
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002644FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2645 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2646}
2647
Songchun Fan3c82a302019-11-29 14:23:45 -08002648} // namespace android::incremental