blob: 60d9ea20d06aa602fde9e39355ce468c0df36af5 [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 Buynytskyy7b3e06e2021-03-23 11:29:05 -070084 // 1s, 10s, 100s (~2min), 1000s (~15min), 10000s (~3hrs)
85 static constexpr auto minBindDelay = 1s;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080086 static constexpr auto maxBindDelay = 10000s;
87 static constexpr auto bindDelayMultiplier = 10;
88 static constexpr auto bindDelayJitterDivider = 10;
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -070089
90 // Max interval after system invoked the DL when readlog collection can be enabled.
91 static constexpr auto readLogsMaxInterval = 2h;
Songchun Fan3c82a302019-11-29 14:23:45 -080092};
93
94static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070095 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080096 return c;
97}
98
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -070099static bool isPageAligned(IncFsSize s) {
100 return (s & (Constants::blockSize - 1)) == 0;
101}
102
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700103static bool getEnforceReadLogsMaxIntervalForSystemDataLoaders() {
104 return android::base::GetBoolProperty("debug.incremental.enforce_readlogs_max_interval_for_"
105 "system_dataloaders",
106 false);
107}
108
109static Seconds getReadLogsMaxInterval() {
110 constexpr int limit = duration_cast<Seconds>(Constants::readLogsMaxInterval).count();
111 int readlogs_max_interval_secs =
112 std::min(limit,
113 android::base::GetIntProperty<
114 int>("debug.incremental.readlogs_max_interval_sec", limit));
115 return Seconds{readlogs_max_interval_secs};
116}
117
Songchun Fan3c82a302019-11-29 14:23:45 -0800118template <base::LogSeverity level = base::ERROR>
119bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
120 auto cstr = path::c_str(name);
121 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800122 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800123 PLOG(level) << "Can't create directory '" << name << '\'';
124 return false;
125 }
126 struct stat st;
127 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
128 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
129 return false;
130 }
131 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800132 if (::chmod(cstr, mode)) {
133 PLOG(level) << "Changing permission failed for '" << name << '\'';
134 return false;
135 }
136
Songchun Fan3c82a302019-11-29 14:23:45 -0800137 return true;
138}
139
140static std::string toMountKey(std::string_view path) {
141 if (path.empty()) {
142 return "@none";
143 }
144 if (path == "/"sv) {
145 return "@root";
146 }
147 if (path::isAbsolute(path)) {
148 path.remove_prefix(1);
149 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700150 if (path.size() > 16) {
151 path = path.substr(0, 16);
152 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800153 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700154 std::replace_if(
155 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
156 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800157}
158
159static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
160 std::string_view path) {
161 auto mountKey = toMountKey(path);
162 const auto prefixSize = mountKey.size();
163 for (int counter = 0; counter < 1000;
164 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
165 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800166 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800167 return {mountKey, mountRoot};
168 }
169 }
170 return {};
171}
172
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700173template <class Map>
174typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
175 const auto nextIt = map.upper_bound(path);
176 if (nextIt == map.begin()) {
177 return map.end();
178 }
179 const auto suspectIt = std::prev(nextIt);
180 if (!path::startsWith(path, suspectIt->first)) {
181 return map.end();
182 }
183 return suspectIt;
184}
185
186static base::unique_fd dup(base::borrowed_fd fd) {
187 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
188 return base::unique_fd(res);
189}
190
Songchun Fan3c82a302019-11-29 14:23:45 -0800191template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700192static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800193 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800194 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800195 ProtoMessage message;
196 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
197}
198
199static bool isValidMountTarget(std::string_view path) {
200 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
201}
202
203std::string makeBindMdName() {
204 static constexpr auto uuidStringSize = 36;
205
206 uuid_t guid;
207 uuid_generate(guid);
208
209 std::string name;
210 const auto prefixSize = constants().mountpointMdPrefix.size();
211 name.reserve(prefixSize + uuidStringSize);
212
213 name = constants().mountpointMdPrefix;
214 name.resize(prefixSize + uuidStringSize);
215 uuid_unparse(guid, name.data() + prefixSize);
216
217 return name;
218}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700219
220static bool checkReadLogsDisabledMarker(std::string_view root) {
221 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
222 struct stat st;
223 return (::stat(markerPath, &st) == 0);
224}
225
Songchun Fan3c82a302019-11-29 14:23:45 -0800226} // namespace
227
228IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700229 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700230 dataLoaderStub->cleanupResources();
231 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700232 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700233 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800234 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
235 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700236 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800237 incrementalService.mVold->unmountIncFs(target);
238 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700239 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800240 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
241 cleanupFilesystem(root);
242}
243
244auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800245 std::string name;
246 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
247 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
248 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800249 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
250 constants().storagePrefix.data(), id, no);
251 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800252 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800253 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800254 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
255 } else if (err != EEXIST) {
256 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
257 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800258 }
259 }
260 nextStorageDirNo = 0;
261 return storages.end();
262}
263
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700264template <class Func>
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700265static auto makeCleanup(Func&& f) requires(!std::is_lvalue_reference_v<Func>) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700266 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700267 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700268 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
269}
270
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700271static auto openDir(const char* dir) {
272 struct DirCloser {
273 void operator()(DIR* d) const noexcept { ::closedir(d); }
274 };
275 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700276}
277
278static auto openDir(std::string_view dir) {
279 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800280}
281
282static int rmDirContent(const char* path) {
283 auto dir = openDir(path);
284 if (!dir) {
285 return -EINVAL;
286 }
287 while (auto entry = ::readdir(dir.get())) {
288 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
289 continue;
290 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700291 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800292 if (entry->d_type == DT_DIR) {
293 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
294 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
295 return err;
296 }
297 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
298 PLOG(WARNING) << "Failed to rmdir " << fullPath;
299 return err;
300 }
301 } else {
302 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
303 PLOG(WARNING) << "Failed to delete " << fullPath;
304 return err;
305 }
306 }
307 }
308 return 0;
309}
310
Songchun Fan3c82a302019-11-29 14:23:45 -0800311void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800312 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800313 ::rmdir(path::join(root, constants().backing).c_str());
314 ::rmdir(path::join(root, constants().mount).c_str());
315 ::rmdir(path::c_str(root));
316}
317
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700318void IncrementalService::IncFsMount::setReadLogsEnabled(bool value) {
319 if (value) {
320 flags |= StorageFlags::ReadLogsEnabled;
321 } else {
322 flags &= ~StorageFlags::ReadLogsEnabled;
323 }
324}
325
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800326IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800327 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800328 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800329 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700330 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700331 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700332 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700333 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700334 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700335 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800336 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800337 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700338 CHECK(mVold) << "Vold service is unavailable";
339 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
340 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
341 CHECK(mJni) << "JNI is unavailable";
342 CHECK(mLooper) << "Looper is unavailable";
343 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700344 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700345 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800346 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700347
348 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700349 mJobProcessor = std::thread([this]() {
350 mJni->initializeForCurrentThread();
351 runJobProcessing();
352 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700353 mCmdLooperThread = std::thread([this]() {
354 mJni->initializeForCurrentThread();
355 runCmdLooper();
356 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700357
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700358 const auto mountedRootNames = adoptMountedInstances();
359 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800360}
361
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700362IncrementalService::~IncrementalService() {
363 {
364 std::lock_guard lock(mJobMutex);
365 mRunning = false;
366 }
367 mJobCondition.notify_all();
368 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700369 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700370 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700371 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700372 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700373 // Ensure that mounts are destroyed while the service is still valid.
374 mBindsByPath.clear();
375 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700376}
Songchun Fan3c82a302019-11-29 14:23:45 -0800377
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700378static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800379 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800380 case IncrementalService::BindKind::Temporary:
381 return "Temporary";
382 case IncrementalService::BindKind::Permanent:
383 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800384 }
385}
386
387void IncrementalService::onDump(int fd) {
388 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
389 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
390
391 std::unique_lock l(mLock);
392
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700393 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800394 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700395 std::unique_lock ll(ifs->lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700396 const IncFsMount& mnt = *ifs;
397 dprintf(fd, " [%d]: {\n", id);
398 if (id != mnt.mountId) {
399 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
400 } else {
401 dprintf(fd, " mountId: %d\n", mnt.mountId);
402 dprintf(fd, " root: %s\n", mnt.root.c_str());
403 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
404 if (mnt.dataLoaderStub) {
405 mnt.dataLoaderStub->onDump(fd);
406 } else {
407 dprintf(fd, " dataLoader: null\n");
408 }
409 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
410 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700411 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700412 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800413 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700414 }
415 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800416
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700417 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
418 for (auto&& [target, bind] : mnt.bindPoints) {
419 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
420 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
421 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
422 dprintf(fd, " kind: %s\n", toString(bind.kind));
423 }
424 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800425 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700426 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800427 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700428 dprintf(fd, "}\n");
429 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800430 for (auto&& [target, mountPairIt] : mBindsByPath) {
431 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700432 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
433 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
434 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
435 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800436 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700437 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800438}
439
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800440bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700441 if (!ifs.dataLoaderStub) {
442 return false;
443 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700444 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800445 return true;
446 }
447
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700448 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800449}
450
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700451void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800452 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700453 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800454 }
455
456 std::vector<IfsMountPtr> mounts;
457 {
458 std::lock_guard l(mLock);
459 mounts.reserve(mMounts.size());
460 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700461 std::unique_lock ll(ifs->lock);
462
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800463 if (ifs->mountId != id) {
464 continue;
465 }
466
467 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800468 mounts.push_back(ifs);
469 }
470 }
471 }
472
Alex Buynytskyy69941662020-04-11 21:40:37 -0700473 if (mounts.empty()) {
474 return;
475 }
476
Songchun Fan3c82a302019-11-29 14:23:45 -0800477 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700478 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800479 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700480 std::unique_lock l(ifs->lock);
481 if (ifs->dataLoaderStub) {
482 ifs->dataLoaderStub->requestStart();
483 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800484 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800485 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800486}
487
488auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
489 for (;;) {
490 if (mNextId == kMaxStorageId) {
491 mNextId = 0;
492 }
493 auto id = ++mNextId;
494 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
495 if (inserted) {
496 return it;
497 }
498 }
499}
500
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700501StorageId IncrementalService::createStorage(std::string_view mountPoint,
502 content::pm::DataLoaderParamsParcel dataLoaderParams,
503 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800504 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
505 if (!path::isAbsolute(mountPoint)) {
506 LOG(ERROR) << "path is not absolute: " << mountPoint;
507 return kInvalidStorageId;
508 }
509
510 auto mountNorm = path::normalize(mountPoint);
511 {
512 const auto id = findStorageId(mountNorm);
513 if (id != kInvalidStorageId) {
514 if (options & CreateOptions::OpenExisting) {
515 LOG(INFO) << "Opened existing storage " << id;
516 return id;
517 }
518 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
519 return kInvalidStorageId;
520 }
521 }
522
523 if (!(options & CreateOptions::CreateNew)) {
524 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
525 return kInvalidStorageId;
526 }
527
528 if (!path::isEmptyDir(mountNorm)) {
529 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
530 return kInvalidStorageId;
531 }
532 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
533 if (mountRoot.empty()) {
534 LOG(ERROR) << "Bad mount point";
535 return kInvalidStorageId;
536 }
537 // Make sure the code removes all crap it may create while still failing.
538 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
539 auto firstCleanupOnFailure =
540 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
541
542 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800543 const auto backing = path::join(mountRoot, constants().backing);
544 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800545 return kInvalidStorageId;
546 }
547
Songchun Fan3c82a302019-11-29 14:23:45 -0800548 IncFsMount::Control control;
549 {
550 std::lock_guard l(mMountOperationLock);
551 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800552
553 if (auto err = rmDirContent(backing.c_str())) {
554 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
555 return kInvalidStorageId;
556 }
557 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
558 return kInvalidStorageId;
559 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800560 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
561 return kInvalidStorageId;
562 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800563 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800564 if (!status.isOk()) {
565 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
566 return kInvalidStorageId;
567 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800568 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
569 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800570 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
571 return kInvalidStorageId;
572 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800573 int cmd = controlParcel.cmd.release().release();
574 int pendingReads = controlParcel.pendingReads.release().release();
575 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800576 int blocksWritten =
577 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
578 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800579 }
580
581 std::unique_lock l(mLock);
582 const auto mountIt = getStorageSlotLocked();
583 const auto mountId = mountIt->first;
584 l.unlock();
585
586 auto ifs =
587 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
588 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
589 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700590 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800591
592 auto secondCleanup = [this, &l](auto itPtr) {
593 if (!l.owns_lock()) {
594 l.lock();
595 }
596 mMounts.erase(*itPtr);
597 };
598 auto secondCleanupOnFailure =
599 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
600
601 const auto storageIt = ifs->makeStorage(ifs->mountId);
602 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800603 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800604 return kInvalidStorageId;
605 }
606
607 {
608 metadata::Mount m;
609 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700610 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700611 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
612 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
613 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800614 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800615 if (auto err =
616 mIncFs->makeFile(ifs->control,
617 path::join(ifs->root, constants().mount,
618 constants().infoMdName),
619 0777, idFromMetadata(metadata),
620 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800621 LOG(ERROR) << "Saving mount metadata failed: " << -err;
622 return kInvalidStorageId;
623 }
624 }
625
626 const auto bk =
627 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800628 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
629 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800630 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800631 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800632 return kInvalidStorageId;
633 }
634
635 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700636 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800637
Songchun Fan3c82a302019-11-29 14:23:45 -0800638 mountIt->second = std::move(ifs);
639 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700640
Songchun Fan3c82a302019-11-29 14:23:45 -0800641 LOG(INFO) << "created storage " << mountId;
642 return mountId;
643}
644
645StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
646 StorageId linkedStorage,
647 IncrementalService::CreateOptions options) {
648 if (!isValidMountTarget(mountPoint)) {
649 LOG(ERROR) << "Mount point is invalid or missing";
650 return kInvalidStorageId;
651 }
652
653 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700654 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800655 if (!ifs) {
656 LOG(ERROR) << "Ifs unavailable";
657 return kInvalidStorageId;
658 }
659
660 const auto mountIt = getStorageSlotLocked();
661 const auto storageId = mountIt->first;
662 const auto storageIt = ifs->makeStorage(storageId);
663 if (storageIt == ifs->storages.end()) {
664 LOG(ERROR) << "Can't create a new storage";
665 mMounts.erase(mountIt);
666 return kInvalidStorageId;
667 }
668
669 l.unlock();
670
671 const auto bk =
672 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800673 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
674 std::string(storageIt->second.name), path::normalize(mountPoint),
675 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800676 err < 0) {
677 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700678 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
679 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800680 return kInvalidStorageId;
681 }
682
683 mountIt->second = ifs;
684 return storageId;
685}
686
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700687bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700688 content::pm::DataLoaderParamsParcel dataLoaderParams,
689 DataLoaderStatusListener statusListener,
690 const StorageHealthCheckParams& healthCheckParams,
691 StorageHealthListener healthListener,
692 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800693 // Per Uid timeouts.
694 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700695 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800696 }
697
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700698 IfsMountPtr ifs;
699 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800700
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700701 // Re-initialize DataLoader.
702 {
703 ifs = getIfs(storageId);
704 if (!ifs) {
705 return false;
706 }
707
708 std::unique_lock l(ifs->lock);
709 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
710 }
711
712 if (dataLoaderStub) {
713 dataLoaderStub->cleanupResources();
714 dataLoaderStub = {};
715 }
716
717 {
718 std::unique_lock l(ifs->lock);
719 if (ifs->dataLoaderStub) {
720 LOG(INFO) << "Skipped data loader stub creation because it already exists";
721 return false;
722 }
723 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
724 healthCheckParams, std::move(healthListener));
725 CHECK(ifs->dataLoaderStub);
726 dataLoaderStub = ifs->dataLoaderStub;
727 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800728
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700729 if (dataLoaderStub->isSystemDataLoader() &&
730 !getEnforceReadLogsMaxIntervalForSystemDataLoaders()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700731 // Readlogs from system dataloader (adb) can always be collected.
732 ifs->startLoadingTs = TimePoint::max();
733 } else {
734 // Assign time when installation wants the DL to start streaming.
735 const auto startLoadingTs = mClock->now();
736 ifs->startLoadingTs = startLoadingTs;
737 // Setup a callback to disable the readlogs after max interval.
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700738 addTimedJob(*mTimedQueue, storageId, getReadLogsMaxInterval(),
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700739 [this, storageId, startLoadingTs]() {
740 const auto ifs = getIfs(storageId);
741 if (!ifs) {
742 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
743 << storageId;
744 return;
745 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700746 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700747 if (ifs->startLoadingTs != startLoadingTs) {
748 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
749 "installation?): "
750 << storageId;
751 return;
752 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700753 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700754 });
755 }
756
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800757 return dataLoaderStub->requestStart();
758}
759
Songchun Fan3c82a302019-11-29 14:23:45 -0800760IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
761 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700762 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800763}
764
765StorageId IncrementalService::findStorageId(std::string_view path) const {
766 std::lock_guard l(mLock);
767 auto it = findStorageLocked(path);
768 if (it == mBindsByPath.end()) {
769 return kInvalidStorageId;
770 }
771 return it->second->second.storage;
772}
773
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800774void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700775 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700776 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800777 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700778 return;
779 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700780
781 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800782 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700783 return;
784 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800785 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700786
787 const auto metadata = constants().readLogsDisabledMarkerName;
788 if (auto err = mIncFs->makeFile(ifs->control,
789 path::join(ifs->root, constants().mount,
790 constants().readLogsDisabledMarkerName),
791 0777, idFromMetadata(metadata), {})) {
792 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
793 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
794 return;
795 }
796
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700797 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700798}
799
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700800int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
801 const auto ifs = getIfs(storageId);
802 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700803 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700804 return -EINVAL;
805 }
806
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700807 std::unique_lock l(ifs->lock);
808 if (!enableReadLogs) {
809 return disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700810 }
811
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700812 if (!ifs->readLogsAllowed()) {
813 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
814 return -EPERM;
815 }
816
817 if (!ifs->dataLoaderStub) {
818 // This should never happen - only DL can call enableReadLogs.
819 LOG(ERROR) << "enableReadLogs failed: invalid state";
820 return -EPERM;
821 }
822
823 // Check installation time.
824 const auto now = mClock->now();
825 const auto startLoadingTs = ifs->startLoadingTs;
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700826 if (startLoadingTs <= now && now - startLoadingTs > getReadLogsMaxInterval()) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700827 LOG(ERROR) << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
828 << storageId;
829 return -EPERM;
830 }
831
832 const auto& packageName = ifs->dataLoaderStub->params().packageName;
833
834 // Check loader usage stats permission and apop.
835 if (auto status =
836 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
837 !status.isOk()) {
838 LOG(ERROR) << " Permission: " << kLoaderUsageStats
839 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700840 return fromBinderStatus(status);
841 }
842
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700843 // Check multiuser permission.
844 if (auto status =
845 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
846 !status.isOk()) {
847 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
848 << " check failed: " << status.toString8();
849 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700850 }
851
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700852 if (auto status = applyStorageParamsLocked(*ifs, /*enableReadLogs=*/true); status != 0) {
853 return status;
854 }
855
856 registerAppOpsCallback(packageName);
857
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700858 return 0;
859}
860
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700861int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
862 return applyStorageParamsLocked(ifs, /*enableReadLogs=*/false);
863}
864
865int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700866 os::incremental::IncrementalFileSystemControlParcel control;
867 control.cmd.reset(dup(ifs.control.cmd()));
868 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700869 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700870 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700871 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700872 }
873
874 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700875 auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800876 if (status.isOk()) {
877 // Store enabled state.
878 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700879 } else {
880 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800881 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700882 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700883}
884
Songchun Fan3c82a302019-11-29 14:23:45 -0800885void IncrementalService::deleteStorage(StorageId storageId) {
886 const auto ifs = getIfs(storageId);
887 if (!ifs) {
888 return;
889 }
890 deleteStorage(*ifs);
891}
892
893void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
894 std::unique_lock l(ifs.lock);
895 deleteStorageLocked(ifs, std::move(l));
896}
897
898void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
899 std::unique_lock<std::mutex>&& ifsLock) {
900 const auto storages = std::move(ifs.storages);
901 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
902 const auto bindPoints = ifs.bindPoints;
903 ifsLock.unlock();
904
905 std::lock_guard l(mLock);
906 for (auto&& [id, _] : storages) {
907 if (id != ifs.mountId) {
908 mMounts.erase(id);
909 }
910 }
911 for (auto&& [path, _] : bindPoints) {
912 mBindsByPath.erase(path);
913 }
914 mMounts.erase(ifs.mountId);
915}
916
917StorageId IncrementalService::openStorage(std::string_view pathInMount) {
918 if (!path::isAbsolute(pathInMount)) {
919 return kInvalidStorageId;
920 }
921
922 return findStorageId(path::normalize(pathInMount));
923}
924
Songchun Fan3c82a302019-11-29 14:23:45 -0800925IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
926 std::lock_guard l(mLock);
927 return getIfsLocked(storage);
928}
929
930const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
931 auto it = mMounts.find(storage);
932 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700933 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700934 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800935 }
936 return it->second;
937}
938
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800939int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
940 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800941 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700942 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800943 return -EINVAL;
944 }
945
946 const auto ifs = getIfs(storage);
947 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700948 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800949 return -EINVAL;
950 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800951
Songchun Fan3c82a302019-11-29 14:23:45 -0800952 std::unique_lock l(ifs->lock);
953 const auto storageInfo = ifs->storages.find(storage);
954 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700955 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800956 return -EINVAL;
957 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700958 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700959 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700960 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700961 return -EINVAL;
962 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800963 l.unlock();
964 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800965 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
966 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800967}
968
969int IncrementalService::unbind(StorageId storage, std::string_view target) {
970 if (!path::isAbsolute(target)) {
971 return -EINVAL;
972 }
973
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700974 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800975
976 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
977 // otherwise there's a chance to unmount something completely unrelated
978 const auto norm = path::normalize(target);
979 std::unique_lock l(mLock);
980 const auto storageIt = mBindsByPath.find(norm);
981 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
982 return -EINVAL;
983 }
984 const auto bindIt = storageIt->second;
985 const auto storageId = bindIt->second.storage;
986 const auto ifs = getIfsLocked(storageId);
987 if (!ifs) {
988 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
989 << " is missing";
990 return -EFAULT;
991 }
992 mBindsByPath.erase(storageIt);
993 l.unlock();
994
995 mVold->unmountIncFs(bindIt->first);
996 std::unique_lock l2(ifs->lock);
997 if (ifs->bindPoints.size() <= 1) {
998 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700999 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001000 } else {
1001 const std::string savedFile = std::move(bindIt->second.savedFilename);
1002 ifs->bindPoints.erase(bindIt);
1003 l2.unlock();
1004 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001005 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001006 }
1007 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001008
Songchun Fan3c82a302019-11-29 14:23:45 -08001009 return 0;
1010}
1011
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001012std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001013 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001014 std::string_view path) const {
1015 if (!path::isAbsolute(path)) {
1016 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001017 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001018 auto normPath = path::normalize(path);
1019 if (path::startsWith(normPath, storageIt->second.name)) {
1020 return normPath;
1021 }
1022 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001023 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1024 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001025 return {};
1026 }
1027 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001028}
1029
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001030std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001031 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001032 std::unique_lock l(ifs.lock);
1033 const auto storageInfo = ifs.storages.find(storage);
1034 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001035 return {};
1036 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001037 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001038}
1039
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001040int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001041 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001042 const auto ifs = getIfs(storage);
1043 if (!ifs) {
1044 return -EINVAL;
1045 }
1046 if (data.size() > params.size) {
1047 LOG(ERROR) << "Bad data size - bigger than file size";
1048 return -EINVAL;
1049 }
1050 if (!data.empty() && data.size() != params.size) {
1051 // Writing a page is an irreversible operation, and it can't be updated with additional
1052 // data later. Check that the last written page is complete, or we may break the file.
1053 if (!isPageAligned(data.size())) {
1054 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001055 return -EINVAL;
1056 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001057 }
1058 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1059 if (normPath.empty()) {
1060 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1061 return -EINVAL;
1062 }
1063 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1064 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1065 return err;
1066 }
1067 if (params.size > 0) {
1068 // Only v2+ incfs supports automatically trimming file over-reserved sizes
1069 if (mIncFs->features() & incfs::Features::v2) {
1070 if (auto err = mIncFs->reserveSpace(ifs->control, normPath, params.size)) {
1071 if (err != -EOPNOTSUPP) {
1072 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1073 (void)mIncFs->unlink(ifs->control, normPath);
1074 return err;
1075 } else {
1076 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1077 "may run out of disk later";
1078 }
1079 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001080 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001081 if (!data.empty()) {
1082 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001083 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001084 return err;
1085 }
1086 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001087 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001088 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001089}
1090
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001091int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001092 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001093 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001094 if (normPath.empty()) {
1095 return -EINVAL;
1096 }
1097 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001098 }
1099 return -EINVAL;
1100}
1101
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001102int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001103 const auto ifs = getIfs(storageId);
1104 if (!ifs) {
1105 return -EINVAL;
1106 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001107 return makeDirs(*ifs, storageId, path, mode);
1108}
1109
1110int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1111 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001112 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1113 if (normPath.empty()) {
1114 return -EINVAL;
1115 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001116 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001117}
1118
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001119int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1120 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001121 std::unique_lock l(mLock);
1122 auto ifsSrc = getIfsLocked(sourceStorageId);
1123 if (!ifsSrc) {
1124 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001125 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001126 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1127 return -EINVAL;
1128 }
1129 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001130 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1131 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001132 if (normOldPath.empty() || normNewPath.empty()) {
1133 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1134 return -EINVAL;
1135 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001136 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1137 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1138 << " to " << newPath << "[" << normNewPath << "]";
1139 return err;
1140 }
1141 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001142}
1143
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001144int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001145 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001146 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001147 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001148 }
1149 return -EINVAL;
1150}
1151
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001152int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1153 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001154 std::string&& target, BindKind kind,
1155 std::unique_lock<std::mutex>& mainLock) {
1156 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001157 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001158 return -EINVAL;
1159 }
1160
1161 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001162 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001163 if (kind != BindKind::Temporary) {
1164 metadata::BindPoint bp;
1165 bp.set_storage_id(storage);
1166 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001167 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001168 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001169 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001170 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001171 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001172 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1173 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1174 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001175 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001176 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001177 return int(node);
1178 }
1179 }
1180
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001181 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1182 std::move(target), kind, mainLock);
1183 if (res) {
1184 mIncFs->unlink(ifs.control, metadataFullPath);
1185 }
1186 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001187}
1188
1189int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001190 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001191 std::string&& target, BindKind kind,
1192 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001193 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001194 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001195 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001196 if (!status.isOk()) {
1197 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1198 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1199 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1200 : status.serviceSpecificErrorCode() == 0
1201 ? -EFAULT
1202 : status.serviceSpecificErrorCode()
1203 : -EIO;
1204 }
1205 }
1206
1207 if (!mainLock.owns_lock()) {
1208 mainLock.lock();
1209 }
1210 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001211 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1212 std::move(target), kind);
1213 return 0;
1214}
1215
1216void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1217 std::string&& metadataName, std::string&& source,
1218 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001219 const auto [it, _] =
1220 ifs.bindPoints.insert_or_assign(target,
1221 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001222 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001223 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001224}
1225
1226RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1227 const auto ifs = getIfs(storage);
1228 if (!ifs) {
1229 return {};
1230 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001231 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001232 if (normPath.empty()) {
1233 return {};
1234 }
1235 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001236}
1237
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001238RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001239 const auto ifs = getIfs(storage);
1240 if (!ifs) {
1241 return {};
1242 }
1243 return mIncFs->getMetadata(ifs->control, node);
1244}
1245
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001246void IncrementalService::setUidReadTimeouts(StorageId storage,
1247 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001248 using microseconds = std::chrono::microseconds;
1249 using milliseconds = std::chrono::milliseconds;
1250
1251 auto maxPendingTimeUs = microseconds(0);
1252 for (const auto& timeouts : perUidReadTimeouts) {
1253 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1254 }
1255 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001256 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001257 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1258 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001259 return;
1260 }
1261
1262 const auto ifs = getIfs(storage);
1263 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001264 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001265 return;
1266 }
1267
1268 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1269 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1270 return;
1271 }
1272
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001273 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1274 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1275 if (checkUidReadTimeouts(storageId, state, timeout)) {
1276 return true;
1277 }
1278 clearUidReadTimeouts(storageId);
1279 return false;
1280 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001281}
1282
1283void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1284 const auto ifs = getIfs(storage);
1285 if (!ifs) {
1286 return;
1287 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001288 mIncFs->setUidReadTimeouts(ifs->control, {});
1289}
1290
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001291bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1292 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001293 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001294 // Reached maximum timeout.
1295 return false;
1296 }
1297 if (state.error) {
1298 // Something is wrong, abort.
1299 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001300 }
1301
1302 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001303 if (state.fullyLoaded && !state.readLogsEnabled) {
1304 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001305 }
1306
1307 const auto timeLeft = timeLimit - Clock::now();
1308 if (timeLeft < Constants::progressUpdateInterval) {
1309 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001310 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001311 }
1312
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001313 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001314}
1315
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001316std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1317 std::unordered_set<std::string_view> mountedRootNames;
1318 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1319 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1320 for (auto [source, target] : binds) {
1321 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1322 LOG(INFO) << " " << path::join(root, source);
1323 }
1324
1325 // Ensure it's a kind of a mount that's managed by IncrementalService
1326 if (path::basename(root) != constants().mount ||
1327 path::basename(backingDir) != constants().backing) {
1328 return;
1329 }
1330 const auto expectedRoot = path::dirname(root);
1331 if (path::dirname(backingDir) != expectedRoot) {
1332 return;
1333 }
1334 if (path::dirname(expectedRoot) != mIncrementalDir) {
1335 return;
1336 }
1337 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1338 return;
1339 }
1340
1341 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1342
1343 // make sure we clean up the mount if it happens to be a bad one.
1344 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1345 auto cleanupFiles = makeCleanup([&]() {
1346 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1347 IncFsMount::cleanupFilesystem(expectedRoot);
1348 });
1349 auto cleanupMounts = makeCleanup([&]() {
1350 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1351 for (auto&& [_, target] : binds) {
1352 mVold->unmountIncFs(std::string(target));
1353 }
1354 mVold->unmountIncFs(std::string(root));
1355 });
1356
1357 auto control = mIncFs->openMount(root);
1358 if (!control) {
1359 LOG(INFO) << "failed to open mount " << root;
1360 return;
1361 }
1362
1363 auto mountRecord =
1364 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1365 path::join(root, constants().infoMdName));
1366 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1367 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1368 return;
1369 }
1370
1371 auto mountId = mountRecord.storage().id();
1372 mNextId = std::max(mNextId, mountId + 1);
1373
1374 DataLoaderParamsParcel dataLoaderParams;
1375 {
1376 const auto& loader = mountRecord.loader();
1377 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1378 dataLoaderParams.packageName = loader.package_name();
1379 dataLoaderParams.className = loader.class_name();
1380 dataLoaderParams.arguments = loader.arguments();
1381 }
1382
1383 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1384 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001385 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001386
Alex Buynytskyy04035452020-06-06 20:15:58 -07001387 // Check if marker file present.
1388 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001389 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001390 }
1391
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001392 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1393 auto d = openDir(root);
1394 while (auto e = ::readdir(d.get())) {
1395 if (e->d_type == DT_REG) {
1396 auto name = std::string_view(e->d_name);
1397 if (name.starts_with(constants().mountpointMdPrefix)) {
1398 permanentBindPoints
1399 .emplace_back(name,
1400 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1401 ifs->control,
1402 path::join(root,
1403 name)));
1404 if (permanentBindPoints.back().second.dest_path().empty() ||
1405 permanentBindPoints.back().second.source_subdir().empty()) {
1406 permanentBindPoints.pop_back();
1407 mIncFs->unlink(ifs->control, path::join(root, name));
1408 } else {
1409 LOG(INFO) << "Permanent bind record: '"
1410 << permanentBindPoints.back().second.source_subdir() << "'->'"
1411 << permanentBindPoints.back().second.dest_path() << "'";
1412 }
1413 }
1414 } else if (e->d_type == DT_DIR) {
1415 if (e->d_name == "."sv || e->d_name == ".."sv) {
1416 continue;
1417 }
1418 auto name = std::string_view(e->d_name);
1419 if (name.starts_with(constants().storagePrefix)) {
1420 int storageId;
1421 const auto res =
1422 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1423 name.data() + name.size(), storageId);
1424 if (res.ec != std::errc{} || *res.ptr != '_') {
1425 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1426 << "' for mount " << expectedRoot;
1427 continue;
1428 }
1429 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1430 if (!inserted) {
1431 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1432 << " for mount " << expectedRoot;
1433 continue;
1434 }
1435 ifs->storages.insert_or_assign(storageId,
1436 IncFsMount::Storage{path::join(root, name)});
1437 mNextId = std::max(mNextId, storageId + 1);
1438 }
1439 }
1440 }
1441
1442 if (ifs->storages.empty()) {
1443 LOG(WARNING) << "No valid storages in mount " << root;
1444 return;
1445 }
1446
1447 // now match the mounted directories with what we expect to have in the metadata
1448 {
1449 std::unique_lock l(mLock, std::defer_lock);
1450 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1451 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1452 [&, bindRecord = bindRecord](auto&& bind) {
1453 return bind.second == bindRecord.dest_path() &&
1454 path::join(root, bind.first) ==
1455 bindRecord.source_subdir();
1456 });
1457 if (mountedIt != binds.end()) {
1458 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1459 << " to mount " << mountedIt->first;
1460 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1461 std::move(*bindRecord.mutable_source_subdir()),
1462 std::move(*bindRecord.mutable_dest_path()),
1463 BindKind::Permanent);
1464 if (mountedIt != binds.end() - 1) {
1465 std::iter_swap(mountedIt, binds.end() - 1);
1466 }
1467 binds = binds.first(binds.size() - 1);
1468 } else {
1469 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1470 << ", mounting";
1471 // doesn't exist - try mounting back
1472 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1473 std::move(*bindRecord.mutable_source_subdir()),
1474 std::move(*bindRecord.mutable_dest_path()),
1475 BindKind::Permanent, l)) {
1476 mIncFs->unlink(ifs->control, metadataFile);
1477 }
1478 }
1479 }
1480 }
1481
1482 // if anything stays in |binds| those are probably temporary binds; system restarted since
1483 // they were mounted - so let's unmount them all.
1484 for (auto&& [source, target] : binds) {
1485 if (source.empty()) {
1486 continue;
1487 }
1488 mVold->unmountIncFs(std::string(target));
1489 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001490 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001491
1492 if (ifs->bindPoints.empty()) {
1493 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1494 deleteStorage(*ifs);
1495 return;
1496 }
1497
1498 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1499 CHECK(ifs->dataLoaderStub);
1500
1501 mountedRootNames.insert(path::basename(ifs->root));
1502
1503 // not locking here at all: we're still in the constructor, no other calls can happen
1504 mMounts[ifs->mountId] = std::move(ifs);
1505 });
1506
1507 return mountedRootNames;
1508}
1509
1510void IncrementalService::mountExistingImages(
1511 const std::unordered_set<std::string_view>& mountedRootNames) {
1512 auto dir = openDir(mIncrementalDir);
1513 if (!dir) {
1514 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1515 return;
1516 }
1517 while (auto entry = ::readdir(dir.get())) {
1518 if (entry->d_type != DT_DIR) {
1519 continue;
1520 }
1521 std::string_view name = entry->d_name;
1522 if (!name.starts_with(constants().mountKeyPrefix)) {
1523 continue;
1524 }
1525 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001526 continue;
1527 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001528 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001529 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001530 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001531 }
1532 }
1533}
1534
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001535bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001536 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001537 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001538
Songchun Fan3c82a302019-11-29 14:23:45 -08001539 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001540 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001541 if (!status.isOk()) {
1542 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1543 return false;
1544 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001545
1546 int cmd = controlParcel.cmd.release().release();
1547 int pendingReads = controlParcel.pendingReads.release().release();
1548 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001549 int blocksWritten =
1550 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1551 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001552
1553 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1554
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001555 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1556 path::join(mountTarget, constants().infoMdName));
1557 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001558 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1559 return false;
1560 }
1561
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001562 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001563 mNextId = std::max(mNextId, ifs->mountId + 1);
1564
Alex Buynytskyy04035452020-06-06 20:15:58 -07001565 // Check if marker file present.
1566 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001567 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001568 }
1569
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001570 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001571 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001572 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001573 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001574 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001575 dataLoaderParams.packageName = loader.package_name();
1576 dataLoaderParams.className = loader.class_name();
1577 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001578 }
1579
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001580 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001581 CHECK(ifs->dataLoaderStub);
1582
Songchun Fan3c82a302019-11-29 14:23:45 -08001583 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001584 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001585 while (auto e = ::readdir(d.get())) {
1586 if (e->d_type == DT_REG) {
1587 auto name = std::string_view(e->d_name);
1588 if (name.starts_with(constants().mountpointMdPrefix)) {
1589 bindPoints.emplace_back(name,
1590 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1591 ifs->control,
1592 path::join(mountTarget,
1593 name)));
1594 if (bindPoints.back().second.dest_path().empty() ||
1595 bindPoints.back().second.source_subdir().empty()) {
1596 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001597 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001598 }
1599 }
1600 } else if (e->d_type == DT_DIR) {
1601 if (e->d_name == "."sv || e->d_name == ".."sv) {
1602 continue;
1603 }
1604 auto name = std::string_view(e->d_name);
1605 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001606 int storageId;
1607 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1608 name.data() + name.size(), storageId);
1609 if (res.ec != std::errc{} || *res.ptr != '_') {
1610 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1611 << root;
1612 continue;
1613 }
1614 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001615 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001616 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001617 << " for mount " << root;
1618 continue;
1619 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001620 ifs->storages.insert_or_assign(storageId,
1621 IncFsMount::Storage{
1622 path::join(root, constants().mount, name)});
1623 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001624 }
1625 }
1626 }
1627
1628 if (ifs->storages.empty()) {
1629 LOG(WARNING) << "No valid storages in mount " << root;
1630 return false;
1631 }
1632
1633 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001634 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001635 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001636 for (auto&& bp : bindPoints) {
1637 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1638 std::move(*bp.second.mutable_source_subdir()),
1639 std::move(*bp.second.mutable_dest_path()),
1640 BindKind::Permanent, l);
1641 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001642 }
1643
1644 if (bindCount == 0) {
1645 LOG(WARNING) << "No valid bind points for mount " << root;
1646 deleteStorage(*ifs);
1647 return false;
1648 }
1649
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001650 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001651 mMounts[ifs->mountId] = std::move(ifs);
1652 return true;
1653}
1654
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001655void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001656 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001657 while (mRunning.load(std::memory_order_relaxed)) {
1658 mLooper->pollAll(kTimeoutMsecs);
1659 }
1660}
1661
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001662void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001663 DataLoaderStatusListener&& statusListener,
1664 const StorageHealthCheckParams& healthCheckParams,
1665 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001666 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001667 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001668 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1669 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1670 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001671 if (ifs.control.blocksWritten() >= 0) {
1672 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1673 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001674 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001675
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001676 ifs.dataLoaderStub =
1677 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001678 std::move(statusListener), healthCheckParams,
1679 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001680
1681 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1682 if (!state.fullyLoaded || state.readLogsEnabled) {
1683 return true;
1684 }
1685
1686 DataLoaderStubPtr dataLoaderStub;
1687 {
1688 const auto ifs = getIfs(storageId);
1689 if (!ifs) {
1690 return false;
1691 }
1692
1693 std::unique_lock l(ifs->lock);
1694 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1695 }
1696
1697 if (dataLoaderStub) {
1698 dataLoaderStub->cleanupResources();
1699 }
1700
1701 return false;
1702 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001703}
1704
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001705template <class Duration>
1706static long elapsedMcs(Duration start, Duration end) {
1707 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1708}
1709
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001710template <class Duration>
1711static constexpr auto castToMs(Duration d) {
1712 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1713}
1714
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001715// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001716// Lib files should be placed next to the APK file in the following matter:
1717// Example:
1718// /path/to/base.apk
1719// /path/to/lib/arm/first.so
1720// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001721bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1722 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001723 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001724 auto start = Clock::now();
1725
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001726 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001727 if (!ifs) {
1728 LOG(ERROR) << "Invalid storage " << storage;
1729 return false;
1730 }
1731
Songchun Fanc8975312020-07-13 12:14:37 -07001732 const auto targetLibPathRelativeToStorage =
1733 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1734 libDirRelativePath);
1735
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001736 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001737 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1738 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001739 << " errno: " << res;
1740 return false;
1741 }
1742
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001743 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001744 ZipArchiveHandle zipFileHandle;
1745 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001746 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1747 return false;
1748 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001749
1750 // Need a shared pointer: will be passing it into all unpacking jobs.
1751 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001752 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001753 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001754 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001755 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1756 return false;
1757 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001758 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001759 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1760
1761 auto openZipTs = Clock::now();
1762
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001763 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1764 incfs::FileId sourceId;
1765 if (mapFiles) {
1766 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1767 if (!incfs::isValidFileId(sourceId)) {
1768 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1769 << "', mapping disabled";
1770 mapFiles = false;
1771 }
1772 }
1773
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001774 std::vector<Job> jobQueue;
1775 ZipEntry entry;
1776 std::string_view fileName;
1777 while (!Next(cookie, &entry, &fileName)) {
1778 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001779 continue;
1780 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001781
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001782 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001783 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001784
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001785 if (!extractNativeLibs) {
1786 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001787 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001788 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1789 return false;
1790 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001791 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001792 LOG(WARNING) << "Library " << fileName
1793 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1794 << entry.offset;
1795 return false;
1796 }
1797 continue;
1798 }
1799
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001800 auto startFileTs = Clock::now();
1801
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001802 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001803 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001804 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001805 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001806 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001807 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001808 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1809 << "; skipping extraction, spent "
1810 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1811 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001812 continue;
1813 }
1814
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001815 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1816 incfs::NewMappedFileParams mappedFileParams = {
1817 .sourceId = sourceId,
1818 .sourceOffset = entry.offset,
1819 .size = entry.uncompressed_length,
1820 };
1821
1822 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1823 mappedFileParams);
1824 res == 0) {
1825 if (perfLoggingEnabled()) {
1826 auto doneTs = Clock::now();
1827 LOG(INFO) << "incfs: Mapped " << libName << ": "
1828 << elapsedMcs(startFileTs, doneTs) << "mcs";
1829 }
1830 continue;
1831 } else {
1832 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1833 << "; falling back to full extraction";
1834 }
1835 }
1836
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001837 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001838 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001839 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001840 .signature = {},
1841 // Metadata of the new lib file is its relative path
1842 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1843 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001844 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001845 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001846 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001847 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001848 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001849 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001850 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001851
1852 auto makeFileTs = Clock::now();
1853
Songchun Fanafaf6e92020-03-18 14:12:20 -07001854 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001855 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001856 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001857 LOG(INFO) << "incfs: Extracted " << libName
1858 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001859 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001860 continue;
1861 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001862
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001863 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1864 libFileId, libPath = std::move(targetLibPath),
1865 makeFileTs]() mutable {
1866 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001867 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001868
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001869 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001870 auto prepareJobTs = Clock::now();
1871 LOG(INFO) << "incfs: Processed " << libName << ": "
1872 << elapsedMcs(startFileTs, prepareJobTs)
1873 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1874 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001875 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001876 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001877
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001878 auto processedTs = Clock::now();
1879
1880 if (!jobQueue.empty()) {
1881 {
1882 std::lock_guard lock(mJobMutex);
1883 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001884 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001885 if (existingJobs.empty()) {
1886 existingJobs = std::move(jobQueue);
1887 } else {
1888 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1889 std::move_iterator(jobQueue.end()));
1890 }
1891 }
1892 }
1893 mJobCondition.notify_all();
1894 }
1895
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001896 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001897 auto end = Clock::now();
1898 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1899 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1900 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001901 << " make files: " << elapsedMcs(openZipTs, processedTs)
1902 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001903 }
1904
1905 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001906}
1907
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001908void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1909 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001910 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001911 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001912 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001913 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001914 return;
1915 }
1916
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001917 auto startedTs = Clock::now();
1918
1919 // Write extracted data to new file
1920 // NOTE: don't zero-initialize memory, it may take a while for nothing
1921 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1922 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001923 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001924 return;
1925 }
1926
1927 auto extractFileTs = Clock::now();
1928
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001929 if (setFileContent(ifs, libFileId, debugLibPath,
1930 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001931 return;
1932 }
1933
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001934 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001935 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001936 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1937 << entry.compressed_length << " -> " << entry.uncompressed_length
1938 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001939 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1940 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001941 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001942 }
1943}
1944
1945bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001946 struct WaitPrinter {
1947 const Clock::time_point startTs = Clock::now();
1948 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001949 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001950 const auto endTs = Clock::now();
1951 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1952 << elapsedMcs(startTs, endTs) << "mcs";
1953 }
1954 }
1955 } waitPrinter;
1956
1957 MountId mount;
1958 {
1959 auto ifs = getIfs(storage);
1960 if (!ifs) {
1961 return true;
1962 }
1963 mount = ifs->mountId;
1964 }
1965
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001966 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001967 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001968 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001969 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001970 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001971 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001972}
1973
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001974int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1975 std::string_view debugFilePath,
1976 std::span<const uint8_t> data) const {
1977 auto startTs = Clock::now();
1978
1979 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1980 if (!writeFd.ok()) {
1981 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1982 << " errno: " << writeFd.get();
1983 return writeFd.get();
1984 }
1985
1986 const auto dataLength = data.size();
1987
1988 auto openFileTs = Clock::now();
1989 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1990 std::vector<IncFsDataBlock> instructions(numBlocks);
1991 for (int i = 0; i < numBlocks; i++) {
1992 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1993 instructions[i] = IncFsDataBlock{
1994 .fileFd = writeFd.get(),
1995 .pageIndex = static_cast<IncFsBlockIndex>(i),
1996 .compression = INCFS_COMPRESSION_KIND_NONE,
1997 .kind = INCFS_BLOCK_KIND_DATA,
1998 .dataSize = static_cast<uint32_t>(blockSize),
1999 .data = reinterpret_cast<const char*>(data.data()),
2000 };
2001 data = data.subspan(blockSize);
2002 }
2003 auto prepareInstsTs = Clock::now();
2004
2005 size_t res = mIncFs->writeBlocks(instructions);
2006 if (res != instructions.size()) {
2007 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2008 return res;
2009 }
2010
2011 if (perfLoggingEnabled()) {
2012 auto endTs = Clock::now();
2013 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2014 << " bytes): " << elapsedMcs(startTs, endTs)
2015 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2016 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2017 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2018 }
2019
2020 return 0;
2021}
2022
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002023incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2024 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002025 std::unique_lock l(mLock);
2026 const auto ifs = getIfsLocked(storage);
2027 if (!ifs) {
2028 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002029 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002030 }
2031 const auto storageInfo = ifs->storages.find(storage);
2032 if (storageInfo == ifs->storages.end()) {
2033 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002034 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002035 }
2036 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002037 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002038}
2039
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002040incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2041 const auto ifs = getIfs(storage);
2042 if (!ifs) {
2043 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2044 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002045 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002046 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002047}
2048
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002049IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002050 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002051 std::unique_lock l(mLock);
2052 const auto ifs = getIfsLocked(storage);
2053 if (!ifs) {
2054 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002055 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002056 }
2057 const auto storageInfo = ifs->storages.find(storage);
2058 if (storageInfo == ifs->storages.end()) {
2059 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002060 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002061 }
2062 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002063 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002064}
2065
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002066IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002067 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002068 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2069 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002070 const auto [filledBlocksCount, totalBlocksCount] =
2071 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002072 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2073 filledBlocksCount == -ENOENT) {
2074 // a kind of a file that's not really being loaded, e.g. a mapped range
2075 // an older IncFS used to return ENOENT in this case, so handle it the same way
2076 return true;
2077 }
Songchun Fan374f7652020-08-20 08:40:29 -07002078 if (filledBlocksCount < 0) {
2079 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002080 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002081 error = filledBlocksCount;
2082 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002083 }
2084 totalBlocks += totalBlocksCount;
2085 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002086 return true;
2087 });
Songchun Fan374f7652020-08-20 08:40:29 -07002088
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002089 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002090}
2091
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002092bool IncrementalService::updateLoadingProgress(StorageId storage,
2093 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002094 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002095 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002096 // Failed to get progress from incfs, abort.
2097 return false;
2098 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002099 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2100 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002101 // Stop updating progress once it is fully loaded
2102 return true;
2103 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002104 addTimedJob(*mProgressUpdateJobQueue, storage,
2105 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002106 [storage, progressListener = std::move(progressListener), this]() mutable {
2107 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002108 });
2109 return true;
2110}
2111
2112bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002113 StorageId storage, StorageLoadingProgressListener progressListener) {
2114 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002115}
2116
2117bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2118 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2119}
2120
Songchun Fan2570ec02020-10-08 17:22:33 -07002121bool IncrementalService::registerStorageHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002122 StorageId storage, const StorageHealthCheckParams& healthCheckParams,
2123 StorageHealthListener healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002124 DataLoaderStubPtr dataLoaderStub;
2125 {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002126 const auto& ifs = getIfs(storage);
Songchun Fan2570ec02020-10-08 17:22:33 -07002127 if (!ifs) {
2128 return false;
2129 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002130 std::unique_lock l(ifs->lock);
Songchun Fan2570ec02020-10-08 17:22:33 -07002131 dataLoaderStub = ifs->dataLoaderStub;
2132 if (!dataLoaderStub) {
2133 return false;
2134 }
2135 }
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002136 dataLoaderStub->setHealthListener(healthCheckParams, std::move(healthListener));
Songchun Fan2570ec02020-10-08 17:22:33 -07002137 return true;
2138}
2139
2140void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002141 registerStorageHealthListener(storage, {}, {});
Songchun Fan2570ec02020-10-08 17:22:33 -07002142}
2143
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002144bool IncrementalService::perfLoggingEnabled() {
2145 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2146 return enabled;
2147}
2148
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002149void IncrementalService::runJobProcessing() {
2150 for (;;) {
2151 std::unique_lock lock(mJobMutex);
2152 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2153 if (!mRunning) {
2154 return;
2155 }
2156
2157 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002158 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002159 auto queue = std::move(it->second);
2160 mJobQueue.erase(it);
2161 lock.unlock();
2162
2163 for (auto&& job : queue) {
2164 job();
2165 }
2166
2167 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002168 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002169 lock.unlock();
2170 mJobCondition.notify_all();
2171 }
2172}
2173
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002174void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002175 sp<IAppOpsCallback> listener;
2176 {
2177 std::unique_lock lock{mCallbacksLock};
2178 auto& cb = mCallbackRegistered[packageName];
2179 if (cb) {
2180 return;
2181 }
2182 cb = new AppOpsListener(*this, packageName);
2183 listener = cb;
2184 }
2185
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002186 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2187 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002188}
2189
2190bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2191 sp<IAppOpsCallback> listener;
2192 {
2193 std::unique_lock lock{mCallbacksLock};
2194 auto found = mCallbackRegistered.find(packageName);
2195 if (found == mCallbackRegistered.end()) {
2196 return false;
2197 }
2198 listener = found->second;
2199 mCallbackRegistered.erase(found);
2200 }
2201
2202 mAppOpsManager->stopWatchingMode(listener);
2203 return true;
2204}
2205
2206void IncrementalService::onAppOpChanged(const std::string& packageName) {
2207 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002208 return;
2209 }
2210
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002211 std::vector<IfsMountPtr> affected;
2212 {
2213 std::lock_guard l(mLock);
2214 affected.reserve(mMounts.size());
2215 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002216 std::unique_lock ll(ifs->lock);
2217
2218 if (ifs->mountId == id && ifs->dataLoaderStub &&
2219 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002220 affected.push_back(ifs);
2221 }
2222 }
2223 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002224 for (auto&& ifs : affected) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002225 applyStorageParamsLocked(*ifs, /*enableReadLogs=*/false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002226 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002227}
2228
Songchun Fana7098592020-09-03 11:45:53 -07002229bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2230 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002231 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002232 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002233 }
Songchun Fana7098592020-09-03 11:45:53 -07002234 timedQueue.addJob(id, after, std::move(what));
2235 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002236}
2237
Songchun Fana7098592020-09-03 11:45:53 -07002238bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002239 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002240 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002241 }
Songchun Fana7098592020-09-03 11:45:53 -07002242 timedQueue.removeJobs(id);
2243 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002244}
2245
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002246void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2247 bool wasEmpty;
2248 {
2249 std::lock_guard l(mIfsStateCallbacksLock);
2250 wasEmpty = mIfsStateCallbacks.empty();
2251 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2252 }
2253 if (wasEmpty) {
2254 addTimedJob(*mTimedQueue, kMaxStorageId, Constants::progressUpdateInterval,
2255 [this]() { processIfsStateCallbacks(); });
2256 }
2257}
2258
2259void IncrementalService::processIfsStateCallbacks() {
2260 StorageId storageId = kInvalidStorageId;
2261 std::vector<IfsStateCallback> local;
2262 while (true) {
2263 {
2264 std::lock_guard l(mIfsStateCallbacksLock);
2265 if (mIfsStateCallbacks.empty()) {
2266 return;
2267 }
2268 IfsStateCallbacks::iterator it;
2269 if (storageId == kInvalidStorageId) {
2270 // First entry, initialize the it.
2271 it = mIfsStateCallbacks.begin();
2272 } else {
2273 // Subsequent entries, update the storageId, and shift to the new one.
2274 it = mIfsStateCallbacks.find(storageId);
2275 if (it == mIfsStateCallbacks.end()) {
2276 // Was removed while processing, too bad.
2277 break;
2278 }
2279
2280 auto& callbacks = it->second;
2281 if (callbacks.empty()) {
2282 std::swap(callbacks, local);
2283 } else {
2284 callbacks.insert(callbacks.end(), local.begin(), local.end());
2285 }
2286 if (callbacks.empty()) {
2287 it = mIfsStateCallbacks.erase(it);
2288 if (mIfsStateCallbacks.empty()) {
2289 return;
2290 }
2291 } else {
2292 ++it;
2293 }
2294 }
2295
2296 if (it == mIfsStateCallbacks.end()) {
2297 break;
2298 }
2299
2300 storageId = it->first;
2301 auto& callbacks = it->second;
2302 if (callbacks.empty()) {
2303 // Invalid case, one extra lookup should be ok.
2304 continue;
2305 }
2306 std::swap(callbacks, local);
2307 }
2308
2309 processIfsStateCallbacks(storageId, local);
2310 }
2311
2312 addTimedJob(*mTimedQueue, kMaxStorageId, Constants::progressUpdateInterval,
2313 [this]() { processIfsStateCallbacks(); });
2314}
2315
2316void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2317 std::vector<IfsStateCallback>& callbacks) {
2318 const auto state = isMountFullyLoaded(storageId);
2319 IfsState storageState = {};
2320 storageState.error = int(state) < 0;
2321 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2322 if (storageState.fullyLoaded) {
2323 const auto ifs = getIfs(storageId);
2324 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2325 }
2326
2327 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2328 if ((*cur)(storageId, storageState)) {
2329 ++cur;
2330 } else {
2331 cur = callbacks.erase(cur);
2332 }
2333 }
2334}
2335
2336void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2337 std::lock_guard l(mIfsStateCallbacksLock);
2338 mIfsStateCallbacks.erase(storageId);
2339}
2340
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002341void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
2342 const auto duration = getMillsSinceOldestPendingRead(storageId);
2343 if (duration >= 0) {
2344 const auto kMetricsMillisSinceOldestPendingRead =
2345 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2346 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2347 }
2348}
2349
2350long IncrementalService::getMillsSinceOldestPendingRead(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002351 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002352 if (!ifs) {
2353 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, invalid storageId: " << storageId;
2354 return -EINVAL;
2355 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002356 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002357 if (!ifs->dataLoaderStub) {
2358 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, no data loader: " << storageId;
2359 return -EINVAL;
2360 }
2361 return ifs->dataLoaderStub->elapsedMsSinceOldestPendingRead();
2362}
2363
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002364IncrementalService::DataLoaderStub::DataLoaderStub(
2365 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2366 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2367 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2368 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002369 : mService(service),
2370 mId(id),
2371 mParams(std::move(params)),
2372 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002373 mStatusListener(std::move(statusListener)),
2374 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002375 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002376 mHealthCheckParams(healthCheckParams) {
2377 if (mHealthListener && !isHealthParamsValid()) {
2378 mHealthListener = {};
2379 }
2380 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002381 // Disable advanced health check statuses.
2382 mHealthCheckParams.blockedTimeoutMs = -1;
2383 }
2384 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002385}
2386
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002387IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002388 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002389 cleanupResources();
2390 }
2391}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002392
2393void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002394 auto now = Clock::now();
2395 {
2396 std::unique_lock lock(mMutex);
2397 mHealthPath.clear();
2398 unregisterFromPendingReads();
2399 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002400 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002401 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002402 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002403
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002404 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002405
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002406 {
2407 std::unique_lock lock(mMutex);
2408 mParams = {};
2409 mControl = {};
2410 mHealthControl = {};
2411 mHealthListener = {};
2412 mStatusCondition.wait_until(lock, now + 60s, [this] {
2413 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2414 });
2415 mStatusListener = {};
2416 mId = kInvalidStorageId;
2417 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002418}
2419
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002420sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2421 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002422 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002423 if (!status.isOk()) {
2424 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2425 return {};
2426 }
2427 if (!dataloader) {
2428 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2429 return {};
2430 }
2431 return dataloader;
2432}
2433
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002434bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2435 return (params().packageName == Constants::systemPackage);
2436}
2437
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002438bool IncrementalService::DataLoaderStub::requestCreate() {
2439 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2440}
2441
2442bool IncrementalService::DataLoaderStub::requestStart() {
2443 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2444}
2445
2446bool IncrementalService::DataLoaderStub::requestDestroy() {
2447 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2448}
2449
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002450bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002451 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002452 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002453 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002454 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002455 return fsmStep();
2456}
2457
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002458void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002459 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002460 mTargetStatus = status;
2461 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002462 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002463 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002464}
2465
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002466std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002467 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002468
2469 const auto now = mService.mClock->now();
2470 const bool healthy = (mPreviousBindDelay == 0ms);
2471
2472 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2473 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2474 LOG(INFO) << "Binding still in progress. "
2475 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
2476 : "Already unhealthy, don't do anything.");
2477 // Binding still in progress.
2478 if (!healthy) {
2479 // Already unhealthy, don't do anything.
2480 return {};
2481 }
2482 // The DL is healthy/freshly bound, ok to retry for a few times.
2483 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2484 // Still within grace period.
2485 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2486 // Retry interval passed, retrying.
2487 mCurrentStatusTs = now;
2488 mPreviousBindDelay = 0ms;
2489 return 0ms;
2490 }
2491 return {};
2492 }
2493 // fallthrough, mark as unhealthy, and retry with delay
2494 }
2495
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002496 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002497 mPreviousBindTs = now;
2498
2499 const auto nonCrashingInterval = std::max(castToMs(now - previousBindTs), 100ms);
2500 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2501 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2502 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002503 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002504 }
2505
2506 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2507 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2508
2509 const auto bindDelayMs =
2510 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2511 maxBindDelayMs)
2512 .count();
2513 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2514 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2515 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002516 return mPreviousBindDelay;
2517}
2518
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002519bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002520 const auto maybeBindDelay = needToBind();
2521 if (!maybeBindDelay) {
2522 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2523 return true;
2524 }
2525 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002526 if (bindDelay > 1s) {
2527 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
2528 << bindDelay.count() / 1000 << "s";
2529 }
2530
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002531 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002532 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2533 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002534 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002535 const bool healthy = (bindDelay == 0ms);
2536 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2537 << (healthy ? ", retrying." : "");
2538
2539 // Internal error, retry for healthy/new DLs.
2540 // Let needToBind migrate it to unhealthy after too many retries.
2541 if (healthy) {
2542 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2543 [this]() { fsmStep(); })) {
2544 // Mark as binding so that we know it's not the DL's fault.
2545 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2546 return true;
2547 }
2548 }
2549
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002550 return false;
2551 }
2552 return true;
2553}
2554
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002555bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002556 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002557 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002558 return false;
2559 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002560 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002561 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002562 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002563 return false;
2564 }
2565 return true;
2566}
2567
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002568bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002569 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002570 if (!dataloader) {
2571 return false;
2572 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002573 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002574 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002575 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002576 return false;
2577 }
2578 return true;
2579}
2580
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002581bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002582 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002583}
2584
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002585bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002586 if (!isValid()) {
2587 return false;
2588 }
2589
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002590 int currentStatus;
2591 int targetStatus;
2592 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002593 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002594 currentStatus = mCurrentStatus;
2595 targetStatus = mTargetStatus;
2596 }
2597
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002598 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002599
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002600 if (currentStatus == targetStatus) {
2601 return true;
2602 }
2603
2604 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002605 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2606 // Do nothing, this is a reset state.
2607 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002608 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002609 switch (currentStatus) {
2610 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2611 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2612 return true;
2613 default:
2614 return destroy();
2615 }
2616 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002617 }
2618 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2619 switch (currentStatus) {
2620 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2621 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2622 return start();
2623 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002624 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002625 }
2626 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2627 switch (currentStatus) {
2628 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002629 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002630 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002631 return bind();
2632 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002633 return create();
2634 }
2635 break;
2636 default:
2637 LOG(ERROR) << "Invalid target status: " << targetStatus
2638 << ", current status: " << currentStatus;
2639 break;
2640 }
2641 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002642}
2643
2644binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002645 if (!isValid()) {
2646 return binder::Status::
2647 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2648 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002649 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002650 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2651 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002652 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2653 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002654 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2655 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2656 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2657 [this, newStatus]() { setCurrentStatus(newStatus); });
2658 return binder::Status::ok();
2659 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002660
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002661 setCurrentStatus(newStatus);
2662 return binder::Status::ok();
2663}
2664
2665void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002666 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002667 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002668 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002669 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002670 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002671 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002672 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002673
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002674 oldStatus = mCurrentStatus;
2675 targetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002676 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002677
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002678 // Change the status.
2679 mCurrentStatus = newStatus;
2680 mCurrentStatusTs = mService.mClock->now();
2681
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002682 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2683 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002684 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2685 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002686 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002687 }
2688
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002689 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002690 << newStatus << " (target " << targetStatus << ")";
2691
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002692 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002693 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002694 }
2695
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002696 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002697
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002698 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002699}
2700
Songchun Fan33093982020-09-10 13:12:39 -07002701binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2702 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002703 if (!isValid()) {
2704 return binder::Status::
2705 fromServiceSpecificError(-EINVAL,
2706 "reportStreamHealth came to invalid DataLoaderStub");
2707 }
2708 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002709 LOG(ERROR) << "reportStreamHealth: mount ID mismatch: expected " << id()
2710 << ", but got: " << mountId;
Songchun Fan2570ec02020-10-08 17:22:33 -07002711 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2712 }
2713 {
2714 std::lock_guard lock(mMutex);
2715 mStreamStatus = newStatus;
2716 }
Songchun Fan33093982020-09-10 13:12:39 -07002717 return binder::Status::ok();
2718}
2719
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002720bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2721 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2722 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002723}
2724
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002725void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002726 int healthStatus) {
2727 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2728 if (healthListener) {
2729 healthListener->onHealthStatus(id(), healthStatus);
2730 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002731}
2732
Songchun Fan2570ec02020-10-08 17:22:33 -07002733static int adjustHealthStatus(int healthStatus, int streamStatus) {
2734 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2735 // everything is good; no need to change status
2736 return healthStatus;
2737 }
2738 int newHeathStatus = healthStatus;
2739 switch (streamStatus) {
2740 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2741 // storage is limited and storage not healthy
2742 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2743 break;
2744 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2745 // fall through
2746 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2747 // fall through
2748 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2749 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2750 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2751 }
2752 // pending/blocked status due to transportation issues is not regarded as unhealthy
2753 break;
2754 default:
2755 break;
2756 }
2757 return newHeathStatus;
2758}
2759
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002760void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2761 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002762
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002763 int healthStatusToReport = -1;
2764 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002765
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002766 {
2767 std::unique_lock lock(mMutex);
2768 unregisterFromPendingReads();
2769
2770 healthListener = mHealthListener;
2771
2772 // Healthcheck depends on timestamp of the oldest pending read.
2773 // 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 -07002774 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2775 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002776 const auto now = Clock::now();
2777 const auto kernelTsUs = getOldestPendingReadTs();
2778 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002779 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2780 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002781 mHealthBase = {now, kernelTsUs};
2782 }
2783
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002784 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2785 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002786 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2787 registerForPendingReads();
2788 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2789 lock.unlock();
2790 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002791 return;
2792 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002793
2794 resetHealthControl();
2795
2796 // Always make sure the data loader is started.
2797 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2798
2799 // Skip any further processing if health check params are invalid.
2800 if (!isHealthParamsValid()) {
2801 LOG(DEBUG) << id()
2802 << ": Skip any further processing if health check params are invalid.";
2803 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2804 lock.unlock();
2805 onHealthStatus(healthListener, healthStatusToReport);
2806 // Triggering data loader start. This is a one-time action.
2807 fsmStep();
2808 return;
2809 }
2810
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002811 // Don't schedule timer job less than 500ms in advance.
2812 static constexpr auto kTolerance = 500ms;
2813
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002814 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2815 const auto unhealthyTimeout =
2816 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2817 const auto unhealthyMonitoring =
2818 std::max(1000ms,
2819 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2820
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002821 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002822
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002823 Milliseconds checkBackAfter;
2824 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002825 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002826 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002827 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002828 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002829 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002830 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002831 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2832 } else {
2833 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002834 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002835 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2836 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002837 // Adjust health status based on stream status
2838 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002839 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002840 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002841 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2842 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002843 }
2844
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002845 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002846 if (healthStatusToReport != -1) {
2847 onHealthStatus(healthListener, healthStatusToReport);
2848 }
2849
2850 fsmStep();
2851}
2852
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002853Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2854 BootClockTsUs kernelTsUs) {
2855 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2856 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2857 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2858}
2859
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002860const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2861 if (mHealthPath.empty()) {
2862 resetHealthControl();
2863 return mHealthControl;
2864 }
2865 if (mHealthControl.pendingReads() < 0) {
2866 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2867 }
2868 if (mHealthControl.pendingReads() < 0) {
2869 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2870 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2871 << mHealthControl.logs() << ")";
2872 }
2873 return mHealthControl;
2874}
2875
2876void IncrementalService::DataLoaderStub::resetHealthControl() {
2877 mHealthControl = {};
2878}
2879
2880BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2881 auto result = kMaxBootClockTsUs;
2882
2883 const auto& control = initializeHealthControl();
2884 if (control.pendingReads() < 0) {
2885 return result;
2886 }
2887
Songchun Fan6944f1e2020-11-06 15:24:24 -08002888 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002889 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002890 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002891 // Clear previous pending reads
2892 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002893 return result;
2894 }
2895
2896 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002897 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002898
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002899 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002900}
2901
2902void IncrementalService::DataLoaderStub::registerForPendingReads() {
2903 const auto pendingReadsFd = mHealthControl.pendingReads();
2904 if (pendingReadsFd < 0) {
2905 return;
2906 }
2907
2908 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2909
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002910 mService.mLooper->addFd(
2911 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2912 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002913 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002914 self->updateHealthStatus(/*baseline=*/true);
2915 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002916 },
2917 this);
2918 mService.mLooper->wake();
2919}
2920
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002921BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2922 auto result = kMaxBootClockTsUs;
2923 for (auto&& pendingRead : mLastPendingReads) {
2924 result = std::min(result, pendingRead.bootClockTsUs);
2925 }
2926 return result;
2927}
2928
2929long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
2930 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
2931 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
2932 return 0;
2933 }
2934 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
2935}
2936
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002937void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002938 const auto pendingReadsFd = mHealthControl.pendingReads();
2939 if (pendingReadsFd < 0) {
2940 return;
2941 }
2942
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002943 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2944
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002945 mService.mLooper->removeFd(pendingReadsFd);
2946 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002947}
2948
Songchun Fan2570ec02020-10-08 17:22:33 -07002949void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002950 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002951 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002952 mHealthCheckParams = healthCheckParams;
2953 mHealthListener = std::move(healthListener);
2954 if (!mHealthListener) {
2955 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07002956 }
2957}
2958
Songchun Fan6944f1e2020-11-06 15:24:24 -08002959static std::string toHexString(const RawMetadata& metadata) {
2960 int n = metadata.size();
2961 std::string res(n * 2, '\0');
2962 // Same as incfs::toString(fileId)
2963 static constexpr char kHexChar[] = "0123456789abcdef";
2964 for (int i = 0; i < n; ++i) {
2965 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2966 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2967 }
2968 return res;
2969}
2970
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002971void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002972 dprintf(fd, " dataLoader: {\n");
2973 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002974 dprintf(fd, " currentStatusTs: %lldmcs\n",
2975 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002976 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2977 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002978 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002979 dprintf(fd, " health: {\n");
2980 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2981 dprintf(fd, " base: %lldmcs (%lld)\n",
2982 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2983 (long long)mHealthBase.kernelTsUs);
2984 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2985 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2986 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2987 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08002988 dprintf(fd, " lastPendingReads: \n");
2989 const auto control = mService.mIncFs->openMount(mHealthPath);
2990 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07002991 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08002992 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
2993 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
2994 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
2995 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
2996 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002997 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
2998 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
2999 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003000 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003001 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003002 dprintf(fd, " dataLoaderParams: {\n");
3003 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3004 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3005 dprintf(fd, " className: %s\n", params.className.c_str());
3006 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3007 dprintf(fd, " }\n");
3008 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003009}
3010
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003011void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3012 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003013}
3014
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003015binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3016 bool enableReadLogs, int32_t* _aidl_return) {
3017 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3018 return binder::Status::ok();
3019}
3020
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003021FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3022 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3023}
3024
Songchun Fan3c82a302019-11-29 14:23:45 -08003025} // namespace android::incremental