blob: 6695ba841b67b98f5f6afa9ffe1ce2198ca07fde [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
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700326void IncrementalService::IncFsMount::setReadLogsRequested(bool value) {
327 if (value) {
328 flags |= StorageFlags::ReadLogsRequested;
329 } else {
330 flags &= ~StorageFlags::ReadLogsRequested;
331 }
332}
333
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800334IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800335 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800336 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800337 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700338 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700339 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700340 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700341 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700342 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700343 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800344 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800345 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700346 CHECK(mVold) << "Vold service is unavailable";
347 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
348 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
349 CHECK(mJni) << "JNI is unavailable";
350 CHECK(mLooper) << "Looper is unavailable";
351 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700352 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700353 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800354 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700355
356 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700357 mJobProcessor = std::thread([this]() {
358 mJni->initializeForCurrentThread();
359 runJobProcessing();
360 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700361 mCmdLooperThread = std::thread([this]() {
362 mJni->initializeForCurrentThread();
363 runCmdLooper();
364 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700365
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700366 const auto mountedRootNames = adoptMountedInstances();
367 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800368}
369
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700370IncrementalService::~IncrementalService() {
371 {
372 std::lock_guard lock(mJobMutex);
373 mRunning = false;
374 }
375 mJobCondition.notify_all();
376 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700377 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700378 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700379 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700380 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700381 // Ensure that mounts are destroyed while the service is still valid.
382 mBindsByPath.clear();
383 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700384}
Songchun Fan3c82a302019-11-29 14:23:45 -0800385
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700386static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800387 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800388 case IncrementalService::BindKind::Temporary:
389 return "Temporary";
390 case IncrementalService::BindKind::Permanent:
391 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800392 }
393}
394
395void IncrementalService::onDump(int fd) {
396 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
397 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
398
399 std::unique_lock l(mLock);
400
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700401 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800402 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700403 std::unique_lock ll(ifs->lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700404 const IncFsMount& mnt = *ifs;
405 dprintf(fd, " [%d]: {\n", id);
406 if (id != mnt.mountId) {
407 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
408 } else {
409 dprintf(fd, " mountId: %d\n", mnt.mountId);
410 dprintf(fd, " root: %s\n", mnt.root.c_str());
411 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
412 if (mnt.dataLoaderStub) {
413 mnt.dataLoaderStub->onDump(fd);
414 } else {
415 dprintf(fd, " dataLoader: null\n");
416 }
417 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
418 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700419 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700420 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800421 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700422 }
423 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800424
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700425 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
426 for (auto&& [target, bind] : mnt.bindPoints) {
427 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
428 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
429 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
430 dprintf(fd, " kind: %s\n", toString(bind.kind));
431 }
432 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800433 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700434 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800435 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700436 dprintf(fd, "}\n");
437 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800438 for (auto&& [target, mountPairIt] : mBindsByPath) {
439 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700440 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
441 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
442 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
443 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800444 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700445 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800446}
447
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800448bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700449 if (!ifs.dataLoaderStub) {
450 return false;
451 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700452 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800453 return true;
454 }
455
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700456 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800457}
458
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700459void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800460 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700461 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800462 }
463
464 std::vector<IfsMountPtr> mounts;
465 {
466 std::lock_guard l(mLock);
467 mounts.reserve(mMounts.size());
468 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700469 std::unique_lock ll(ifs->lock);
470
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800471 if (ifs->mountId != id) {
472 continue;
473 }
474
475 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800476 mounts.push_back(ifs);
477 }
478 }
479 }
480
Alex Buynytskyy69941662020-04-11 21:40:37 -0700481 if (mounts.empty()) {
482 return;
483 }
484
Songchun Fan3c82a302019-11-29 14:23:45 -0800485 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700486 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800487 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700488 std::unique_lock l(ifs->lock);
489 if (ifs->dataLoaderStub) {
490 ifs->dataLoaderStub->requestStart();
491 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800492 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800493 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800494}
495
496auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
497 for (;;) {
498 if (mNextId == kMaxStorageId) {
499 mNextId = 0;
500 }
501 auto id = ++mNextId;
502 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
503 if (inserted) {
504 return it;
505 }
506 }
507}
508
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700509StorageId IncrementalService::createStorage(std::string_view mountPoint,
510 content::pm::DataLoaderParamsParcel dataLoaderParams,
511 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800512 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
513 if (!path::isAbsolute(mountPoint)) {
514 LOG(ERROR) << "path is not absolute: " << mountPoint;
515 return kInvalidStorageId;
516 }
517
518 auto mountNorm = path::normalize(mountPoint);
519 {
520 const auto id = findStorageId(mountNorm);
521 if (id != kInvalidStorageId) {
522 if (options & CreateOptions::OpenExisting) {
523 LOG(INFO) << "Opened existing storage " << id;
524 return id;
525 }
526 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
527 return kInvalidStorageId;
528 }
529 }
530
531 if (!(options & CreateOptions::CreateNew)) {
532 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
533 return kInvalidStorageId;
534 }
535
536 if (!path::isEmptyDir(mountNorm)) {
537 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
538 return kInvalidStorageId;
539 }
540 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
541 if (mountRoot.empty()) {
542 LOG(ERROR) << "Bad mount point";
543 return kInvalidStorageId;
544 }
545 // Make sure the code removes all crap it may create while still failing.
546 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
547 auto firstCleanupOnFailure =
548 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
549
550 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800551 const auto backing = path::join(mountRoot, constants().backing);
552 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800553 return kInvalidStorageId;
554 }
555
Songchun Fan3c82a302019-11-29 14:23:45 -0800556 IncFsMount::Control control;
557 {
558 std::lock_guard l(mMountOperationLock);
559 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800560
561 if (auto err = rmDirContent(backing.c_str())) {
562 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
563 return kInvalidStorageId;
564 }
565 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
566 return kInvalidStorageId;
567 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800568 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
569 return kInvalidStorageId;
570 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800571 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800572 if (!status.isOk()) {
573 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
574 return kInvalidStorageId;
575 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800576 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
577 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800578 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
579 return kInvalidStorageId;
580 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800581 int cmd = controlParcel.cmd.release().release();
582 int pendingReads = controlParcel.pendingReads.release().release();
583 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800584 int blocksWritten =
585 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
586 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800587 }
588
589 std::unique_lock l(mLock);
590 const auto mountIt = getStorageSlotLocked();
591 const auto mountId = mountIt->first;
592 l.unlock();
593
594 auto ifs =
595 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
596 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
597 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700598 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800599
600 auto secondCleanup = [this, &l](auto itPtr) {
601 if (!l.owns_lock()) {
602 l.lock();
603 }
604 mMounts.erase(*itPtr);
605 };
606 auto secondCleanupOnFailure =
607 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
608
609 const auto storageIt = ifs->makeStorage(ifs->mountId);
610 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800611 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800612 return kInvalidStorageId;
613 }
614
615 {
616 metadata::Mount m;
617 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700618 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700619 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
620 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
621 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800622 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800623 if (auto err =
624 mIncFs->makeFile(ifs->control,
625 path::join(ifs->root, constants().mount,
626 constants().infoMdName),
627 0777, idFromMetadata(metadata),
628 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800629 LOG(ERROR) << "Saving mount metadata failed: " << -err;
630 return kInvalidStorageId;
631 }
632 }
633
634 const auto bk =
635 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800636 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
637 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800638 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800639 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800640 return kInvalidStorageId;
641 }
642
643 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700644 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800645
Songchun Fan3c82a302019-11-29 14:23:45 -0800646 mountIt->second = std::move(ifs);
647 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700648
Songchun Fan3c82a302019-11-29 14:23:45 -0800649 LOG(INFO) << "created storage " << mountId;
650 return mountId;
651}
652
653StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
654 StorageId linkedStorage,
655 IncrementalService::CreateOptions options) {
656 if (!isValidMountTarget(mountPoint)) {
657 LOG(ERROR) << "Mount point is invalid or missing";
658 return kInvalidStorageId;
659 }
660
661 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700662 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800663 if (!ifs) {
664 LOG(ERROR) << "Ifs unavailable";
665 return kInvalidStorageId;
666 }
667
668 const auto mountIt = getStorageSlotLocked();
669 const auto storageId = mountIt->first;
670 const auto storageIt = ifs->makeStorage(storageId);
671 if (storageIt == ifs->storages.end()) {
672 LOG(ERROR) << "Can't create a new storage";
673 mMounts.erase(mountIt);
674 return kInvalidStorageId;
675 }
676
677 l.unlock();
678
679 const auto bk =
680 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800681 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
682 std::string(storageIt->second.name), path::normalize(mountPoint),
683 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800684 err < 0) {
685 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700686 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
687 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800688 return kInvalidStorageId;
689 }
690
691 mountIt->second = ifs;
692 return storageId;
693}
694
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700695bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700696 content::pm::DataLoaderParamsParcel dataLoaderParams,
697 DataLoaderStatusListener statusListener,
698 const StorageHealthCheckParams& healthCheckParams,
699 StorageHealthListener healthListener,
700 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800701 // Per Uid timeouts.
702 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700703 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800704 }
705
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700706 IfsMountPtr ifs;
707 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800708
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700709 // Re-initialize DataLoader.
710 {
711 ifs = getIfs(storageId);
712 if (!ifs) {
713 return false;
714 }
715
716 std::unique_lock l(ifs->lock);
717 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
718 }
719
720 if (dataLoaderStub) {
721 dataLoaderStub->cleanupResources();
722 dataLoaderStub = {};
723 }
724
725 {
726 std::unique_lock l(ifs->lock);
727 if (ifs->dataLoaderStub) {
728 LOG(INFO) << "Skipped data loader stub creation because it already exists";
729 return false;
730 }
731 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
732 healthCheckParams, std::move(healthListener));
733 CHECK(ifs->dataLoaderStub);
734 dataLoaderStub = ifs->dataLoaderStub;
735 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800736
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700737 if (dataLoaderStub->isSystemDataLoader() &&
738 !getEnforceReadLogsMaxIntervalForSystemDataLoaders()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700739 // Readlogs from system dataloader (adb) can always be collected.
740 ifs->startLoadingTs = TimePoint::max();
741 } else {
742 // Assign time when installation wants the DL to start streaming.
743 const auto startLoadingTs = mClock->now();
744 ifs->startLoadingTs = startLoadingTs;
745 // Setup a callback to disable the readlogs after max interval.
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700746 addTimedJob(*mTimedQueue, storageId, getReadLogsMaxInterval(),
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700747 [this, storageId, startLoadingTs]() {
748 const auto ifs = getIfs(storageId);
749 if (!ifs) {
750 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
751 << storageId;
752 return;
753 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700754 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700755 if (ifs->startLoadingTs != startLoadingTs) {
756 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
757 "installation?): "
758 << storageId;
759 return;
760 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700761 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700762 });
763 }
764
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800765 return dataLoaderStub->requestStart();
766}
767
Songchun Fan3c82a302019-11-29 14:23:45 -0800768IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
769 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700770 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800771}
772
773StorageId IncrementalService::findStorageId(std::string_view path) const {
774 std::lock_guard l(mLock);
775 auto it = findStorageLocked(path);
776 if (it == mBindsByPath.end()) {
777 return kInvalidStorageId;
778 }
779 return it->second->second.storage;
780}
781
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800782void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700783 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700784 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800785 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700786 return;
787 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700788
789 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800790 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700791 return;
792 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800793 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700794
795 const auto metadata = constants().readLogsDisabledMarkerName;
796 if (auto err = mIncFs->makeFile(ifs->control,
797 path::join(ifs->root, constants().mount,
798 constants().readLogsDisabledMarkerName),
799 0777, idFromMetadata(metadata), {})) {
800 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
801 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
802 return;
803 }
804
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700805 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700806}
807
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700808int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
809 const auto ifs = getIfs(storageId);
810 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700811 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700812 return -EINVAL;
813 }
814
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700815 std::string packageName;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700816
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700817 {
818 std::unique_lock l(ifs->lock);
819 if (!enableReadLogs) {
820 return disableReadLogsLocked(*ifs);
821 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700822
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700823 if (!ifs->readLogsAllowed()) {
824 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
825 return -EPERM;
826 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700827
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700828 if (!ifs->dataLoaderStub) {
829 // This should never happen - only DL can call enableReadLogs.
830 LOG(ERROR) << "enableReadLogs failed: invalid state";
831 return -EPERM;
832 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700833
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700834 // Check installation time.
835 const auto now = mClock->now();
836 const auto startLoadingTs = ifs->startLoadingTs;
837 if (startLoadingTs <= now && now - startLoadingTs > getReadLogsMaxInterval()) {
838 LOG(ERROR)
839 << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
840 << storageId;
841 return -EPERM;
842 }
843
844 packageName = ifs->dataLoaderStub->params().packageName;
845 ifs->setReadLogsRequested(true);
846 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700847
848 // Check loader usage stats permission and apop.
849 if (auto status =
850 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
851 !status.isOk()) {
852 LOG(ERROR) << " Permission: " << kLoaderUsageStats
853 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700854 return fromBinderStatus(status);
855 }
856
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700857 // Check multiuser permission.
858 if (auto status =
859 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
860 !status.isOk()) {
861 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
862 << " check failed: " << status.toString8();
863 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700864 }
865
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700866 {
867 std::unique_lock l(ifs->lock);
868 if (!ifs->readLogsRequested()) {
869 return 0;
870 }
871 if (auto status = applyStorageParamsLocked(*ifs, /*enableReadLogs=*/true); status != 0) {
872 return status;
873 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700874 }
875
876 registerAppOpsCallback(packageName);
877
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700878 return 0;
879}
880
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700881int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700882 ifs.setReadLogsRequested(false);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700883 return applyStorageParamsLocked(ifs, /*enableReadLogs=*/false);
884}
885
886int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700887 os::incremental::IncrementalFileSystemControlParcel control;
888 control.cmd.reset(dup(ifs.control.cmd()));
889 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700890 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700891 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700892 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700893 }
894
895 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700896 auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800897 if (status.isOk()) {
898 // Store enabled state.
899 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700900 } else {
901 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800902 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700903 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700904}
905
Songchun Fan3c82a302019-11-29 14:23:45 -0800906void IncrementalService::deleteStorage(StorageId storageId) {
907 const auto ifs = getIfs(storageId);
908 if (!ifs) {
909 return;
910 }
911 deleteStorage(*ifs);
912}
913
914void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
915 std::unique_lock l(ifs.lock);
916 deleteStorageLocked(ifs, std::move(l));
917}
918
919void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
920 std::unique_lock<std::mutex>&& ifsLock) {
921 const auto storages = std::move(ifs.storages);
922 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
923 const auto bindPoints = ifs.bindPoints;
924 ifsLock.unlock();
925
926 std::lock_guard l(mLock);
927 for (auto&& [id, _] : storages) {
928 if (id != ifs.mountId) {
929 mMounts.erase(id);
930 }
931 }
932 for (auto&& [path, _] : bindPoints) {
933 mBindsByPath.erase(path);
934 }
935 mMounts.erase(ifs.mountId);
936}
937
938StorageId IncrementalService::openStorage(std::string_view pathInMount) {
939 if (!path::isAbsolute(pathInMount)) {
940 return kInvalidStorageId;
941 }
942
943 return findStorageId(path::normalize(pathInMount));
944}
945
Songchun Fan3c82a302019-11-29 14:23:45 -0800946IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
947 std::lock_guard l(mLock);
948 return getIfsLocked(storage);
949}
950
951const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
952 auto it = mMounts.find(storage);
953 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700954 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700955 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800956 }
957 return it->second;
958}
959
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800960int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
961 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800962 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700963 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800964 return -EINVAL;
965 }
966
967 const auto ifs = getIfs(storage);
968 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700969 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800970 return -EINVAL;
971 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800972
Songchun Fan3c82a302019-11-29 14:23:45 -0800973 std::unique_lock l(ifs->lock);
974 const auto storageInfo = ifs->storages.find(storage);
975 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700976 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800977 return -EINVAL;
978 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700979 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700980 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700981 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700982 return -EINVAL;
983 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800984 l.unlock();
985 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800986 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
987 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800988}
989
990int IncrementalService::unbind(StorageId storage, std::string_view target) {
991 if (!path::isAbsolute(target)) {
992 return -EINVAL;
993 }
994
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700995 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800996
997 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
998 // otherwise there's a chance to unmount something completely unrelated
999 const auto norm = path::normalize(target);
1000 std::unique_lock l(mLock);
1001 const auto storageIt = mBindsByPath.find(norm);
1002 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
1003 return -EINVAL;
1004 }
1005 const auto bindIt = storageIt->second;
1006 const auto storageId = bindIt->second.storage;
1007 const auto ifs = getIfsLocked(storageId);
1008 if (!ifs) {
1009 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
1010 << " is missing";
1011 return -EFAULT;
1012 }
1013 mBindsByPath.erase(storageIt);
1014 l.unlock();
1015
1016 mVold->unmountIncFs(bindIt->first);
1017 std::unique_lock l2(ifs->lock);
1018 if (ifs->bindPoints.size() <= 1) {
1019 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -07001020 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001021 } else {
1022 const std::string savedFile = std::move(bindIt->second.savedFilename);
1023 ifs->bindPoints.erase(bindIt);
1024 l2.unlock();
1025 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001026 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001027 }
1028 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001029
Songchun Fan3c82a302019-11-29 14:23:45 -08001030 return 0;
1031}
1032
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001033std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001034 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001035 std::string_view path) const {
1036 if (!path::isAbsolute(path)) {
1037 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001038 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001039 auto normPath = path::normalize(path);
1040 if (path::startsWith(normPath, storageIt->second.name)) {
1041 return normPath;
1042 }
1043 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001044 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1045 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001046 return {};
1047 }
1048 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001049}
1050
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001051std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001052 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001053 std::unique_lock l(ifs.lock);
1054 const auto storageInfo = ifs.storages.find(storage);
1055 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001056 return {};
1057 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001058 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001059}
1060
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001061int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001062 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001063 const auto ifs = getIfs(storage);
1064 if (!ifs) {
1065 return -EINVAL;
1066 }
1067 if (data.size() > params.size) {
1068 LOG(ERROR) << "Bad data size - bigger than file size";
1069 return -EINVAL;
1070 }
1071 if (!data.empty() && data.size() != params.size) {
1072 // Writing a page is an irreversible operation, and it can't be updated with additional
1073 // data later. Check that the last written page is complete, or we may break the file.
1074 if (!isPageAligned(data.size())) {
1075 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001076 return -EINVAL;
1077 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001078 }
1079 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1080 if (normPath.empty()) {
1081 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1082 return -EINVAL;
1083 }
1084 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1085 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1086 return err;
1087 }
1088 if (params.size > 0) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001089 if (auto err = mIncFs->reserveSpace(ifs->control, id, params.size)) {
1090 if (err != -EOPNOTSUPP) {
1091 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1092 (void)mIncFs->unlink(ifs->control, normPath);
1093 return err;
1094 } else {
1095 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1096 "may run out of disk later";
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001097 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001098 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001099 if (!data.empty()) {
1100 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001101 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001102 return err;
1103 }
1104 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001105 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001106 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001107}
1108
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001109int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001110 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001111 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001112 if (normPath.empty()) {
1113 return -EINVAL;
1114 }
1115 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001116 }
1117 return -EINVAL;
1118}
1119
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001120int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001121 const auto ifs = getIfs(storageId);
1122 if (!ifs) {
1123 return -EINVAL;
1124 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001125 return makeDirs(*ifs, storageId, path, mode);
1126}
1127
1128int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1129 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001130 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1131 if (normPath.empty()) {
1132 return -EINVAL;
1133 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001134 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001135}
1136
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001137int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1138 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001139 std::unique_lock l(mLock);
1140 auto ifsSrc = getIfsLocked(sourceStorageId);
1141 if (!ifsSrc) {
1142 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001143 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001144 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1145 return -EINVAL;
1146 }
1147 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001148 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1149 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001150 if (normOldPath.empty() || normNewPath.empty()) {
1151 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1152 return -EINVAL;
1153 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001154 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1155 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1156 << " to " << newPath << "[" << normNewPath << "]";
1157 return err;
1158 }
1159 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001160}
1161
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001162int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001163 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001164 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001165 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001166 }
1167 return -EINVAL;
1168}
1169
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001170int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1171 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001172 std::string&& target, BindKind kind,
1173 std::unique_lock<std::mutex>& mainLock) {
1174 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001175 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001176 return -EINVAL;
1177 }
1178
1179 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001180 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001181 if (kind != BindKind::Temporary) {
1182 metadata::BindPoint bp;
1183 bp.set_storage_id(storage);
1184 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001185 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001186 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001187 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001188 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001189 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001190 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1191 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1192 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001193 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001194 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001195 return int(node);
1196 }
1197 }
1198
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001199 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1200 std::move(target), kind, mainLock);
1201 if (res) {
1202 mIncFs->unlink(ifs.control, metadataFullPath);
1203 }
1204 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001205}
1206
1207int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001208 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001209 std::string&& target, BindKind kind,
1210 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001211 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001212 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001213 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001214 if (!status.isOk()) {
1215 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1216 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1217 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1218 : status.serviceSpecificErrorCode() == 0
1219 ? -EFAULT
1220 : status.serviceSpecificErrorCode()
1221 : -EIO;
1222 }
1223 }
1224
1225 if (!mainLock.owns_lock()) {
1226 mainLock.lock();
1227 }
1228 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001229 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1230 std::move(target), kind);
1231 return 0;
1232}
1233
1234void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1235 std::string&& metadataName, std::string&& source,
1236 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001237 const auto [it, _] =
1238 ifs.bindPoints.insert_or_assign(target,
1239 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001240 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001241 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001242}
1243
1244RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1245 const auto ifs = getIfs(storage);
1246 if (!ifs) {
1247 return {};
1248 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001249 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001250 if (normPath.empty()) {
1251 return {};
1252 }
1253 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001254}
1255
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001256RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001257 const auto ifs = getIfs(storage);
1258 if (!ifs) {
1259 return {};
1260 }
1261 return mIncFs->getMetadata(ifs->control, node);
1262}
1263
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001264void IncrementalService::setUidReadTimeouts(StorageId storage,
1265 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001266 using microseconds = std::chrono::microseconds;
1267 using milliseconds = std::chrono::milliseconds;
1268
1269 auto maxPendingTimeUs = microseconds(0);
1270 for (const auto& timeouts : perUidReadTimeouts) {
1271 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1272 }
1273 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001274 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001275 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1276 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001277 return;
1278 }
1279
1280 const auto ifs = getIfs(storage);
1281 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001282 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001283 return;
1284 }
1285
1286 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1287 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1288 return;
1289 }
1290
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001291 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1292 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1293 if (checkUidReadTimeouts(storageId, state, timeout)) {
1294 return true;
1295 }
1296 clearUidReadTimeouts(storageId);
1297 return false;
1298 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001299}
1300
1301void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1302 const auto ifs = getIfs(storage);
1303 if (!ifs) {
1304 return;
1305 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001306 mIncFs->setUidReadTimeouts(ifs->control, {});
1307}
1308
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001309bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1310 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001311 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001312 // Reached maximum timeout.
1313 return false;
1314 }
1315 if (state.error) {
1316 // Something is wrong, abort.
1317 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001318 }
1319
1320 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001321 if (state.fullyLoaded && !state.readLogsEnabled) {
1322 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001323 }
1324
1325 const auto timeLeft = timeLimit - Clock::now();
1326 if (timeLeft < Constants::progressUpdateInterval) {
1327 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001328 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001329 }
1330
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001331 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001332}
1333
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001334std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1335 std::unordered_set<std::string_view> mountedRootNames;
1336 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1337 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1338 for (auto [source, target] : binds) {
1339 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1340 LOG(INFO) << " " << path::join(root, source);
1341 }
1342
1343 // Ensure it's a kind of a mount that's managed by IncrementalService
1344 if (path::basename(root) != constants().mount ||
1345 path::basename(backingDir) != constants().backing) {
1346 return;
1347 }
1348 const auto expectedRoot = path::dirname(root);
1349 if (path::dirname(backingDir) != expectedRoot) {
1350 return;
1351 }
1352 if (path::dirname(expectedRoot) != mIncrementalDir) {
1353 return;
1354 }
1355 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1356 return;
1357 }
1358
1359 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1360
1361 // make sure we clean up the mount if it happens to be a bad one.
1362 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1363 auto cleanupFiles = makeCleanup([&]() {
1364 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1365 IncFsMount::cleanupFilesystem(expectedRoot);
1366 });
1367 auto cleanupMounts = makeCleanup([&]() {
1368 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1369 for (auto&& [_, target] : binds) {
1370 mVold->unmountIncFs(std::string(target));
1371 }
1372 mVold->unmountIncFs(std::string(root));
1373 });
1374
1375 auto control = mIncFs->openMount(root);
1376 if (!control) {
1377 LOG(INFO) << "failed to open mount " << root;
1378 return;
1379 }
1380
1381 auto mountRecord =
1382 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1383 path::join(root, constants().infoMdName));
1384 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1385 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1386 return;
1387 }
1388
1389 auto mountId = mountRecord.storage().id();
1390 mNextId = std::max(mNextId, mountId + 1);
1391
1392 DataLoaderParamsParcel dataLoaderParams;
1393 {
1394 const auto& loader = mountRecord.loader();
1395 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1396 dataLoaderParams.packageName = loader.package_name();
1397 dataLoaderParams.className = loader.class_name();
1398 dataLoaderParams.arguments = loader.arguments();
1399 }
1400
1401 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1402 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001403 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001404
Alex Buynytskyy04035452020-06-06 20:15:58 -07001405 // Check if marker file present.
1406 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001407 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001408 }
1409
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001410 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1411 auto d = openDir(root);
1412 while (auto e = ::readdir(d.get())) {
1413 if (e->d_type == DT_REG) {
1414 auto name = std::string_view(e->d_name);
1415 if (name.starts_with(constants().mountpointMdPrefix)) {
1416 permanentBindPoints
1417 .emplace_back(name,
1418 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1419 ifs->control,
1420 path::join(root,
1421 name)));
1422 if (permanentBindPoints.back().second.dest_path().empty() ||
1423 permanentBindPoints.back().second.source_subdir().empty()) {
1424 permanentBindPoints.pop_back();
1425 mIncFs->unlink(ifs->control, path::join(root, name));
1426 } else {
1427 LOG(INFO) << "Permanent bind record: '"
1428 << permanentBindPoints.back().second.source_subdir() << "'->'"
1429 << permanentBindPoints.back().second.dest_path() << "'";
1430 }
1431 }
1432 } else if (e->d_type == DT_DIR) {
1433 if (e->d_name == "."sv || e->d_name == ".."sv) {
1434 continue;
1435 }
1436 auto name = std::string_view(e->d_name);
1437 if (name.starts_with(constants().storagePrefix)) {
1438 int storageId;
1439 const auto res =
1440 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1441 name.data() + name.size(), storageId);
1442 if (res.ec != std::errc{} || *res.ptr != '_') {
1443 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1444 << "' for mount " << expectedRoot;
1445 continue;
1446 }
1447 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1448 if (!inserted) {
1449 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1450 << " for mount " << expectedRoot;
1451 continue;
1452 }
1453 ifs->storages.insert_or_assign(storageId,
1454 IncFsMount::Storage{path::join(root, name)});
1455 mNextId = std::max(mNextId, storageId + 1);
1456 }
1457 }
1458 }
1459
1460 if (ifs->storages.empty()) {
1461 LOG(WARNING) << "No valid storages in mount " << root;
1462 return;
1463 }
1464
1465 // now match the mounted directories with what we expect to have in the metadata
1466 {
1467 std::unique_lock l(mLock, std::defer_lock);
1468 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1469 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1470 [&, bindRecord = bindRecord](auto&& bind) {
1471 return bind.second == bindRecord.dest_path() &&
1472 path::join(root, bind.first) ==
1473 bindRecord.source_subdir();
1474 });
1475 if (mountedIt != binds.end()) {
1476 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1477 << " to mount " << mountedIt->first;
1478 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1479 std::move(*bindRecord.mutable_source_subdir()),
1480 std::move(*bindRecord.mutable_dest_path()),
1481 BindKind::Permanent);
1482 if (mountedIt != binds.end() - 1) {
1483 std::iter_swap(mountedIt, binds.end() - 1);
1484 }
1485 binds = binds.first(binds.size() - 1);
1486 } else {
1487 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1488 << ", mounting";
1489 // doesn't exist - try mounting back
1490 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1491 std::move(*bindRecord.mutable_source_subdir()),
1492 std::move(*bindRecord.mutable_dest_path()),
1493 BindKind::Permanent, l)) {
1494 mIncFs->unlink(ifs->control, metadataFile);
1495 }
1496 }
1497 }
1498 }
1499
1500 // if anything stays in |binds| those are probably temporary binds; system restarted since
1501 // they were mounted - so let's unmount them all.
1502 for (auto&& [source, target] : binds) {
1503 if (source.empty()) {
1504 continue;
1505 }
1506 mVold->unmountIncFs(std::string(target));
1507 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001508 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001509
1510 if (ifs->bindPoints.empty()) {
1511 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1512 deleteStorage(*ifs);
1513 return;
1514 }
1515
1516 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1517 CHECK(ifs->dataLoaderStub);
1518
1519 mountedRootNames.insert(path::basename(ifs->root));
1520
1521 // not locking here at all: we're still in the constructor, no other calls can happen
1522 mMounts[ifs->mountId] = std::move(ifs);
1523 });
1524
1525 return mountedRootNames;
1526}
1527
1528void IncrementalService::mountExistingImages(
1529 const std::unordered_set<std::string_view>& mountedRootNames) {
1530 auto dir = openDir(mIncrementalDir);
1531 if (!dir) {
1532 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1533 return;
1534 }
1535 while (auto entry = ::readdir(dir.get())) {
1536 if (entry->d_type != DT_DIR) {
1537 continue;
1538 }
1539 std::string_view name = entry->d_name;
1540 if (!name.starts_with(constants().mountKeyPrefix)) {
1541 continue;
1542 }
1543 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001544 continue;
1545 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001546 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001547 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001548 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001549 }
1550 }
1551}
1552
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001553bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001554 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001555 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001556
Songchun Fan3c82a302019-11-29 14:23:45 -08001557 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001558 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001559 if (!status.isOk()) {
1560 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1561 return false;
1562 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001563
1564 int cmd = controlParcel.cmd.release().release();
1565 int pendingReads = controlParcel.pendingReads.release().release();
1566 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001567 int blocksWritten =
1568 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1569 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001570
1571 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1572
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001573 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1574 path::join(mountTarget, constants().infoMdName));
1575 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001576 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1577 return false;
1578 }
1579
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001580 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001581 mNextId = std::max(mNextId, ifs->mountId + 1);
1582
Alex Buynytskyy04035452020-06-06 20:15:58 -07001583 // Check if marker file present.
1584 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001585 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001586 }
1587
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001588 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001589 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001590 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001591 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001592 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001593 dataLoaderParams.packageName = loader.package_name();
1594 dataLoaderParams.className = loader.class_name();
1595 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001596 }
1597
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001598 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001599 CHECK(ifs->dataLoaderStub);
1600
Songchun Fan3c82a302019-11-29 14:23:45 -08001601 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001602 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001603 while (auto e = ::readdir(d.get())) {
1604 if (e->d_type == DT_REG) {
1605 auto name = std::string_view(e->d_name);
1606 if (name.starts_with(constants().mountpointMdPrefix)) {
1607 bindPoints.emplace_back(name,
1608 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1609 ifs->control,
1610 path::join(mountTarget,
1611 name)));
1612 if (bindPoints.back().second.dest_path().empty() ||
1613 bindPoints.back().second.source_subdir().empty()) {
1614 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001615 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001616 }
1617 }
1618 } else if (e->d_type == DT_DIR) {
1619 if (e->d_name == "."sv || e->d_name == ".."sv) {
1620 continue;
1621 }
1622 auto name = std::string_view(e->d_name);
1623 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001624 int storageId;
1625 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1626 name.data() + name.size(), storageId);
1627 if (res.ec != std::errc{} || *res.ptr != '_') {
1628 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1629 << root;
1630 continue;
1631 }
1632 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001633 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001634 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001635 << " for mount " << root;
1636 continue;
1637 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001638 ifs->storages.insert_or_assign(storageId,
1639 IncFsMount::Storage{
1640 path::join(root, constants().mount, name)});
1641 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001642 }
1643 }
1644 }
1645
1646 if (ifs->storages.empty()) {
1647 LOG(WARNING) << "No valid storages in mount " << root;
1648 return false;
1649 }
1650
1651 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001652 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001653 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001654 for (auto&& bp : bindPoints) {
1655 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1656 std::move(*bp.second.mutable_source_subdir()),
1657 std::move(*bp.second.mutable_dest_path()),
1658 BindKind::Permanent, l);
1659 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001660 }
1661
1662 if (bindCount == 0) {
1663 LOG(WARNING) << "No valid bind points for mount " << root;
1664 deleteStorage(*ifs);
1665 return false;
1666 }
1667
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001668 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001669 mMounts[ifs->mountId] = std::move(ifs);
1670 return true;
1671}
1672
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001673void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001674 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001675 while (mRunning.load(std::memory_order_relaxed)) {
1676 mLooper->pollAll(kTimeoutMsecs);
1677 }
1678}
1679
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001680void IncrementalService::trimReservedSpaceV1(const IncFsMount& ifs) {
1681 mIncFs->forEachFile(ifs.control, [this](auto&& control, auto&& fileId) {
1682 if (mIncFs->isFileFullyLoaded(control, fileId) == incfs::LoadingState::Full) {
1683 mIncFs->reserveSpace(control, fileId, -1);
1684 }
1685 return true;
1686 });
1687}
1688
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001689void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001690 DataLoaderStatusListener&& statusListener,
1691 const StorageHealthCheckParams& healthCheckParams,
1692 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001693 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001694 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001695 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1696 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1697 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001698 if (ifs.control.blocksWritten() >= 0) {
1699 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1700 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001701 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001702
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001703 ifs.dataLoaderStub =
1704 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001705 std::move(statusListener), healthCheckParams,
1706 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001707
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001708 // pre-v2 IncFS doesn't do automatic reserved space trimming - need to run it manually
1709 if (!(mIncFs->features() & incfs::Features::v2)) {
1710 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1711 if (!state.fullyLoaded) {
1712 return true;
1713 }
1714
1715 const auto ifs = getIfs(storageId);
1716 if (!ifs) {
1717 return false;
1718 }
1719 trimReservedSpaceV1(*ifs);
1720 return false;
1721 });
1722 }
1723
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001724 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1725 if (!state.fullyLoaded || state.readLogsEnabled) {
1726 return true;
1727 }
1728
1729 DataLoaderStubPtr dataLoaderStub;
1730 {
1731 const auto ifs = getIfs(storageId);
1732 if (!ifs) {
1733 return false;
1734 }
1735
1736 std::unique_lock l(ifs->lock);
1737 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1738 }
1739
1740 if (dataLoaderStub) {
1741 dataLoaderStub->cleanupResources();
1742 }
1743
1744 return false;
1745 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001746}
1747
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001748template <class Duration>
1749static long elapsedMcs(Duration start, Duration end) {
1750 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1751}
1752
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001753template <class Duration>
1754static constexpr auto castToMs(Duration d) {
1755 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1756}
1757
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001758// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001759// Lib files should be placed next to the APK file in the following matter:
1760// Example:
1761// /path/to/base.apk
1762// /path/to/lib/arm/first.so
1763// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001764bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1765 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001766 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001767 auto start = Clock::now();
1768
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001769 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001770 if (!ifs) {
1771 LOG(ERROR) << "Invalid storage " << storage;
1772 return false;
1773 }
1774
Songchun Fanc8975312020-07-13 12:14:37 -07001775 const auto targetLibPathRelativeToStorage =
1776 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1777 libDirRelativePath);
1778
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001779 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001780 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1781 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001782 << " errno: " << res;
1783 return false;
1784 }
1785
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001786 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001787 ZipArchiveHandle zipFileHandle;
1788 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001789 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1790 return false;
1791 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001792
1793 // Need a shared pointer: will be passing it into all unpacking jobs.
1794 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001795 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001796 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001797 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001798 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1799 return false;
1800 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001801 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001802 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1803
1804 auto openZipTs = Clock::now();
1805
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001806 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1807 incfs::FileId sourceId;
1808 if (mapFiles) {
1809 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1810 if (!incfs::isValidFileId(sourceId)) {
1811 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1812 << "', mapping disabled";
1813 mapFiles = false;
1814 }
1815 }
1816
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001817 std::vector<Job> jobQueue;
1818 ZipEntry entry;
1819 std::string_view fileName;
1820 while (!Next(cookie, &entry, &fileName)) {
1821 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001822 continue;
1823 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001824
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001825 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001826 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001827
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001828 if (!extractNativeLibs) {
1829 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001830 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001831 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1832 return false;
1833 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001834 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001835 LOG(WARNING) << "Library " << fileName
1836 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1837 << entry.offset;
1838 return false;
1839 }
1840 continue;
1841 }
1842
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001843 auto startFileTs = Clock::now();
1844
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001845 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001846 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001847 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001848 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001849 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001850 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001851 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1852 << "; skipping extraction, spent "
1853 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1854 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001855 continue;
1856 }
1857
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001858 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1859 incfs::NewMappedFileParams mappedFileParams = {
1860 .sourceId = sourceId,
1861 .sourceOffset = entry.offset,
1862 .size = entry.uncompressed_length,
1863 };
1864
1865 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1866 mappedFileParams);
1867 res == 0) {
1868 if (perfLoggingEnabled()) {
1869 auto doneTs = Clock::now();
1870 LOG(INFO) << "incfs: Mapped " << libName << ": "
1871 << elapsedMcs(startFileTs, doneTs) << "mcs";
1872 }
1873 continue;
1874 } else {
1875 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1876 << "; falling back to full extraction";
1877 }
1878 }
1879
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001880 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001881 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001882 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001883 .signature = {},
1884 // Metadata of the new lib file is its relative path
1885 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1886 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001887 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001888 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001889 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001890 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001891 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001892 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001893 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001894
1895 auto makeFileTs = Clock::now();
1896
Songchun Fanafaf6e92020-03-18 14:12:20 -07001897 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001898 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001899 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001900 LOG(INFO) << "incfs: Extracted " << libName
1901 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001902 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001903 continue;
1904 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001905
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001906 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1907 libFileId, libPath = std::move(targetLibPath),
1908 makeFileTs]() mutable {
1909 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001910 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001911
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001912 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001913 auto prepareJobTs = Clock::now();
1914 LOG(INFO) << "incfs: Processed " << libName << ": "
1915 << elapsedMcs(startFileTs, prepareJobTs)
1916 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1917 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001918 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001919 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001920
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001921 auto processedTs = Clock::now();
1922
1923 if (!jobQueue.empty()) {
1924 {
1925 std::lock_guard lock(mJobMutex);
1926 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001927 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001928 if (existingJobs.empty()) {
1929 existingJobs = std::move(jobQueue);
1930 } else {
1931 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1932 std::move_iterator(jobQueue.end()));
1933 }
1934 }
1935 }
1936 mJobCondition.notify_all();
1937 }
1938
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001939 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001940 auto end = Clock::now();
1941 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1942 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1943 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001944 << " make files: " << elapsedMcs(openZipTs, processedTs)
1945 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001946 }
1947
1948 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001949}
1950
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001951void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1952 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001953 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001954 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001955 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001956 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001957 return;
1958 }
1959
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001960 auto startedTs = Clock::now();
1961
1962 // Write extracted data to new file
1963 // NOTE: don't zero-initialize memory, it may take a while for nothing
1964 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1965 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001966 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001967 return;
1968 }
1969
1970 auto extractFileTs = Clock::now();
1971
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001972 if (setFileContent(ifs, libFileId, debugLibPath,
1973 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001974 return;
1975 }
1976
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001977 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001978 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001979 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1980 << entry.compressed_length << " -> " << entry.uncompressed_length
1981 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001982 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1983 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001984 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001985 }
1986}
1987
1988bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001989 struct WaitPrinter {
1990 const Clock::time_point startTs = Clock::now();
1991 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001992 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001993 const auto endTs = Clock::now();
1994 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1995 << elapsedMcs(startTs, endTs) << "mcs";
1996 }
1997 }
1998 } waitPrinter;
1999
2000 MountId mount;
2001 {
2002 auto ifs = getIfs(storage);
2003 if (!ifs) {
2004 return true;
2005 }
2006 mount = ifs->mountId;
2007 }
2008
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002009 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002010 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002011 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002012 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002013 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002014 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002015}
2016
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002017int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
2018 std::string_view debugFilePath,
2019 std::span<const uint8_t> data) const {
2020 auto startTs = Clock::now();
2021
2022 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2023 if (!writeFd.ok()) {
2024 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2025 << " errno: " << writeFd.get();
2026 return writeFd.get();
2027 }
2028
2029 const auto dataLength = data.size();
2030
2031 auto openFileTs = Clock::now();
2032 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2033 std::vector<IncFsDataBlock> instructions(numBlocks);
2034 for (int i = 0; i < numBlocks; i++) {
2035 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2036 instructions[i] = IncFsDataBlock{
2037 .fileFd = writeFd.get(),
2038 .pageIndex = static_cast<IncFsBlockIndex>(i),
2039 .compression = INCFS_COMPRESSION_KIND_NONE,
2040 .kind = INCFS_BLOCK_KIND_DATA,
2041 .dataSize = static_cast<uint32_t>(blockSize),
2042 .data = reinterpret_cast<const char*>(data.data()),
2043 };
2044 data = data.subspan(blockSize);
2045 }
2046 auto prepareInstsTs = Clock::now();
2047
2048 size_t res = mIncFs->writeBlocks(instructions);
2049 if (res != instructions.size()) {
2050 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2051 return res;
2052 }
2053
2054 if (perfLoggingEnabled()) {
2055 auto endTs = Clock::now();
2056 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2057 << " bytes): " << elapsedMcs(startTs, endTs)
2058 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2059 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2060 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2061 }
2062
2063 return 0;
2064}
2065
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002066incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2067 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002068 std::unique_lock l(mLock);
2069 const auto ifs = getIfsLocked(storage);
2070 if (!ifs) {
2071 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002072 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002073 }
2074 const auto storageInfo = ifs->storages.find(storage);
2075 if (storageInfo == ifs->storages.end()) {
2076 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002077 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002078 }
2079 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002080 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002081}
2082
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002083incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2084 const auto ifs = getIfs(storage);
2085 if (!ifs) {
2086 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2087 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002088 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002089 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002090}
2091
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002092IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002093 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002094 std::unique_lock l(mLock);
2095 const auto ifs = getIfsLocked(storage);
2096 if (!ifs) {
2097 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002098 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002099 }
2100 const auto storageInfo = ifs->storages.find(storage);
2101 if (storageInfo == ifs->storages.end()) {
2102 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002103 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002104 }
2105 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002106 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002107}
2108
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002109IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002110 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002111 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2112 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002113 const auto [filledBlocksCount, totalBlocksCount] =
2114 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002115 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2116 filledBlocksCount == -ENOENT) {
2117 // a kind of a file that's not really being loaded, e.g. a mapped range
2118 // an older IncFS used to return ENOENT in this case, so handle it the same way
2119 return true;
2120 }
Songchun Fan374f7652020-08-20 08:40:29 -07002121 if (filledBlocksCount < 0) {
2122 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002123 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002124 error = filledBlocksCount;
2125 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002126 }
2127 totalBlocks += totalBlocksCount;
2128 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002129 return true;
2130 });
Songchun Fan374f7652020-08-20 08:40:29 -07002131
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002132 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002133}
2134
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002135bool IncrementalService::updateLoadingProgress(StorageId storage,
2136 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002137 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002138 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002139 // Failed to get progress from incfs, abort.
2140 return false;
2141 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002142 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2143 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002144 // Stop updating progress once it is fully loaded
2145 return true;
2146 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002147 addTimedJob(*mProgressUpdateJobQueue, storage,
2148 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002149 [storage, progressListener = std::move(progressListener), this]() mutable {
2150 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002151 });
2152 return true;
2153}
2154
2155bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002156 StorageId storage, StorageLoadingProgressListener progressListener) {
2157 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002158}
2159
2160bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2161 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2162}
2163
Songchun Fan2570ec02020-10-08 17:22:33 -07002164bool IncrementalService::registerStorageHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002165 StorageId storage, const StorageHealthCheckParams& healthCheckParams,
2166 StorageHealthListener healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002167 DataLoaderStubPtr dataLoaderStub;
2168 {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002169 const auto& ifs = getIfs(storage);
Songchun Fan2570ec02020-10-08 17:22:33 -07002170 if (!ifs) {
2171 return false;
2172 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002173 std::unique_lock l(ifs->lock);
Songchun Fan2570ec02020-10-08 17:22:33 -07002174 dataLoaderStub = ifs->dataLoaderStub;
2175 if (!dataLoaderStub) {
2176 return false;
2177 }
2178 }
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002179 dataLoaderStub->setHealthListener(healthCheckParams, std::move(healthListener));
Songchun Fan2570ec02020-10-08 17:22:33 -07002180 return true;
2181}
2182
2183void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002184 registerStorageHealthListener(storage, {}, {});
Songchun Fan2570ec02020-10-08 17:22:33 -07002185}
2186
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002187bool IncrementalService::perfLoggingEnabled() {
2188 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2189 return enabled;
2190}
2191
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002192void IncrementalService::runJobProcessing() {
2193 for (;;) {
2194 std::unique_lock lock(mJobMutex);
2195 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2196 if (!mRunning) {
2197 return;
2198 }
2199
2200 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002201 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002202 auto queue = std::move(it->second);
2203 mJobQueue.erase(it);
2204 lock.unlock();
2205
2206 for (auto&& job : queue) {
2207 job();
2208 }
2209
2210 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002211 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002212 lock.unlock();
2213 mJobCondition.notify_all();
2214 }
2215}
2216
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002217void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002218 sp<IAppOpsCallback> listener;
2219 {
2220 std::unique_lock lock{mCallbacksLock};
2221 auto& cb = mCallbackRegistered[packageName];
2222 if (cb) {
2223 return;
2224 }
2225 cb = new AppOpsListener(*this, packageName);
2226 listener = cb;
2227 }
2228
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002229 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2230 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002231}
2232
2233bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2234 sp<IAppOpsCallback> listener;
2235 {
2236 std::unique_lock lock{mCallbacksLock};
2237 auto found = mCallbackRegistered.find(packageName);
2238 if (found == mCallbackRegistered.end()) {
2239 return false;
2240 }
2241 listener = found->second;
2242 mCallbackRegistered.erase(found);
2243 }
2244
2245 mAppOpsManager->stopWatchingMode(listener);
2246 return true;
2247}
2248
2249void IncrementalService::onAppOpChanged(const std::string& packageName) {
2250 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002251 return;
2252 }
2253
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002254 std::vector<IfsMountPtr> affected;
2255 {
2256 std::lock_guard l(mLock);
2257 affected.reserve(mMounts.size());
2258 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002259 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002260 if (ifs->mountId == id && ifs->dataLoaderStub &&
2261 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002262 affected.push_back(ifs);
2263 }
2264 }
2265 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002266 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002267 std::unique_lock ll(ifs->lock);
2268 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002269 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002270}
2271
Songchun Fana7098592020-09-03 11:45:53 -07002272bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2273 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002274 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002275 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002276 }
Songchun Fana7098592020-09-03 11:45:53 -07002277 timedQueue.addJob(id, after, std::move(what));
2278 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002279}
2280
Songchun Fana7098592020-09-03 11:45:53 -07002281bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002282 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002283 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002284 }
Songchun Fana7098592020-09-03 11:45:53 -07002285 timedQueue.removeJobs(id);
2286 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002287}
2288
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002289void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2290 bool wasEmpty;
2291 {
2292 std::lock_guard l(mIfsStateCallbacksLock);
2293 wasEmpty = mIfsStateCallbacks.empty();
2294 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2295 }
2296 if (wasEmpty) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002297 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002298 [this]() { processIfsStateCallbacks(); });
2299 }
2300}
2301
2302void IncrementalService::processIfsStateCallbacks() {
2303 StorageId storageId = kInvalidStorageId;
2304 std::vector<IfsStateCallback> local;
2305 while (true) {
2306 {
2307 std::lock_guard l(mIfsStateCallbacksLock);
2308 if (mIfsStateCallbacks.empty()) {
2309 return;
2310 }
2311 IfsStateCallbacks::iterator it;
2312 if (storageId == kInvalidStorageId) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002313 // First entry, initialize the |it|.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002314 it = mIfsStateCallbacks.begin();
2315 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002316 // Subsequent entries, update the |storageId|, and shift to the new one (not that
2317 // it guarantees much about updated items, but at least the loop will finish).
2318 it = mIfsStateCallbacks.lower_bound(storageId);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002319 if (it == mIfsStateCallbacks.end()) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002320 // Nothing else left, too bad.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002321 break;
2322 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002323 if (it->first != storageId) {
2324 local.clear(); // Was removed during processing, forget the old callbacks.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002325 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002326 // Put the 'surviving' callbacks back into the map and advance the position.
2327 auto& callbacks = it->second;
2328 if (callbacks.empty()) {
2329 std::swap(callbacks, local);
2330 } else {
2331 callbacks.insert(callbacks.end(), std::move_iterator(local.begin()),
2332 std::move_iterator(local.end()));
2333 local.clear();
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002334 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002335 if (callbacks.empty()) {
2336 it = mIfsStateCallbacks.erase(it);
2337 if (mIfsStateCallbacks.empty()) {
2338 return;
2339 }
2340 } else {
2341 ++it;
2342 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002343 }
2344 }
2345
2346 if (it == mIfsStateCallbacks.end()) {
2347 break;
2348 }
2349
2350 storageId = it->first;
2351 auto& callbacks = it->second;
2352 if (callbacks.empty()) {
2353 // Invalid case, one extra lookup should be ok.
2354 continue;
2355 }
2356 std::swap(callbacks, local);
2357 }
2358
2359 processIfsStateCallbacks(storageId, local);
2360 }
2361
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002362 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002363 [this]() { processIfsStateCallbacks(); });
2364}
2365
2366void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2367 std::vector<IfsStateCallback>& callbacks) {
2368 const auto state = isMountFullyLoaded(storageId);
2369 IfsState storageState = {};
2370 storageState.error = int(state) < 0;
2371 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2372 if (storageState.fullyLoaded) {
2373 const auto ifs = getIfs(storageId);
2374 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2375 }
2376
2377 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2378 if ((*cur)(storageId, storageState)) {
2379 ++cur;
2380 } else {
2381 cur = callbacks.erase(cur);
2382 }
2383 }
2384}
2385
2386void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2387 std::lock_guard l(mIfsStateCallbacksLock);
2388 mIfsStateCallbacks.erase(storageId);
2389}
2390
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002391void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
2392 const auto duration = getMillsSinceOldestPendingRead(storageId);
2393 if (duration >= 0) {
2394 const auto kMetricsMillisSinceOldestPendingRead =
2395 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2396 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2397 }
2398}
2399
2400long IncrementalService::getMillsSinceOldestPendingRead(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002401 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002402 if (!ifs) {
2403 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, invalid storageId: " << storageId;
2404 return -EINVAL;
2405 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002406 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002407 if (!ifs->dataLoaderStub) {
2408 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, no data loader: " << storageId;
2409 return -EINVAL;
2410 }
2411 return ifs->dataLoaderStub->elapsedMsSinceOldestPendingRead();
2412}
2413
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002414IncrementalService::DataLoaderStub::DataLoaderStub(
2415 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2416 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2417 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2418 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002419 : mService(service),
2420 mId(id),
2421 mParams(std::move(params)),
2422 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002423 mStatusListener(std::move(statusListener)),
2424 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002425 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002426 mHealthCheckParams(healthCheckParams) {
2427 if (mHealthListener && !isHealthParamsValid()) {
2428 mHealthListener = {};
2429 }
2430 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002431 // Disable advanced health check statuses.
2432 mHealthCheckParams.blockedTimeoutMs = -1;
2433 }
2434 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002435}
2436
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002437IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002438 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002439 cleanupResources();
2440 }
2441}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002442
2443void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002444 auto now = Clock::now();
2445 {
2446 std::unique_lock lock(mMutex);
2447 mHealthPath.clear();
2448 unregisterFromPendingReads();
2449 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002450 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002451 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002452 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002453
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002454 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002455
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002456 {
2457 std::unique_lock lock(mMutex);
2458 mParams = {};
2459 mControl = {};
2460 mHealthControl = {};
2461 mHealthListener = {};
2462 mStatusCondition.wait_until(lock, now + 60s, [this] {
2463 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2464 });
2465 mStatusListener = {};
2466 mId = kInvalidStorageId;
2467 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002468}
2469
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002470sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2471 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002472 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002473 if (!status.isOk()) {
2474 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2475 return {};
2476 }
2477 if (!dataloader) {
2478 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2479 return {};
2480 }
2481 return dataloader;
2482}
2483
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002484bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2485 return (params().packageName == Constants::systemPackage);
2486}
2487
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002488bool IncrementalService::DataLoaderStub::requestCreate() {
2489 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2490}
2491
2492bool IncrementalService::DataLoaderStub::requestStart() {
2493 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2494}
2495
2496bool IncrementalService::DataLoaderStub::requestDestroy() {
2497 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2498}
2499
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002500bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002501 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002502 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002503 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002504 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002505 return fsmStep();
2506}
2507
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002508void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002509 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002510 mTargetStatus = status;
2511 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002512 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002513 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002514}
2515
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002516std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002517 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002518
2519 const auto now = mService.mClock->now();
2520 const bool healthy = (mPreviousBindDelay == 0ms);
2521
2522 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2523 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2524 LOG(INFO) << "Binding still in progress. "
2525 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002526 : "Already unhealthy, don't do anything.")
2527 << " for storage " << mId;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002528 // Binding still in progress.
2529 if (!healthy) {
2530 // Already unhealthy, don't do anything.
2531 return {};
2532 }
2533 // The DL is healthy/freshly bound, ok to retry for a few times.
2534 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2535 // Still within grace period.
2536 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2537 // Retry interval passed, retrying.
2538 mCurrentStatusTs = now;
2539 mPreviousBindDelay = 0ms;
2540 return 0ms;
2541 }
2542 return {};
2543 }
2544 // fallthrough, mark as unhealthy, and retry with delay
2545 }
2546
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002547 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002548 mPreviousBindTs = now;
2549
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002550 const auto nonCrashingInterval =
2551 std::max(castToMs(now - previousBindTs - mPreviousBindDelay), 100ms);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002552 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2553 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2554 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002555 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002556 }
2557
2558 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2559 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2560
2561 const auto bindDelayMs =
2562 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2563 maxBindDelayMs)
2564 .count();
2565 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2566 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2567 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002568 return mPreviousBindDelay;
2569}
2570
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002571bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002572 const auto maybeBindDelay = needToBind();
2573 if (!maybeBindDelay) {
2574 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2575 return true;
2576 }
2577 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002578 if (bindDelay > 1s) {
2579 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002580 << bindDelay.count() / 1000 << "s"
2581 << " for storage " << mId;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002582 }
2583
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002584 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002585 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2586 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002587 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002588 const bool healthy = (bindDelay == 0ms);
2589 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2590 << (healthy ? ", retrying." : "");
2591
2592 // Internal error, retry for healthy/new DLs.
2593 // Let needToBind migrate it to unhealthy after too many retries.
2594 if (healthy) {
2595 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2596 [this]() { fsmStep(); })) {
2597 // Mark as binding so that we know it's not the DL's fault.
2598 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2599 return true;
2600 }
2601 }
2602
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002603 return false;
2604 }
2605 return true;
2606}
2607
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002608bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002609 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002610 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002611 return false;
2612 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002613 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002614 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002615 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002616 return false;
2617 }
2618 return true;
2619}
2620
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002621bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002622 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002623 if (!dataloader) {
2624 return false;
2625 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002626 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002627 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002628 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002629 return false;
2630 }
2631 return true;
2632}
2633
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002634bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002635 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002636}
2637
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002638bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002639 if (!isValid()) {
2640 return false;
2641 }
2642
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002643 int currentStatus;
2644 int targetStatus;
2645 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002646 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002647 currentStatus = mCurrentStatus;
2648 targetStatus = mTargetStatus;
2649 }
2650
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002651 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002652
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002653 if (currentStatus == targetStatus) {
2654 return true;
2655 }
2656
2657 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002658 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2659 // Do nothing, this is a reset state.
2660 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002661 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002662 switch (currentStatus) {
2663 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2664 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2665 return true;
2666 default:
2667 return destroy();
2668 }
2669 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002670 }
2671 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2672 switch (currentStatus) {
2673 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2674 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2675 return start();
2676 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002677 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002678 }
2679 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2680 switch (currentStatus) {
2681 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002682 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002683 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002684 return bind();
2685 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002686 return create();
2687 }
2688 break;
2689 default:
2690 LOG(ERROR) << "Invalid target status: " << targetStatus
2691 << ", current status: " << currentStatus;
2692 break;
2693 }
2694 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002695}
2696
2697binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002698 if (!isValid()) {
2699 return binder::Status::
2700 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2701 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002702 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002703 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2704 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002705 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2706 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002707 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2708 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2709 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2710 [this, newStatus]() { setCurrentStatus(newStatus); });
2711 return binder::Status::ok();
2712 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002713
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002714 setCurrentStatus(newStatus);
2715 return binder::Status::ok();
2716}
2717
2718void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002719 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002720 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002721 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002722 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002723 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002724 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002725 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002726
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002727 oldStatus = mCurrentStatus;
2728 targetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002729 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002730
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002731 // Change the status.
2732 mCurrentStatus = newStatus;
2733 mCurrentStatusTs = mService.mClock->now();
2734
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002735 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2736 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002737 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2738 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002739 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002740 }
2741
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002742 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002743 << newStatus << " (target " << targetStatus << ")";
2744
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002745 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002746 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002747 }
2748
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002749 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002750
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002751 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002752}
2753
Songchun Fan33093982020-09-10 13:12:39 -07002754binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2755 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002756 if (!isValid()) {
2757 return binder::Status::
2758 fromServiceSpecificError(-EINVAL,
2759 "reportStreamHealth came to invalid DataLoaderStub");
2760 }
2761 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002762 LOG(ERROR) << "reportStreamHealth: mount ID mismatch: expected " << id()
2763 << ", but got: " << mountId;
Songchun Fan2570ec02020-10-08 17:22:33 -07002764 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2765 }
2766 {
2767 std::lock_guard lock(mMutex);
2768 mStreamStatus = newStatus;
2769 }
Songchun Fan33093982020-09-10 13:12:39 -07002770 return binder::Status::ok();
2771}
2772
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002773bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2774 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2775 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002776}
2777
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002778void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002779 int healthStatus) {
2780 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2781 if (healthListener) {
2782 healthListener->onHealthStatus(id(), healthStatus);
2783 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002784}
2785
Songchun Fan2570ec02020-10-08 17:22:33 -07002786static int adjustHealthStatus(int healthStatus, int streamStatus) {
2787 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2788 // everything is good; no need to change status
2789 return healthStatus;
2790 }
2791 int newHeathStatus = healthStatus;
2792 switch (streamStatus) {
2793 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2794 // storage is limited and storage not healthy
2795 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2796 break;
2797 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2798 // fall through
2799 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2800 // fall through
2801 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2802 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2803 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2804 }
2805 // pending/blocked status due to transportation issues is not regarded as unhealthy
2806 break;
2807 default:
2808 break;
2809 }
2810 return newHeathStatus;
2811}
2812
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002813void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2814 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002815
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002816 int healthStatusToReport = -1;
2817 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002818
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002819 {
2820 std::unique_lock lock(mMutex);
2821 unregisterFromPendingReads();
2822
2823 healthListener = mHealthListener;
2824
2825 // Healthcheck depends on timestamp of the oldest pending read.
2826 // 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 -07002827 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2828 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002829 const auto now = Clock::now();
2830 const auto kernelTsUs = getOldestPendingReadTs();
2831 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002832 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2833 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002834 mHealthBase = {now, kernelTsUs};
2835 }
2836
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002837 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2838 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002839 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2840 registerForPendingReads();
2841 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2842 lock.unlock();
2843 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002844 return;
2845 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002846
2847 resetHealthControl();
2848
2849 // Always make sure the data loader is started.
2850 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2851
2852 // Skip any further processing if health check params are invalid.
2853 if (!isHealthParamsValid()) {
2854 LOG(DEBUG) << id()
2855 << ": Skip any further processing if health check params are invalid.";
2856 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2857 lock.unlock();
2858 onHealthStatus(healthListener, healthStatusToReport);
2859 // Triggering data loader start. This is a one-time action.
2860 fsmStep();
2861 return;
2862 }
2863
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002864 // Don't schedule timer job less than 500ms in advance.
2865 static constexpr auto kTolerance = 500ms;
2866
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002867 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2868 const auto unhealthyTimeout =
2869 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2870 const auto unhealthyMonitoring =
2871 std::max(1000ms,
2872 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2873
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002874 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002875
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002876 Milliseconds checkBackAfter;
2877 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002878 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002879 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002880 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002881 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002882 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002883 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002884 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2885 } else {
2886 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002887 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002888 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2889 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002890 // Adjust health status based on stream status
2891 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002892 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002893 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002894 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2895 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002896 }
2897
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002898 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002899 if (healthStatusToReport != -1) {
2900 onHealthStatus(healthListener, healthStatusToReport);
2901 }
2902
2903 fsmStep();
2904}
2905
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002906Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2907 BootClockTsUs kernelTsUs) {
2908 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2909 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2910 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2911}
2912
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002913const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2914 if (mHealthPath.empty()) {
2915 resetHealthControl();
2916 return mHealthControl;
2917 }
2918 if (mHealthControl.pendingReads() < 0) {
2919 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2920 }
2921 if (mHealthControl.pendingReads() < 0) {
2922 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2923 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2924 << mHealthControl.logs() << ")";
2925 }
2926 return mHealthControl;
2927}
2928
2929void IncrementalService::DataLoaderStub::resetHealthControl() {
2930 mHealthControl = {};
2931}
2932
2933BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2934 auto result = kMaxBootClockTsUs;
2935
2936 const auto& control = initializeHealthControl();
2937 if (control.pendingReads() < 0) {
2938 return result;
2939 }
2940
Songchun Fan6944f1e2020-11-06 15:24:24 -08002941 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002942 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002943 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002944 // Clear previous pending reads
2945 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002946 return result;
2947 }
2948
2949 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002950 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002951
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002952 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002953}
2954
2955void IncrementalService::DataLoaderStub::registerForPendingReads() {
2956 const auto pendingReadsFd = mHealthControl.pendingReads();
2957 if (pendingReadsFd < 0) {
2958 return;
2959 }
2960
2961 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2962
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002963 mService.mLooper->addFd(
2964 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2965 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002966 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002967 self->updateHealthStatus(/*baseline=*/true);
2968 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002969 },
2970 this);
2971 mService.mLooper->wake();
2972}
2973
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002974BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2975 auto result = kMaxBootClockTsUs;
2976 for (auto&& pendingRead : mLastPendingReads) {
2977 result = std::min(result, pendingRead.bootClockTsUs);
2978 }
2979 return result;
2980}
2981
2982long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
2983 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
2984 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
2985 return 0;
2986 }
2987 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
2988}
2989
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002990void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002991 const auto pendingReadsFd = mHealthControl.pendingReads();
2992 if (pendingReadsFd < 0) {
2993 return;
2994 }
2995
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002996 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2997
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002998 mService.mLooper->removeFd(pendingReadsFd);
2999 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003000}
3001
Songchun Fan2570ec02020-10-08 17:22:33 -07003002void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003003 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07003004 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003005 mHealthCheckParams = healthCheckParams;
3006 mHealthListener = std::move(healthListener);
3007 if (!mHealthListener) {
3008 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07003009 }
3010}
3011
Songchun Fan6944f1e2020-11-06 15:24:24 -08003012static std::string toHexString(const RawMetadata& metadata) {
3013 int n = metadata.size();
3014 std::string res(n * 2, '\0');
3015 // Same as incfs::toString(fileId)
3016 static constexpr char kHexChar[] = "0123456789abcdef";
3017 for (int i = 0; i < n; ++i) {
3018 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
3019 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
3020 }
3021 return res;
3022}
3023
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003024void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003025 dprintf(fd, " dataLoader: {\n");
3026 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08003027 dprintf(fd, " currentStatusTs: %lldmcs\n",
3028 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003029 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
3030 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003031 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003032 dprintf(fd, " health: {\n");
3033 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3034 dprintf(fd, " base: %lldmcs (%lld)\n",
3035 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3036 (long long)mHealthBase.kernelTsUs);
3037 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3038 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3039 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3040 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003041 dprintf(fd, " lastPendingReads: \n");
3042 const auto control = mService.mIncFs->openMount(mHealthPath);
3043 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003044 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003045 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3046 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3047 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3048 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3049 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003050 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
3051 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
3052 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003053 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003054 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003055 dprintf(fd, " dataLoaderParams: {\n");
3056 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3057 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3058 dprintf(fd, " className: %s\n", params.className.c_str());
3059 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3060 dprintf(fd, " }\n");
3061 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003062}
3063
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003064void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3065 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003066}
3067
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003068binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3069 bool enableReadLogs, int32_t* _aidl_return) {
3070 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3071 return binder::Status::ok();
3072}
3073
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003074FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3075 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3076}
3077
Songchun Fan3c82a302019-11-29 14:23:45 -08003078} // namespace android::incremental