blob: c38d0b3cc7dbf839ce04ea03af5e795e950698ae [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "IncrementalService"
18
19#include "IncrementalService.h"
20
Songchun Fan3c82a302019-11-29 14:23:45 -080021#include <android-base/logging.h>
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -070022#include <android-base/no_destructor.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080023#include <android-base/properties.h>
24#include <android-base/stringprintf.h>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070025#include <binder/AppOpsManager.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080026#include <binder/Status.h>
27#include <sys/stat.h>
28#include <uuid/uuid.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080029
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070030#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080031#include <ctime>
Songchun Fan3c82a302019-11-29 14:23:45 -080032#include <iterator>
33#include <span>
Songchun Fan3c82a302019-11-29 14:23:45 -080034#include <type_traits>
35
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070036#include "IncrementalServiceValidation.h"
Songchun Fan3c82a302019-11-29 14:23:45 -080037#include "Metadata.pb.h"
38
39using namespace std::literals;
Songchun Fan3c82a302019-11-29 14:23:45 -080040
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -080041constexpr const char* kLoaderUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070042constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070043
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -080044constexpr const char* kInteractAcrossUsers = "android.permission.INTERACT_ACROSS_USERS";
45
Songchun Fan3c82a302019-11-29 14:23:45 -080046namespace android::incremental {
47
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070048using content::pm::DataLoaderParamsParcel;
49using content::pm::FileSystemControlParcel;
50using content::pm::IDataLoader;
51
Songchun Fan3c82a302019-11-29 14:23:45 -080052namespace {
53
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070054using IncrementalFileSystemControlParcel = os::incremental::IncrementalFileSystemControlParcel;
Songchun Fan3c82a302019-11-29 14:23:45 -080055
56struct Constants {
57 static constexpr auto backing = "backing_store"sv;
58 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080059 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080060 static constexpr auto storagePrefix = "st"sv;
61 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
62 static constexpr auto infoMdName = ".info"sv;
Alex Buynytskyy04035452020-06-06 20:15:58 -070063 static constexpr auto readLogsDisabledMarkerName = ".readlogs_disabled"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080064 static constexpr auto libDir = "lib"sv;
65 static constexpr auto libSuffix = ".so"sv;
66 static constexpr auto blockSize = 4096;
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -070067 static constexpr auto systemPackage = "android"sv;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -080068
Alex Buynytskyy060c9d62021-02-18 20:55:17 -080069 static constexpr auto userStatusDelay = 100ms;
70
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -080071 static constexpr auto progressUpdateInterval = 1000ms;
72 static constexpr auto perUidTimeoutOffset = progressUpdateInterval * 2;
73 static constexpr auto minPerUidTimeout = progressUpdateInterval * 3;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080074
75 // If DL was up and not crashing for 10mins, we consider it healthy and reset all delays.
76 static constexpr auto healthyDataLoaderUptime = 10min;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -080077
78 // For healthy DLs, we'll retry every ~5secs for ~10min
79 static constexpr auto bindRetryInterval = 5s;
80 static constexpr auto bindGracePeriod = 10min;
81
82 static constexpr auto bindingTimeout = 1min;
83
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080084 // 10s, 100s (~2min), 1000s (~15min), 10000s (~3hrs)
85 static constexpr auto minBindDelay = 10s;
86 static constexpr auto maxBindDelay = 10000s;
87 static constexpr auto bindDelayMultiplier = 10;
88 static constexpr auto bindDelayJitterDivider = 10;
Songchun Fan3c82a302019-11-29 14:23:45 -080089};
90
91static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070092 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080093 return c;
94}
95
96template <base::LogSeverity level = base::ERROR>
97bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
98 auto cstr = path::c_str(name);
99 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800100 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800101 PLOG(level) << "Can't create directory '" << name << '\'';
102 return false;
103 }
104 struct stat st;
105 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
106 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
107 return false;
108 }
109 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800110 if (::chmod(cstr, mode)) {
111 PLOG(level) << "Changing permission failed for '" << name << '\'';
112 return false;
113 }
114
Songchun Fan3c82a302019-11-29 14:23:45 -0800115 return true;
116}
117
118static std::string toMountKey(std::string_view path) {
119 if (path.empty()) {
120 return "@none";
121 }
122 if (path == "/"sv) {
123 return "@root";
124 }
125 if (path::isAbsolute(path)) {
126 path.remove_prefix(1);
127 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700128 if (path.size() > 16) {
129 path = path.substr(0, 16);
130 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800131 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700132 std::replace_if(
133 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
134 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800135}
136
137static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
138 std::string_view path) {
139 auto mountKey = toMountKey(path);
140 const auto prefixSize = mountKey.size();
141 for (int counter = 0; counter < 1000;
142 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
143 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800144 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800145 return {mountKey, mountRoot};
146 }
147 }
148 return {};
149}
150
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700151template <class Map>
152typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
153 const auto nextIt = map.upper_bound(path);
154 if (nextIt == map.begin()) {
155 return map.end();
156 }
157 const auto suspectIt = std::prev(nextIt);
158 if (!path::startsWith(path, suspectIt->first)) {
159 return map.end();
160 }
161 return suspectIt;
162}
163
164static base::unique_fd dup(base::borrowed_fd fd) {
165 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
166 return base::unique_fd(res);
167}
168
Songchun Fan3c82a302019-11-29 14:23:45 -0800169template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700170static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800171 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800172 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800173 ProtoMessage message;
174 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
175}
176
177static bool isValidMountTarget(std::string_view path) {
178 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
179}
180
181std::string makeBindMdName() {
182 static constexpr auto uuidStringSize = 36;
183
184 uuid_t guid;
185 uuid_generate(guid);
186
187 std::string name;
188 const auto prefixSize = constants().mountpointMdPrefix.size();
189 name.reserve(prefixSize + uuidStringSize);
190
191 name = constants().mountpointMdPrefix;
192 name.resize(prefixSize + uuidStringSize);
193 uuid_unparse(guid, name.data() + prefixSize);
194
195 return name;
196}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700197
198static bool checkReadLogsDisabledMarker(std::string_view root) {
199 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
200 struct stat st;
201 return (::stat(markerPath, &st) == 0);
202}
203
Songchun Fan3c82a302019-11-29 14:23:45 -0800204} // namespace
205
206IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700207 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700208 dataLoaderStub->cleanupResources();
209 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700210 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700211 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800212 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
213 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700214 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800215 incrementalService.mVold->unmountIncFs(target);
216 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700217 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800218 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
219 cleanupFilesystem(root);
220}
221
222auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800223 std::string name;
224 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
225 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
226 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800227 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
228 constants().storagePrefix.data(), id, no);
229 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800230 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800231 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800232 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
233 } else if (err != EEXIST) {
234 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
235 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800236 }
237 }
238 nextStorageDirNo = 0;
239 return storages.end();
240}
241
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700242template <class Func>
243static auto makeCleanup(Func&& f) {
244 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700245 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700246 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
247}
248
249static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
250 return {::opendir(dir), ::closedir};
251}
252
253static auto openDir(std::string_view dir) {
254 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800255}
256
257static int rmDirContent(const char* path) {
258 auto dir = openDir(path);
259 if (!dir) {
260 return -EINVAL;
261 }
262 while (auto entry = ::readdir(dir.get())) {
263 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
264 continue;
265 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700266 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800267 if (entry->d_type == DT_DIR) {
268 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
269 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
270 return err;
271 }
272 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
273 PLOG(WARNING) << "Failed to rmdir " << fullPath;
274 return err;
275 }
276 } else {
277 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
278 PLOG(WARNING) << "Failed to delete " << fullPath;
279 return err;
280 }
281 }
282 }
283 return 0;
284}
285
Songchun Fan3c82a302019-11-29 14:23:45 -0800286void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800287 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800288 ::rmdir(path::join(root, constants().backing).c_str());
289 ::rmdir(path::join(root, constants().mount).c_str());
290 ::rmdir(path::c_str(root));
291}
292
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800293IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800294 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800295 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800296 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700297 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700298 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700299 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700300 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700301 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700302 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800303 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800304 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700305 CHECK(mVold) << "Vold service is unavailable";
306 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
307 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
308 CHECK(mJni) << "JNI is unavailable";
309 CHECK(mLooper) << "Looper is unavailable";
310 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700311 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700312 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800313 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700314
315 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700316 mJobProcessor = std::thread([this]() {
317 mJni->initializeForCurrentThread();
318 runJobProcessing();
319 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700320 mCmdLooperThread = std::thread([this]() {
321 mJni->initializeForCurrentThread();
322 runCmdLooper();
323 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700324
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700325 const auto mountedRootNames = adoptMountedInstances();
326 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800327}
328
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700329IncrementalService::~IncrementalService() {
330 {
331 std::lock_guard lock(mJobMutex);
332 mRunning = false;
333 }
334 mJobCondition.notify_all();
335 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700336 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700337 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700338 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700339 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700340 // Ensure that mounts are destroyed while the service is still valid.
341 mBindsByPath.clear();
342 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700343}
Songchun Fan3c82a302019-11-29 14:23:45 -0800344
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700345static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800346 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800347 case IncrementalService::BindKind::Temporary:
348 return "Temporary";
349 case IncrementalService::BindKind::Permanent:
350 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800351 }
352}
353
354void IncrementalService::onDump(int fd) {
355 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
356 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
357
358 std::unique_lock l(mLock);
359
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700360 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800361 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700362 const IncFsMount& mnt = *ifs;
363 dprintf(fd, " [%d]: {\n", id);
364 if (id != mnt.mountId) {
365 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
366 } else {
367 dprintf(fd, " mountId: %d\n", mnt.mountId);
368 dprintf(fd, " root: %s\n", mnt.root.c_str());
369 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
370 if (mnt.dataLoaderStub) {
371 mnt.dataLoaderStub->onDump(fd);
372 } else {
373 dprintf(fd, " dataLoader: null\n");
374 }
375 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
376 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700377 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800378 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str(),
379 /*stopOnFirstIncomplete=*/false)
380 .getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800381 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700382 }
383 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800384
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700385 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
386 for (auto&& [target, bind] : mnt.bindPoints) {
387 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
388 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
389 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
390 dprintf(fd, " kind: %s\n", toString(bind.kind));
391 }
392 dprintf(fd, " }\n");
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 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700396 dprintf(fd, "}\n");
397 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800398 for (auto&& [target, mountPairIt] : mBindsByPath) {
399 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700400 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
401 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
402 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
403 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800404 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700405 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800406}
407
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800408bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
409 if (ifs.dataLoaderStub->params().packageName == Constants::systemPackage) {
410 return true;
411 }
412
413 // Check all permanent binds.
414 for (auto&& [_, bindPoint] : ifs.bindPoints) {
415 if (bindPoint.kind != BindKind::Permanent) {
416 continue;
417 }
418 const auto progress = getLoadingProgressFromPath(ifs, bindPoint.sourceDir,
419 /*stopOnFirstIncomplete=*/true);
420 if (!progress.isError() && !progress.fullyLoaded()) {
421 LOG(INFO) << "Non system mount: [" << bindPoint.sourceDir
422 << "], partial progress: " << progress.getProgress() * 100 << "%";
423 return true;
424 }
425 }
426
427 return false;
428}
429
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700430void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800431 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700432 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800433 }
434
435 std::vector<IfsMountPtr> mounts;
436 {
437 std::lock_guard l(mLock);
438 mounts.reserve(mMounts.size());
439 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800440 if (ifs->mountId != id) {
441 continue;
442 }
443
444 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800445 mounts.push_back(ifs);
446 }
447 }
448 }
449
Alex Buynytskyy69941662020-04-11 21:40:37 -0700450 if (mounts.empty()) {
451 return;
452 }
453
Songchun Fan3c82a302019-11-29 14:23:45 -0800454 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700455 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800456 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700457 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800458 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800459 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800460}
461
462auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
463 for (;;) {
464 if (mNextId == kMaxStorageId) {
465 mNextId = 0;
466 }
467 auto id = ++mNextId;
468 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
469 if (inserted) {
470 return it;
471 }
472 }
473}
474
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800475StorageId IncrementalService::createStorage(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800476 std::string_view mountPoint, const content::pm::DataLoaderParamsParcel& dataLoaderParams,
477 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800478 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
479 if (!path::isAbsolute(mountPoint)) {
480 LOG(ERROR) << "path is not absolute: " << mountPoint;
481 return kInvalidStorageId;
482 }
483
484 auto mountNorm = path::normalize(mountPoint);
485 {
486 const auto id = findStorageId(mountNorm);
487 if (id != kInvalidStorageId) {
488 if (options & CreateOptions::OpenExisting) {
489 LOG(INFO) << "Opened existing storage " << id;
490 return id;
491 }
492 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
493 return kInvalidStorageId;
494 }
495 }
496
497 if (!(options & CreateOptions::CreateNew)) {
498 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
499 return kInvalidStorageId;
500 }
501
502 if (!path::isEmptyDir(mountNorm)) {
503 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
504 return kInvalidStorageId;
505 }
506 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
507 if (mountRoot.empty()) {
508 LOG(ERROR) << "Bad mount point";
509 return kInvalidStorageId;
510 }
511 // Make sure the code removes all crap it may create while still failing.
512 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
513 auto firstCleanupOnFailure =
514 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
515
516 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800517 const auto backing = path::join(mountRoot, constants().backing);
518 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800519 return kInvalidStorageId;
520 }
521
Songchun Fan3c82a302019-11-29 14:23:45 -0800522 IncFsMount::Control control;
523 {
524 std::lock_guard l(mMountOperationLock);
525 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800526
527 if (auto err = rmDirContent(backing.c_str())) {
528 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
529 return kInvalidStorageId;
530 }
531 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
532 return kInvalidStorageId;
533 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800534 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
535 return kInvalidStorageId;
536 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800537 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800538 if (!status.isOk()) {
539 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
540 return kInvalidStorageId;
541 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800542 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
543 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800544 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
545 return kInvalidStorageId;
546 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800547 int cmd = controlParcel.cmd.release().release();
548 int pendingReads = controlParcel.pendingReads.release().release();
549 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800550 int blocksWritten =
551 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
552 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800553 }
554
555 std::unique_lock l(mLock);
556 const auto mountIt = getStorageSlotLocked();
557 const auto mountId = mountIt->first;
558 l.unlock();
559
560 auto ifs =
561 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
562 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
563 // is the removal of the |ifs|.
564 firstCleanupOnFailure.release();
565
566 auto secondCleanup = [this, &l](auto itPtr) {
567 if (!l.owns_lock()) {
568 l.lock();
569 }
570 mMounts.erase(*itPtr);
571 };
572 auto secondCleanupOnFailure =
573 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
574
575 const auto storageIt = ifs->makeStorage(ifs->mountId);
576 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800577 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800578 return kInvalidStorageId;
579 }
580
581 {
582 metadata::Mount m;
583 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700584 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800585 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
586 m.mutable_loader()->set_class_name(dataLoaderParams.className);
587 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800588 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800589 if (auto err =
590 mIncFs->makeFile(ifs->control,
591 path::join(ifs->root, constants().mount,
592 constants().infoMdName),
593 0777, idFromMetadata(metadata),
594 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800595 LOG(ERROR) << "Saving mount metadata failed: " << -err;
596 return kInvalidStorageId;
597 }
598 }
599
600 const auto bk =
601 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800602 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
603 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800604 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800605 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800606 return kInvalidStorageId;
607 }
608
609 // Done here as well, all data structures are in good state.
610 secondCleanupOnFailure.release();
611
Songchun Fan3c82a302019-11-29 14:23:45 -0800612 mountIt->second = std::move(ifs);
613 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700614
Songchun Fan3c82a302019-11-29 14:23:45 -0800615 LOG(INFO) << "created storage " << mountId;
616 return mountId;
617}
618
619StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
620 StorageId linkedStorage,
621 IncrementalService::CreateOptions options) {
622 if (!isValidMountTarget(mountPoint)) {
623 LOG(ERROR) << "Mount point is invalid or missing";
624 return kInvalidStorageId;
625 }
626
627 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700628 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800629 if (!ifs) {
630 LOG(ERROR) << "Ifs unavailable";
631 return kInvalidStorageId;
632 }
633
634 const auto mountIt = getStorageSlotLocked();
635 const auto storageId = mountIt->first;
636 const auto storageIt = ifs->makeStorage(storageId);
637 if (storageIt == ifs->storages.end()) {
638 LOG(ERROR) << "Can't create a new storage";
639 mMounts.erase(mountIt);
640 return kInvalidStorageId;
641 }
642
643 l.unlock();
644
645 const auto bk =
646 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800647 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
648 std::string(storageIt->second.name), path::normalize(mountPoint),
649 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800650 err < 0) {
651 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700652 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
653 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800654 return kInvalidStorageId;
655 }
656
657 mountIt->second = ifs;
658 return storageId;
659}
660
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800661bool IncrementalService::startLoading(StorageId storage,
662 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
663 const DataLoaderStatusListener& statusListener,
664 StorageHealthCheckParams&& healthCheckParams,
665 const StorageHealthListener& healthListener,
666 const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
667 // Per Uid timeouts.
668 if (!perUidReadTimeouts.empty()) {
669 setUidReadTimeouts(storage, perUidReadTimeouts);
670 }
671
672 // Re-initialize DataLoader.
673 std::unique_lock l(mLock);
674 const auto ifs = getIfsLocked(storage);
675 if (!ifs) {
676 return false;
677 }
678 if (ifs->dataLoaderStub) {
679 ifs->dataLoaderStub->cleanupResources();
680 ifs->dataLoaderStub = {};
681 }
682 l.unlock();
683
684 // DataLoader.
685 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
686 std::move(healthCheckParams), &healthListener);
687 CHECK(dataLoaderStub);
688
689 return dataLoaderStub->requestStart();
690}
691
Songchun Fan3c82a302019-11-29 14:23:45 -0800692IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
693 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700694 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800695}
696
697StorageId IncrementalService::findStorageId(std::string_view path) const {
698 std::lock_guard l(mLock);
699 auto it = findStorageLocked(path);
700 if (it == mBindsByPath.end()) {
701 return kInvalidStorageId;
702 }
703 return it->second->second.storage;
704}
705
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800706void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700707 std::unique_lock l(mLock);
708 const auto ifs = getIfsLocked(storageId);
709 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800710 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700711 return;
712 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800713 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700714 return;
715 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800716 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700717 l.unlock();
718
719 const auto metadata = constants().readLogsDisabledMarkerName;
720 if (auto err = mIncFs->makeFile(ifs->control,
721 path::join(ifs->root, constants().mount,
722 constants().readLogsDisabledMarkerName),
723 0777, idFromMetadata(metadata), {})) {
724 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
725 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
726 return;
727 }
728
729 setStorageParams(storageId, /*enableReadLogs=*/false);
730}
731
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700732int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
733 const auto ifs = getIfs(storageId);
734 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700735 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700736 return -EINVAL;
737 }
738
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700739 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700740 if (enableReadLogs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800741 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700742 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
743 return -EPERM;
744 }
745
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800746 // Check loader usage stats permission and apop.
747 if (auto status = mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700748 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700749 !status.isOk()) {
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -0800750 LOG(ERROR) << " Permission: " << kLoaderUsageStats
751 << " check failed: " << status.toString8();
752 return fromBinderStatus(status);
753 }
754
755 // Check multiuser permission.
756 if (auto status = mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr,
757 params.packageName.c_str());
758 !status.isOk()) {
759 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
760 << " check failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700761 return fromBinderStatus(status);
762 }
763 }
764
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700765 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
766 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
767 return fromBinderStatus(status);
768 }
769
770 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700771 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700772 }
773
774 return 0;
775}
776
777binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700778 os::incremental::IncrementalFileSystemControlParcel control;
779 control.cmd.reset(dup(ifs.control.cmd()));
780 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700781 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700782 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700783 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700784 }
785
786 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800787 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
788 if (status.isOk()) {
789 // Store enabled state.
790 ifs.setReadLogsEnabled(enableReadLogs);
791 }
792 return status;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700793}
794
Songchun Fan3c82a302019-11-29 14:23:45 -0800795void IncrementalService::deleteStorage(StorageId storageId) {
796 const auto ifs = getIfs(storageId);
797 if (!ifs) {
798 return;
799 }
800 deleteStorage(*ifs);
801}
802
803void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
804 std::unique_lock l(ifs.lock);
805 deleteStorageLocked(ifs, std::move(l));
806}
807
808void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
809 std::unique_lock<std::mutex>&& ifsLock) {
810 const auto storages = std::move(ifs.storages);
811 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
812 const auto bindPoints = ifs.bindPoints;
813 ifsLock.unlock();
814
815 std::lock_guard l(mLock);
816 for (auto&& [id, _] : storages) {
817 if (id != ifs.mountId) {
818 mMounts.erase(id);
819 }
820 }
821 for (auto&& [path, _] : bindPoints) {
822 mBindsByPath.erase(path);
823 }
824 mMounts.erase(ifs.mountId);
825}
826
827StorageId IncrementalService::openStorage(std::string_view pathInMount) {
828 if (!path::isAbsolute(pathInMount)) {
829 return kInvalidStorageId;
830 }
831
832 return findStorageId(path::normalize(pathInMount));
833}
834
Songchun Fan3c82a302019-11-29 14:23:45 -0800835IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
836 std::lock_guard l(mLock);
837 return getIfsLocked(storage);
838}
839
840const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
841 auto it = mMounts.find(storage);
842 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700843 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700844 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800845 }
846 return it->second;
847}
848
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800849int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
850 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800851 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700852 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800853 return -EINVAL;
854 }
855
856 const auto ifs = getIfs(storage);
857 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700858 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800859 return -EINVAL;
860 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800861
Songchun Fan3c82a302019-11-29 14:23:45 -0800862 std::unique_lock l(ifs->lock);
863 const auto storageInfo = ifs->storages.find(storage);
864 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700865 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800866 return -EINVAL;
867 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700868 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700869 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700870 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700871 return -EINVAL;
872 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800873 l.unlock();
874 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800875 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
876 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800877}
878
879int IncrementalService::unbind(StorageId storage, std::string_view target) {
880 if (!path::isAbsolute(target)) {
881 return -EINVAL;
882 }
883
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700884 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800885
886 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
887 // otherwise there's a chance to unmount something completely unrelated
888 const auto norm = path::normalize(target);
889 std::unique_lock l(mLock);
890 const auto storageIt = mBindsByPath.find(norm);
891 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
892 return -EINVAL;
893 }
894 const auto bindIt = storageIt->second;
895 const auto storageId = bindIt->second.storage;
896 const auto ifs = getIfsLocked(storageId);
897 if (!ifs) {
898 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
899 << " is missing";
900 return -EFAULT;
901 }
902 mBindsByPath.erase(storageIt);
903 l.unlock();
904
905 mVold->unmountIncFs(bindIt->first);
906 std::unique_lock l2(ifs->lock);
907 if (ifs->bindPoints.size() <= 1) {
908 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700909 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800910 } else {
911 const std::string savedFile = std::move(bindIt->second.savedFilename);
912 ifs->bindPoints.erase(bindIt);
913 l2.unlock();
914 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800915 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800916 }
917 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700918
Songchun Fan3c82a302019-11-29 14:23:45 -0800919 return 0;
920}
921
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700922std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700923 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700924 std::string_view path) const {
925 if (!path::isAbsolute(path)) {
926 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700927 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700928 auto normPath = path::normalize(path);
929 if (path::startsWith(normPath, storageIt->second.name)) {
930 return normPath;
931 }
932 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700933 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
934 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700935 return {};
936 }
937 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700938}
939
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700940std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700941 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700942 std::unique_lock l(ifs.lock);
943 const auto storageInfo = ifs.storages.find(storage);
944 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800945 return {};
946 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700947 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800948}
949
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800950int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700951 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800952 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700953 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800954 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700955 LOG(ERROR) << "Internal error: storageId " << storage
956 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800957 return -EINVAL;
958 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700959 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700960 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800961 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800962 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700963 if (!data.empty()) {
964 if (auto err = setFileContent(ifs, id, path, data); err) {
965 return err;
966 }
967 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800968 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800969 }
970 return -EINVAL;
971}
972
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800973int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800974 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700975 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800976 if (normPath.empty()) {
977 return -EINVAL;
978 }
979 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800980 }
981 return -EINVAL;
982}
983
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800984int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800985 const auto ifs = getIfs(storageId);
986 if (!ifs) {
987 return -EINVAL;
988 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700989 return makeDirs(*ifs, storageId, path, mode);
990}
991
992int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
993 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800994 std::string normPath = normalizePathToStorage(ifs, storageId, path);
995 if (normPath.empty()) {
996 return -EINVAL;
997 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700998 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800999}
1000
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001001int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1002 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001003 std::unique_lock l(mLock);
1004 auto ifsSrc = getIfsLocked(sourceStorageId);
1005 if (!ifsSrc) {
1006 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001007 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001008 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1009 return -EINVAL;
1010 }
1011 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001012 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1013 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001014 if (normOldPath.empty() || normNewPath.empty()) {
1015 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1016 return -EINVAL;
1017 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001018 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1019 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1020 << " to " << newPath << "[" << normNewPath << "]";
1021 return err;
1022 }
1023 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001024}
1025
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001026int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001027 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001028 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001029 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001030 }
1031 return -EINVAL;
1032}
1033
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001034int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1035 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001036 std::string&& target, BindKind kind,
1037 std::unique_lock<std::mutex>& mainLock) {
1038 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001039 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001040 return -EINVAL;
1041 }
1042
1043 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001044 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001045 if (kind != BindKind::Temporary) {
1046 metadata::BindPoint bp;
1047 bp.set_storage_id(storage);
1048 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001049 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001050 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001051 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001052 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001053 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001054 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1055 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1056 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001057 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001058 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001059 return int(node);
1060 }
1061 }
1062
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001063 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1064 std::move(target), kind, mainLock);
1065 if (res) {
1066 mIncFs->unlink(ifs.control, metadataFullPath);
1067 }
1068 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001069}
1070
1071int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001072 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001073 std::string&& target, BindKind kind,
1074 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001075 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001076 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001077 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001078 if (!status.isOk()) {
1079 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1080 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1081 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1082 : status.serviceSpecificErrorCode() == 0
1083 ? -EFAULT
1084 : status.serviceSpecificErrorCode()
1085 : -EIO;
1086 }
1087 }
1088
1089 if (!mainLock.owns_lock()) {
1090 mainLock.lock();
1091 }
1092 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001093 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1094 std::move(target), kind);
1095 return 0;
1096}
1097
1098void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1099 std::string&& metadataName, std::string&& source,
1100 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001101 const auto [it, _] =
1102 ifs.bindPoints.insert_or_assign(target,
1103 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001104 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001105 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001106}
1107
1108RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1109 const auto ifs = getIfs(storage);
1110 if (!ifs) {
1111 return {};
1112 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001113 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001114 if (normPath.empty()) {
1115 return {};
1116 }
1117 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001118}
1119
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001120RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001121 const auto ifs = getIfs(storage);
1122 if (!ifs) {
1123 return {};
1124 }
1125 return mIncFs->getMetadata(ifs->control, node);
1126}
1127
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001128void IncrementalService::setUidReadTimeouts(
1129 StorageId storage, const std::vector<PerUidReadTimeouts>& perUidReadTimeouts) {
1130 using microseconds = std::chrono::microseconds;
1131 using milliseconds = std::chrono::milliseconds;
1132
1133 auto maxPendingTimeUs = microseconds(0);
1134 for (const auto& timeouts : perUidReadTimeouts) {
1135 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1136 }
1137 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001138 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001139 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1140 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001141 return;
1142 }
1143
1144 const auto ifs = getIfs(storage);
1145 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001146 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001147 return;
1148 }
1149
1150 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1151 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1152 return;
1153 }
1154
1155 const auto timeout = std::chrono::duration_cast<milliseconds>(maxPendingTimeUs) -
1156 Constants::perUidTimeoutOffset;
1157 updateUidReadTimeouts(storage, Clock::now() + timeout);
1158}
1159
1160void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1161 const auto ifs = getIfs(storage);
1162 if (!ifs) {
1163 return;
1164 }
1165
1166 mIncFs->setUidReadTimeouts(ifs->control, {});
1167}
1168
1169void IncrementalService::updateUidReadTimeouts(StorageId storage, Clock::time_point timeLimit) {
1170 // Reached maximum timeout.
1171 if (Clock::now() >= timeLimit) {
1172 return clearUidReadTimeouts(storage);
1173 }
1174
1175 // Still loading?
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001176 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/true);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001177 if (progress.isError()) {
1178 // Something is wrong, abort.
1179 return clearUidReadTimeouts(storage);
1180 }
1181
1182 if (progress.started() && progress.fullyLoaded()) {
1183 // Fully loaded, check readLogs collection.
1184 const auto ifs = getIfs(storage);
1185 if (!ifs->readLogsEnabled()) {
1186 return clearUidReadTimeouts(storage);
1187 }
1188 }
1189
1190 const auto timeLeft = timeLimit - Clock::now();
1191 if (timeLeft < Constants::progressUpdateInterval) {
1192 // Don't bother.
1193 return clearUidReadTimeouts(storage);
1194 }
1195
1196 addTimedJob(*mTimedQueue, storage, Constants::progressUpdateInterval,
1197 [this, storage, timeLimit]() { updateUidReadTimeouts(storage, timeLimit); });
1198}
1199
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001200std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1201 std::unordered_set<std::string_view> mountedRootNames;
1202 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1203 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1204 for (auto [source, target] : binds) {
1205 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1206 LOG(INFO) << " " << path::join(root, source);
1207 }
1208
1209 // Ensure it's a kind of a mount that's managed by IncrementalService
1210 if (path::basename(root) != constants().mount ||
1211 path::basename(backingDir) != constants().backing) {
1212 return;
1213 }
1214 const auto expectedRoot = path::dirname(root);
1215 if (path::dirname(backingDir) != expectedRoot) {
1216 return;
1217 }
1218 if (path::dirname(expectedRoot) != mIncrementalDir) {
1219 return;
1220 }
1221 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1222 return;
1223 }
1224
1225 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1226
1227 // make sure we clean up the mount if it happens to be a bad one.
1228 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1229 auto cleanupFiles = makeCleanup([&]() {
1230 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1231 IncFsMount::cleanupFilesystem(expectedRoot);
1232 });
1233 auto cleanupMounts = makeCleanup([&]() {
1234 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1235 for (auto&& [_, target] : binds) {
1236 mVold->unmountIncFs(std::string(target));
1237 }
1238 mVold->unmountIncFs(std::string(root));
1239 });
1240
1241 auto control = mIncFs->openMount(root);
1242 if (!control) {
1243 LOG(INFO) << "failed to open mount " << root;
1244 return;
1245 }
1246
1247 auto mountRecord =
1248 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1249 path::join(root, constants().infoMdName));
1250 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1251 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1252 return;
1253 }
1254
1255 auto mountId = mountRecord.storage().id();
1256 mNextId = std::max(mNextId, mountId + 1);
1257
1258 DataLoaderParamsParcel dataLoaderParams;
1259 {
1260 const auto& loader = mountRecord.loader();
1261 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1262 dataLoaderParams.packageName = loader.package_name();
1263 dataLoaderParams.className = loader.class_name();
1264 dataLoaderParams.arguments = loader.arguments();
1265 }
1266
1267 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1268 std::move(control), *this);
1269 cleanupFiles.release(); // ifs will take care of that now
1270
Alex Buynytskyy04035452020-06-06 20:15:58 -07001271 // Check if marker file present.
1272 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001273 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001274 }
1275
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001276 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1277 auto d = openDir(root);
1278 while (auto e = ::readdir(d.get())) {
1279 if (e->d_type == DT_REG) {
1280 auto name = std::string_view(e->d_name);
1281 if (name.starts_with(constants().mountpointMdPrefix)) {
1282 permanentBindPoints
1283 .emplace_back(name,
1284 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1285 ifs->control,
1286 path::join(root,
1287 name)));
1288 if (permanentBindPoints.back().second.dest_path().empty() ||
1289 permanentBindPoints.back().second.source_subdir().empty()) {
1290 permanentBindPoints.pop_back();
1291 mIncFs->unlink(ifs->control, path::join(root, name));
1292 } else {
1293 LOG(INFO) << "Permanent bind record: '"
1294 << permanentBindPoints.back().second.source_subdir() << "'->'"
1295 << permanentBindPoints.back().second.dest_path() << "'";
1296 }
1297 }
1298 } else if (e->d_type == DT_DIR) {
1299 if (e->d_name == "."sv || e->d_name == ".."sv) {
1300 continue;
1301 }
1302 auto name = std::string_view(e->d_name);
1303 if (name.starts_with(constants().storagePrefix)) {
1304 int storageId;
1305 const auto res =
1306 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1307 name.data() + name.size(), storageId);
1308 if (res.ec != std::errc{} || *res.ptr != '_') {
1309 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1310 << "' for mount " << expectedRoot;
1311 continue;
1312 }
1313 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1314 if (!inserted) {
1315 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1316 << " for mount " << expectedRoot;
1317 continue;
1318 }
1319 ifs->storages.insert_or_assign(storageId,
1320 IncFsMount::Storage{path::join(root, name)});
1321 mNextId = std::max(mNextId, storageId + 1);
1322 }
1323 }
1324 }
1325
1326 if (ifs->storages.empty()) {
1327 LOG(WARNING) << "No valid storages in mount " << root;
1328 return;
1329 }
1330
1331 // now match the mounted directories with what we expect to have in the metadata
1332 {
1333 std::unique_lock l(mLock, std::defer_lock);
1334 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1335 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1336 [&, bindRecord = bindRecord](auto&& bind) {
1337 return bind.second == bindRecord.dest_path() &&
1338 path::join(root, bind.first) ==
1339 bindRecord.source_subdir();
1340 });
1341 if (mountedIt != binds.end()) {
1342 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1343 << " to mount " << mountedIt->first;
1344 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1345 std::move(*bindRecord.mutable_source_subdir()),
1346 std::move(*bindRecord.mutable_dest_path()),
1347 BindKind::Permanent);
1348 if (mountedIt != binds.end() - 1) {
1349 std::iter_swap(mountedIt, binds.end() - 1);
1350 }
1351 binds = binds.first(binds.size() - 1);
1352 } else {
1353 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1354 << ", mounting";
1355 // doesn't exist - try mounting back
1356 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1357 std::move(*bindRecord.mutable_source_subdir()),
1358 std::move(*bindRecord.mutable_dest_path()),
1359 BindKind::Permanent, l)) {
1360 mIncFs->unlink(ifs->control, metadataFile);
1361 }
1362 }
1363 }
1364 }
1365
1366 // if anything stays in |binds| those are probably temporary binds; system restarted since
1367 // they were mounted - so let's unmount them all.
1368 for (auto&& [source, target] : binds) {
1369 if (source.empty()) {
1370 continue;
1371 }
1372 mVold->unmountIncFs(std::string(target));
1373 }
1374 cleanupMounts.release(); // ifs now manages everything
1375
1376 if (ifs->bindPoints.empty()) {
1377 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1378 deleteStorage(*ifs);
1379 return;
1380 }
1381
1382 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1383 CHECK(ifs->dataLoaderStub);
1384
1385 mountedRootNames.insert(path::basename(ifs->root));
1386
1387 // not locking here at all: we're still in the constructor, no other calls can happen
1388 mMounts[ifs->mountId] = std::move(ifs);
1389 });
1390
1391 return mountedRootNames;
1392}
1393
1394void IncrementalService::mountExistingImages(
1395 const std::unordered_set<std::string_view>& mountedRootNames) {
1396 auto dir = openDir(mIncrementalDir);
1397 if (!dir) {
1398 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1399 return;
1400 }
1401 while (auto entry = ::readdir(dir.get())) {
1402 if (entry->d_type != DT_DIR) {
1403 continue;
1404 }
1405 std::string_view name = entry->d_name;
1406 if (!name.starts_with(constants().mountKeyPrefix)) {
1407 continue;
1408 }
1409 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001410 continue;
1411 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001412 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001413 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001414 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001415 }
1416 }
1417}
1418
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001419bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001420 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001421 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001422
Songchun Fan3c82a302019-11-29 14:23:45 -08001423 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001424 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001425 if (!status.isOk()) {
1426 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1427 return false;
1428 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001429
1430 int cmd = controlParcel.cmd.release().release();
1431 int pendingReads = controlParcel.pendingReads.release().release();
1432 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001433 int blocksWritten =
1434 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1435 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001436
1437 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1438
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001439 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1440 path::join(mountTarget, constants().infoMdName));
1441 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001442 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1443 return false;
1444 }
1445
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001446 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001447 mNextId = std::max(mNextId, ifs->mountId + 1);
1448
Alex Buynytskyy04035452020-06-06 20:15:58 -07001449 // Check if marker file present.
1450 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001451 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001452 }
1453
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001454 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001455 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001456 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001457 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001458 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001459 dataLoaderParams.packageName = loader.package_name();
1460 dataLoaderParams.className = loader.class_name();
1461 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001462 }
1463
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001464 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001465 CHECK(ifs->dataLoaderStub);
1466
Songchun Fan3c82a302019-11-29 14:23:45 -08001467 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001468 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001469 while (auto e = ::readdir(d.get())) {
1470 if (e->d_type == DT_REG) {
1471 auto name = std::string_view(e->d_name);
1472 if (name.starts_with(constants().mountpointMdPrefix)) {
1473 bindPoints.emplace_back(name,
1474 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1475 ifs->control,
1476 path::join(mountTarget,
1477 name)));
1478 if (bindPoints.back().second.dest_path().empty() ||
1479 bindPoints.back().second.source_subdir().empty()) {
1480 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001481 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001482 }
1483 }
1484 } else if (e->d_type == DT_DIR) {
1485 if (e->d_name == "."sv || e->d_name == ".."sv) {
1486 continue;
1487 }
1488 auto name = std::string_view(e->d_name);
1489 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001490 int storageId;
1491 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1492 name.data() + name.size(), storageId);
1493 if (res.ec != std::errc{} || *res.ptr != '_') {
1494 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1495 << root;
1496 continue;
1497 }
1498 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001499 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001500 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001501 << " for mount " << root;
1502 continue;
1503 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001504 ifs->storages.insert_or_assign(storageId,
1505 IncFsMount::Storage{
1506 path::join(root, constants().mount, name)});
1507 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001508 }
1509 }
1510 }
1511
1512 if (ifs->storages.empty()) {
1513 LOG(WARNING) << "No valid storages in mount " << root;
1514 return false;
1515 }
1516
1517 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001518 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001519 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001520 for (auto&& bp : bindPoints) {
1521 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1522 std::move(*bp.second.mutable_source_subdir()),
1523 std::move(*bp.second.mutable_dest_path()),
1524 BindKind::Permanent, l);
1525 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001526 }
1527
1528 if (bindCount == 0) {
1529 LOG(WARNING) << "No valid bind points for mount " << root;
1530 deleteStorage(*ifs);
1531 return false;
1532 }
1533
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001534 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001535 mMounts[ifs->mountId] = std::move(ifs);
1536 return true;
1537}
1538
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001539void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001540 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001541 while (mRunning.load(std::memory_order_relaxed)) {
1542 mLooper->pollAll(kTimeoutMsecs);
1543 }
1544}
1545
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001546IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001547 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001548 const DataLoaderStatusListener* statusListener,
1549 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001550 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001551 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1552 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001553 return ifs.dataLoaderStub;
1554}
1555
1556void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001557 const DataLoaderStatusListener* statusListener,
1558 StorageHealthCheckParams&& healthCheckParams,
1559 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001560 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001561 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001562 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001563 }
1564
Songchun Fan3c82a302019-11-29 14:23:45 -08001565 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001566 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001567 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1568 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1569 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001570 if (ifs.control.blocksWritten() >= 0) {
1571 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1572 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001573 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001574
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001575 ifs.dataLoaderStub =
1576 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001577 statusListener, std::move(healthCheckParams), healthListener,
1578 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001579}
1580
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001581template <class Duration>
1582static long elapsedMcs(Duration start, Duration end) {
1583 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1584}
1585
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001586template <class Duration>
1587static constexpr auto castToMs(Duration d) {
1588 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1589}
1590
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001591// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001592// Lib files should be placed next to the APK file in the following matter:
1593// Example:
1594// /path/to/base.apk
1595// /path/to/lib/arm/first.so
1596// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001597bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1598 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001599 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001600 auto start = Clock::now();
1601
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001602 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001603 if (!ifs) {
1604 LOG(ERROR) << "Invalid storage " << storage;
1605 return false;
1606 }
1607
Songchun Fanc8975312020-07-13 12:14:37 -07001608 const auto targetLibPathRelativeToStorage =
1609 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1610 libDirRelativePath);
1611
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001612 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001613 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1614 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001615 << " errno: " << res;
1616 return false;
1617 }
1618
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001619 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001620 ZipArchiveHandle zipFileHandle;
1621 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001622 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1623 return false;
1624 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001625
1626 // Need a shared pointer: will be passing it into all unpacking jobs.
1627 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001628 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001629 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001630 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001631 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1632 return false;
1633 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001634 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001635 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1636
1637 auto openZipTs = Clock::now();
1638
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001639 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1640 incfs::FileId sourceId;
1641 if (mapFiles) {
1642 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1643 if (!incfs::isValidFileId(sourceId)) {
1644 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1645 << "', mapping disabled";
1646 mapFiles = false;
1647 }
1648 }
1649
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001650 std::vector<Job> jobQueue;
1651 ZipEntry entry;
1652 std::string_view fileName;
1653 while (!Next(cookie, &entry, &fileName)) {
1654 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001655 continue;
1656 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001657
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001658 const auto entryUncompressed = entry.method == kCompressStored;
1659 const auto entryPageAligned = (entry.offset & (constants().blockSize - 1)) == 0;
1660
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001661 if (!extractNativeLibs) {
1662 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001663 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001664 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1665 return false;
1666 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001667 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001668 LOG(WARNING) << "Library " << fileName
1669 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1670 << entry.offset;
1671 return false;
1672 }
1673 continue;
1674 }
1675
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001676 auto startFileTs = Clock::now();
1677
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001678 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001679 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001680 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001681 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001682 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001683 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001684 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1685 << "; skipping extraction, spent "
1686 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1687 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001688 continue;
1689 }
1690
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001691 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1692 incfs::NewMappedFileParams mappedFileParams = {
1693 .sourceId = sourceId,
1694 .sourceOffset = entry.offset,
1695 .size = entry.uncompressed_length,
1696 };
1697
1698 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1699 mappedFileParams);
1700 res == 0) {
1701 if (perfLoggingEnabled()) {
1702 auto doneTs = Clock::now();
1703 LOG(INFO) << "incfs: Mapped " << libName << ": "
1704 << elapsedMcs(startFileTs, doneTs) << "mcs";
1705 }
1706 continue;
1707 } else {
1708 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1709 << "; falling back to full extraction";
1710 }
1711 }
1712
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001713 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001714 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001715 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001716 .signature = {},
1717 // Metadata of the new lib file is its relative path
1718 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1719 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001720 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001721 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001722 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001723 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001724 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001725 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001726 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001727
1728 auto makeFileTs = Clock::now();
1729
Songchun Fanafaf6e92020-03-18 14:12:20 -07001730 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001731 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001732 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001733 LOG(INFO) << "incfs: Extracted " << libName
1734 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001735 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001736 continue;
1737 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001738
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001739 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1740 libFileId, libPath = std::move(targetLibPath),
1741 makeFileTs]() mutable {
1742 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001743 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001744
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001745 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001746 auto prepareJobTs = Clock::now();
1747 LOG(INFO) << "incfs: Processed " << libName << ": "
1748 << elapsedMcs(startFileTs, prepareJobTs)
1749 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1750 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001751 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001752 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001753
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001754 auto processedTs = Clock::now();
1755
1756 if (!jobQueue.empty()) {
1757 {
1758 std::lock_guard lock(mJobMutex);
1759 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001760 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001761 if (existingJobs.empty()) {
1762 existingJobs = std::move(jobQueue);
1763 } else {
1764 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1765 std::move_iterator(jobQueue.end()));
1766 }
1767 }
1768 }
1769 mJobCondition.notify_all();
1770 }
1771
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001772 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001773 auto end = Clock::now();
1774 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1775 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1776 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001777 << " make files: " << elapsedMcs(openZipTs, processedTs)
1778 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001779 }
1780
1781 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001782}
1783
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001784void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1785 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001786 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001787 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001788 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001789 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001790 return;
1791 }
1792
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001793 auto startedTs = Clock::now();
1794
1795 // Write extracted data to new file
1796 // NOTE: don't zero-initialize memory, it may take a while for nothing
1797 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1798 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001799 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001800 return;
1801 }
1802
1803 auto extractFileTs = Clock::now();
1804
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001805 if (setFileContent(ifs, libFileId, debugLibPath,
1806 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001807 return;
1808 }
1809
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001810 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001811 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001812 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1813 << entry.compressed_length << " -> " << entry.uncompressed_length
1814 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001815 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1816 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001817 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001818 }
1819}
1820
1821bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001822 struct WaitPrinter {
1823 const Clock::time_point startTs = Clock::now();
1824 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001825 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001826 const auto endTs = Clock::now();
1827 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1828 << elapsedMcs(startTs, endTs) << "mcs";
1829 }
1830 }
1831 } waitPrinter;
1832
1833 MountId mount;
1834 {
1835 auto ifs = getIfs(storage);
1836 if (!ifs) {
1837 return true;
1838 }
1839 mount = ifs->mountId;
1840 }
1841
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001842 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001843 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001844 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001845 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001846 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001847 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001848}
1849
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001850int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1851 std::string_view debugFilePath,
1852 std::span<const uint8_t> data) const {
1853 auto startTs = Clock::now();
1854
1855 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1856 if (!writeFd.ok()) {
1857 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1858 << " errno: " << writeFd.get();
1859 return writeFd.get();
1860 }
1861
1862 const auto dataLength = data.size();
1863
1864 auto openFileTs = Clock::now();
1865 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1866 std::vector<IncFsDataBlock> instructions(numBlocks);
1867 for (int i = 0; i < numBlocks; i++) {
1868 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1869 instructions[i] = IncFsDataBlock{
1870 .fileFd = writeFd.get(),
1871 .pageIndex = static_cast<IncFsBlockIndex>(i),
1872 .compression = INCFS_COMPRESSION_KIND_NONE,
1873 .kind = INCFS_BLOCK_KIND_DATA,
1874 .dataSize = static_cast<uint32_t>(blockSize),
1875 .data = reinterpret_cast<const char*>(data.data()),
1876 };
1877 data = data.subspan(blockSize);
1878 }
1879 auto prepareInstsTs = Clock::now();
1880
1881 size_t res = mIncFs->writeBlocks(instructions);
1882 if (res != instructions.size()) {
1883 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1884 return res;
1885 }
1886
1887 if (perfLoggingEnabled()) {
1888 auto endTs = Clock::now();
1889 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1890 << " bytes): " << elapsedMcs(startTs, endTs)
1891 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1892 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1893 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1894 }
1895
1896 return 0;
1897}
1898
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001899int IncrementalService::isFileFullyLoaded(StorageId storage, std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001900 std::unique_lock l(mLock);
1901 const auto ifs = getIfsLocked(storage);
1902 if (!ifs) {
1903 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1904 return -EINVAL;
1905 }
1906 const auto storageInfo = ifs->storages.find(storage);
1907 if (storageInfo == ifs->storages.end()) {
1908 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1909 return -EINVAL;
1910 }
1911 l.unlock();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001912 return isFileFullyLoadedFromPath(*ifs, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001913}
1914
1915int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1916 std::string_view filePath) const {
1917 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1918 if (filledBlocks < 0) {
1919 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1920 << filePath << " errno: " << filledBlocks;
1921 return filledBlocks;
1922 }
1923 if (totalBlocks < filledBlocks) {
1924 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1925 return -EINVAL;
1926 }
1927 return totalBlocks - filledBlocks;
1928}
1929
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001930IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001931 StorageId storage, bool stopOnFirstIncomplete) const {
Songchun Fan374f7652020-08-20 08:40:29 -07001932 std::unique_lock l(mLock);
1933 const auto ifs = getIfsLocked(storage);
1934 if (!ifs) {
1935 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001936 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001937 }
1938 const auto storageInfo = ifs->storages.find(storage);
1939 if (storageInfo == ifs->storages.end()) {
1940 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001941 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07001942 }
1943 l.unlock();
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001944 return getLoadingProgressFromPath(*ifs, storageInfo->second.name, stopOnFirstIncomplete);
Songchun Fan374f7652020-08-20 08:40:29 -07001945}
1946
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001947IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001948 const IncFsMount& ifs, std::string_view storagePath,
1949 const bool stopOnFirstIncomplete) const {
1950 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
1951 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07001952 const auto [filledBlocksCount, totalBlocksCount] =
1953 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001954 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
1955 filledBlocksCount == -ENOENT) {
1956 // a kind of a file that's not really being loaded, e.g. a mapped range
1957 // an older IncFS used to return ENOENT in this case, so handle it the same way
1958 return true;
1959 }
Songchun Fan374f7652020-08-20 08:40:29 -07001960 if (filledBlocksCount < 0) {
1961 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1962 << " errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001963 error = filledBlocksCount;
1964 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07001965 }
1966 totalBlocks += totalBlocksCount;
1967 filledBlocks += filledBlocksCount;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001968 if (stopOnFirstIncomplete && filledBlocks < totalBlocks) {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001969 return false;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001970 }
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001971 return true;
1972 });
Songchun Fan374f7652020-08-20 08:40:29 -07001973
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08001974 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07001975}
1976
Songchun Fana7098592020-09-03 11:45:53 -07001977bool IncrementalService::updateLoadingProgress(
1978 StorageId storage, const StorageLoadingProgressListener& progressListener) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001979 const auto progress = getLoadingProgress(storage, /*stopOnFirstIncomplete=*/false);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001980 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07001981 // Failed to get progress from incfs, abort.
1982 return false;
1983 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001984 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
1985 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07001986 // Stop updating progress once it is fully loaded
1987 return true;
1988 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001989 addTimedJob(*mProgressUpdateJobQueue, storage,
1990 Constants::progressUpdateInterval /* repeat after 1s */,
Songchun Fana7098592020-09-03 11:45:53 -07001991 [storage, progressListener, this]() {
1992 updateLoadingProgress(storage, progressListener);
1993 });
1994 return true;
1995}
1996
1997bool IncrementalService::registerLoadingProgressListener(
1998 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1999 return updateLoadingProgress(storage, progressListener);
2000}
2001
2002bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2003 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2004}
2005
Songchun Fan2570ec02020-10-08 17:22:33 -07002006bool IncrementalService::registerStorageHealthListener(
2007 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
2008 const StorageHealthListener& healthListener) {
2009 DataLoaderStubPtr dataLoaderStub;
2010 {
2011 std::unique_lock l(mLock);
2012 const auto& ifs = getIfsLocked(storage);
2013 if (!ifs) {
2014 return false;
2015 }
2016 dataLoaderStub = ifs->dataLoaderStub;
2017 if (!dataLoaderStub) {
2018 return false;
2019 }
2020 }
2021 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
2022 return true;
2023}
2024
2025void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
2026 StorageHealthCheckParams invalidCheckParams;
2027 invalidCheckParams.blockedTimeoutMs = -1;
2028 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
2029}
2030
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002031bool IncrementalService::perfLoggingEnabled() {
2032 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2033 return enabled;
2034}
2035
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002036void IncrementalService::runJobProcessing() {
2037 for (;;) {
2038 std::unique_lock lock(mJobMutex);
2039 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2040 if (!mRunning) {
2041 return;
2042 }
2043
2044 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002045 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002046 auto queue = std::move(it->second);
2047 mJobQueue.erase(it);
2048 lock.unlock();
2049
2050 for (auto&& job : queue) {
2051 job();
2052 }
2053
2054 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002055 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002056 lock.unlock();
2057 mJobCondition.notify_all();
2058 }
2059}
2060
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002061void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002062 sp<IAppOpsCallback> listener;
2063 {
2064 std::unique_lock lock{mCallbacksLock};
2065 auto& cb = mCallbackRegistered[packageName];
2066 if (cb) {
2067 return;
2068 }
2069 cb = new AppOpsListener(*this, packageName);
2070 listener = cb;
2071 }
2072
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002073 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2074 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002075}
2076
2077bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2078 sp<IAppOpsCallback> listener;
2079 {
2080 std::unique_lock lock{mCallbacksLock};
2081 auto found = mCallbackRegistered.find(packageName);
2082 if (found == mCallbackRegistered.end()) {
2083 return false;
2084 }
2085 listener = found->second;
2086 mCallbackRegistered.erase(found);
2087 }
2088
2089 mAppOpsManager->stopWatchingMode(listener);
2090 return true;
2091}
2092
2093void IncrementalService::onAppOpChanged(const std::string& packageName) {
2094 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002095 return;
2096 }
2097
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002098 std::vector<IfsMountPtr> affected;
2099 {
2100 std::lock_guard l(mLock);
2101 affected.reserve(mMounts.size());
2102 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002103 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002104 affected.push_back(ifs);
2105 }
2106 }
2107 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002108 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002109 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002110 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002111}
2112
Songchun Fana7098592020-09-03 11:45:53 -07002113bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2114 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002115 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002116 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002117 }
Songchun Fana7098592020-09-03 11:45:53 -07002118 timedQueue.addJob(id, after, std::move(what));
2119 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002120}
2121
Songchun Fana7098592020-09-03 11:45:53 -07002122bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002123 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002124 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002125 }
Songchun Fana7098592020-09-03 11:45:53 -07002126 timedQueue.removeJobs(id);
2127 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002128}
2129
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002130void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
2131 const auto duration = getMillsSinceOldestPendingRead(storageId);
2132 if (duration >= 0) {
2133 const auto kMetricsMillisSinceOldestPendingRead =
2134 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2135 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2136 }
2137}
2138
2139long IncrementalService::getMillsSinceOldestPendingRead(StorageId storageId) {
2140 std::unique_lock l(mLock);
2141 const auto ifs = getIfsLocked(storageId);
2142 if (!ifs) {
2143 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, invalid storageId: " << storageId;
2144 return -EINVAL;
2145 }
2146 if (!ifs->dataLoaderStub) {
2147 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, no data loader: " << storageId;
2148 return -EINVAL;
2149 }
2150 return ifs->dataLoaderStub->elapsedMsSinceOldestPendingRead();
2151}
2152
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002153IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
2154 DataLoaderParamsParcel&& params,
2155 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002156 const DataLoaderStatusListener* statusListener,
2157 StorageHealthCheckParams&& healthCheckParams,
2158 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002159 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002160 : mService(service),
2161 mId(id),
2162 mParams(std::move(params)),
2163 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002164 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
2165 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002166 mHealthPath(std::move(healthPath)),
2167 mHealthCheckParams(std::move(healthCheckParams)) {
2168 if (mHealthListener) {
2169 if (!isHealthParamsValid()) {
2170 mHealthListener = {};
2171 }
2172 } else {
2173 // Disable advanced health check statuses.
2174 mHealthCheckParams.blockedTimeoutMs = -1;
2175 }
2176 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002177}
2178
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002179IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002180 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002181 cleanupResources();
2182 }
2183}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002184
2185void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002186 auto now = Clock::now();
2187 {
2188 std::unique_lock lock(mMutex);
2189 mHealthPath.clear();
2190 unregisterFromPendingReads();
2191 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002192 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002193 }
2194
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002195 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002196
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002197 {
2198 std::unique_lock lock(mMutex);
2199 mParams = {};
2200 mControl = {};
2201 mHealthControl = {};
2202 mHealthListener = {};
2203 mStatusCondition.wait_until(lock, now + 60s, [this] {
2204 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2205 });
2206 mStatusListener = {};
2207 mId = kInvalidStorageId;
2208 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002209}
2210
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002211sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2212 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002213 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002214 if (!status.isOk()) {
2215 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2216 return {};
2217 }
2218 if (!dataloader) {
2219 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2220 return {};
2221 }
2222 return dataloader;
2223}
2224
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002225bool IncrementalService::DataLoaderStub::requestCreate() {
2226 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2227}
2228
2229bool IncrementalService::DataLoaderStub::requestStart() {
2230 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2231}
2232
2233bool IncrementalService::DataLoaderStub::requestDestroy() {
2234 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2235}
2236
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002237bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002238 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002239 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002240 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002241 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002242 return fsmStep();
2243}
2244
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002245void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002246 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002247 mTargetStatus = status;
2248 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002249 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002250 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002251}
2252
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002253std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002254 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002255
2256 const auto now = mService.mClock->now();
2257 const bool healthy = (mPreviousBindDelay == 0ms);
2258
2259 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2260 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2261 LOG(INFO) << "Binding still in progress. "
2262 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
2263 : "Already unhealthy, don't do anything.");
2264 // Binding still in progress.
2265 if (!healthy) {
2266 // Already unhealthy, don't do anything.
2267 return {};
2268 }
2269 // The DL is healthy/freshly bound, ok to retry for a few times.
2270 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2271 // Still within grace period.
2272 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2273 // Retry interval passed, retrying.
2274 mCurrentStatusTs = now;
2275 mPreviousBindDelay = 0ms;
2276 return 0ms;
2277 }
2278 return {};
2279 }
2280 // fallthrough, mark as unhealthy, and retry with delay
2281 }
2282
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002283 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002284 mPreviousBindTs = now;
2285
2286 const auto nonCrashingInterval = std::max(castToMs(now - previousBindTs), 100ms);
2287 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2288 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2289 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002290 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002291 }
2292
2293 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2294 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2295
2296 const auto bindDelayMs =
2297 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2298 maxBindDelayMs)
2299 .count();
2300 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2301 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2302 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002303 return mPreviousBindDelay;
2304}
2305
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002306bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002307 const auto maybeBindDelay = needToBind();
2308 if (!maybeBindDelay) {
2309 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2310 return true;
2311 }
2312 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002313 if (bindDelay > 1s) {
2314 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
2315 << bindDelay.count() / 1000 << "s";
2316 }
2317
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002318 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002319 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2320 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002321 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002322 const bool healthy = (bindDelay == 0ms);
2323 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2324 << (healthy ? ", retrying." : "");
2325
2326 // Internal error, retry for healthy/new DLs.
2327 // Let needToBind migrate it to unhealthy after too many retries.
2328 if (healthy) {
2329 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2330 [this]() { fsmStep(); })) {
2331 // Mark as binding so that we know it's not the DL's fault.
2332 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2333 return true;
2334 }
2335 }
2336
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002337 return false;
2338 }
2339 return true;
2340}
2341
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002342bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002343 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002344 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002345 return false;
2346 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002347 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002348 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002349 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002350 return false;
2351 }
2352 return true;
2353}
2354
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002355bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002356 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002357 if (!dataloader) {
2358 return false;
2359 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002360 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002361 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002362 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002363 return false;
2364 }
2365 return true;
2366}
2367
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002368bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002369 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002370}
2371
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002372bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002373 if (!isValid()) {
2374 return false;
2375 }
2376
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002377 int currentStatus;
2378 int targetStatus;
2379 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002380 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002381 currentStatus = mCurrentStatus;
2382 targetStatus = mTargetStatus;
2383 }
2384
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002385 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002386
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002387 if (currentStatus == targetStatus) {
2388 return true;
2389 }
2390
2391 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002392 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2393 // Do nothing, this is a reset state.
2394 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002395 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002396 switch (currentStatus) {
2397 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2398 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2399 return true;
2400 default:
2401 return destroy();
2402 }
2403 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002404 }
2405 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2406 switch (currentStatus) {
2407 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2408 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2409 return start();
2410 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002411 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002412 }
2413 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2414 switch (currentStatus) {
2415 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002416 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002417 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002418 return bind();
2419 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002420 return create();
2421 }
2422 break;
2423 default:
2424 LOG(ERROR) << "Invalid target status: " << targetStatus
2425 << ", current status: " << currentStatus;
2426 break;
2427 }
2428 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002429}
2430
2431binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002432 if (!isValid()) {
2433 return binder::Status::
2434 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2435 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002436 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002437 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2438 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002439 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2440 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002441 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2442 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2443 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2444 [this, newStatus]() { setCurrentStatus(newStatus); });
2445 return binder::Status::ok();
2446 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002447
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002448 setCurrentStatus(newStatus);
2449 return binder::Status::ok();
2450}
2451
2452void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002453 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002454 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002455 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002456 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002457 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002458 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002459 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002460
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002461 oldStatus = mCurrentStatus;
2462 targetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002463 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002464
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002465 // Change the status.
2466 mCurrentStatus = newStatus;
2467 mCurrentStatusTs = mService.mClock->now();
2468
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002469 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2470 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002471 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2472 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002473 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002474 }
2475
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002476 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002477 << newStatus << " (target " << targetStatus << ")";
2478
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002479 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002480 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002481 }
2482
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002483 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002484
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002485 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002486}
2487
Songchun Fan33093982020-09-10 13:12:39 -07002488binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2489 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002490 if (!isValid()) {
2491 return binder::Status::
2492 fromServiceSpecificError(-EINVAL,
2493 "reportStreamHealth came to invalid DataLoaderStub");
2494 }
2495 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002496 LOG(ERROR) << "reportStreamHealth: mount ID mismatch: expected " << id()
2497 << ", but got: " << mountId;
Songchun Fan2570ec02020-10-08 17:22:33 -07002498 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2499 }
2500 {
2501 std::lock_guard lock(mMutex);
2502 mStreamStatus = newStatus;
2503 }
Songchun Fan33093982020-09-10 13:12:39 -07002504 return binder::Status::ok();
2505}
2506
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002507bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2508 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2509 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002510}
2511
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002512void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2513 int healthStatus) {
2514 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2515 if (healthListener) {
2516 healthListener->onHealthStatus(id(), healthStatus);
2517 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002518}
2519
Songchun Fan2570ec02020-10-08 17:22:33 -07002520static int adjustHealthStatus(int healthStatus, int streamStatus) {
2521 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2522 // everything is good; no need to change status
2523 return healthStatus;
2524 }
2525 int newHeathStatus = healthStatus;
2526 switch (streamStatus) {
2527 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2528 // storage is limited and storage not healthy
2529 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2530 break;
2531 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2532 // fall through
2533 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2534 // fall through
2535 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2536 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2537 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2538 }
2539 // pending/blocked status due to transportation issues is not regarded as unhealthy
2540 break;
2541 default:
2542 break;
2543 }
2544 return newHeathStatus;
2545}
2546
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002547void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2548 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002549
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002550 int healthStatusToReport = -1;
2551 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002552
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002553 {
2554 std::unique_lock lock(mMutex);
2555 unregisterFromPendingReads();
2556
2557 healthListener = mHealthListener;
2558
2559 // Healthcheck depends on timestamp of the oldest pending read.
2560 // 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 -07002561 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2562 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002563 const auto now = Clock::now();
2564 const auto kernelTsUs = getOldestPendingReadTs();
2565 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002566 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2567 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002568 mHealthBase = {now, kernelTsUs};
2569 }
2570
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002571 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2572 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002573 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2574 registerForPendingReads();
2575 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2576 lock.unlock();
2577 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002578 return;
2579 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002580
2581 resetHealthControl();
2582
2583 // Always make sure the data loader is started.
2584 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2585
2586 // Skip any further processing if health check params are invalid.
2587 if (!isHealthParamsValid()) {
2588 LOG(DEBUG) << id()
2589 << ": Skip any further processing if health check params are invalid.";
2590 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2591 lock.unlock();
2592 onHealthStatus(healthListener, healthStatusToReport);
2593 // Triggering data loader start. This is a one-time action.
2594 fsmStep();
2595 return;
2596 }
2597
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002598 // Don't schedule timer job less than 500ms in advance.
2599 static constexpr auto kTolerance = 500ms;
2600
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002601 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2602 const auto unhealthyTimeout =
2603 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2604 const auto unhealthyMonitoring =
2605 std::max(1000ms,
2606 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2607
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002608 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002609
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002610 Milliseconds checkBackAfter;
2611 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002612 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002613 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002614 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002615 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002616 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002617 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002618 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2619 } else {
2620 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002621 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002622 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2623 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002624 // Adjust health status based on stream status
2625 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002626 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002627 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002628 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2629 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002630 }
2631
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002632 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002633 if (healthStatusToReport != -1) {
2634 onHealthStatus(healthListener, healthStatusToReport);
2635 }
2636
2637 fsmStep();
2638}
2639
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002640Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2641 BootClockTsUs kernelTsUs) {
2642 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2643 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2644 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2645}
2646
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002647const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2648 if (mHealthPath.empty()) {
2649 resetHealthControl();
2650 return mHealthControl;
2651 }
2652 if (mHealthControl.pendingReads() < 0) {
2653 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2654 }
2655 if (mHealthControl.pendingReads() < 0) {
2656 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2657 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2658 << mHealthControl.logs() << ")";
2659 }
2660 return mHealthControl;
2661}
2662
2663void IncrementalService::DataLoaderStub::resetHealthControl() {
2664 mHealthControl = {};
2665}
2666
2667BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2668 auto result = kMaxBootClockTsUs;
2669
2670 const auto& control = initializeHealthControl();
2671 if (control.pendingReads() < 0) {
2672 return result;
2673 }
2674
Songchun Fan6944f1e2020-11-06 15:24:24 -08002675 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002676 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002677 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002678 // Clear previous pending reads
2679 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002680 return result;
2681 }
2682
2683 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002684 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002685
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002686 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002687}
2688
2689void IncrementalService::DataLoaderStub::registerForPendingReads() {
2690 const auto pendingReadsFd = mHealthControl.pendingReads();
2691 if (pendingReadsFd < 0) {
2692 return;
2693 }
2694
2695 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2696
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002697 mService.mLooper->addFd(
2698 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2699 [](int, int, void* data) -> int {
2700 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002701 self->updateHealthStatus(/*baseline=*/true);
2702 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002703 },
2704 this);
2705 mService.mLooper->wake();
2706}
2707
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002708BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2709 auto result = kMaxBootClockTsUs;
2710 for (auto&& pendingRead : mLastPendingReads) {
2711 result = std::min(result, pendingRead.bootClockTsUs);
2712 }
2713 return result;
2714}
2715
2716long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
2717 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
2718 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
2719 return 0;
2720 }
2721 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
2722}
2723
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002724void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002725 const auto pendingReadsFd = mHealthControl.pendingReads();
2726 if (pendingReadsFd < 0) {
2727 return;
2728 }
2729
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002730 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2731
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002732 mService.mLooper->removeFd(pendingReadsFd);
2733 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002734}
2735
Songchun Fan2570ec02020-10-08 17:22:33 -07002736void IncrementalService::DataLoaderStub::setHealthListener(
2737 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2738 std::lock_guard lock(mMutex);
2739 mHealthCheckParams = std::move(healthCheckParams);
2740 if (healthListener == nullptr) {
2741 // reset listener and params
2742 mHealthListener = {};
2743 } else {
2744 mHealthListener = *healthListener;
2745 }
2746}
2747
Songchun Fan6944f1e2020-11-06 15:24:24 -08002748static std::string toHexString(const RawMetadata& metadata) {
2749 int n = metadata.size();
2750 std::string res(n * 2, '\0');
2751 // Same as incfs::toString(fileId)
2752 static constexpr char kHexChar[] = "0123456789abcdef";
2753 for (int i = 0; i < n; ++i) {
2754 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2755 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2756 }
2757 return res;
2758}
2759
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002760void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002761 dprintf(fd, " dataLoader: {\n");
2762 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002763 dprintf(fd, " currentStatusTs: %lldmcs\n",
2764 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002765 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2766 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002767 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002768 dprintf(fd, " health: {\n");
2769 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2770 dprintf(fd, " base: %lldmcs (%lld)\n",
2771 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2772 (long long)mHealthBase.kernelTsUs);
2773 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2774 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2775 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2776 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002777 dprintf(fd, " lastPendingReads: \n");
2778 const auto control = mService.mIncFs->openMount(mHealthPath);
2779 for (auto&& pendingRead : mLastPendingReads) {
2780 dprintf(fd, " fileId: %s\n", mService.mIncFs->toString(pendingRead.id).c_str());
2781 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2782 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2783 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2784 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2785 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002786 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
2787 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
2788 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002789 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002790 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002791 dprintf(fd, " dataLoaderParams: {\n");
2792 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2793 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2794 dprintf(fd, " className: %s\n", params.className.c_str());
2795 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2796 dprintf(fd, " }\n");
2797 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002798}
2799
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002800void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2801 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002802}
2803
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002804binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2805 bool enableReadLogs, int32_t* _aidl_return) {
2806 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2807 return binder::Status::ok();
2808}
2809
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002810FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2811 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2812}
2813
Songchun Fan3c82a302019-11-29 14:23:45 -08002814} // namespace android::incremental