blob: 217b621e54ab6148cdd8a51c60af8c91f1399a94 [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) {
1089 // Only v2+ incfs supports automatically trimming file over-reserved sizes
1090 if (mIncFs->features() & incfs::Features::v2) {
1091 if (auto err = mIncFs->reserveSpace(ifs->control, normPath, params.size)) {
1092 if (err != -EOPNOTSUPP) {
1093 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1094 (void)mIncFs->unlink(ifs->control, normPath);
1095 return err;
1096 } else {
1097 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1098 "may run out of disk later";
1099 }
1100 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001101 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001102 if (!data.empty()) {
1103 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001104 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001105 return err;
1106 }
1107 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001108 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001109 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001110}
1111
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001112int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001113 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001114 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001115 if (normPath.empty()) {
1116 return -EINVAL;
1117 }
1118 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001119 }
1120 return -EINVAL;
1121}
1122
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001123int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001124 const auto ifs = getIfs(storageId);
1125 if (!ifs) {
1126 return -EINVAL;
1127 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001128 return makeDirs(*ifs, storageId, path, mode);
1129}
1130
1131int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1132 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001133 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1134 if (normPath.empty()) {
1135 return -EINVAL;
1136 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001137 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001138}
1139
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001140int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1141 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001142 std::unique_lock l(mLock);
1143 auto ifsSrc = getIfsLocked(sourceStorageId);
1144 if (!ifsSrc) {
1145 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001146 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001147 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1148 return -EINVAL;
1149 }
1150 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001151 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1152 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001153 if (normOldPath.empty() || normNewPath.empty()) {
1154 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1155 return -EINVAL;
1156 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001157 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1158 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1159 << " to " << newPath << "[" << normNewPath << "]";
1160 return err;
1161 }
1162 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001163}
1164
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001165int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001166 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001167 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001168 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001169 }
1170 return -EINVAL;
1171}
1172
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001173int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1174 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001175 std::string&& target, BindKind kind,
1176 std::unique_lock<std::mutex>& mainLock) {
1177 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001178 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001179 return -EINVAL;
1180 }
1181
1182 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001183 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001184 if (kind != BindKind::Temporary) {
1185 metadata::BindPoint bp;
1186 bp.set_storage_id(storage);
1187 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001188 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001189 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001190 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001191 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001192 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001193 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1194 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1195 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001196 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001197 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001198 return int(node);
1199 }
1200 }
1201
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001202 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1203 std::move(target), kind, mainLock);
1204 if (res) {
1205 mIncFs->unlink(ifs.control, metadataFullPath);
1206 }
1207 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001208}
1209
1210int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001211 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001212 std::string&& target, BindKind kind,
1213 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001214 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001215 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001216 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001217 if (!status.isOk()) {
1218 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1219 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1220 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1221 : status.serviceSpecificErrorCode() == 0
1222 ? -EFAULT
1223 : status.serviceSpecificErrorCode()
1224 : -EIO;
1225 }
1226 }
1227
1228 if (!mainLock.owns_lock()) {
1229 mainLock.lock();
1230 }
1231 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001232 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1233 std::move(target), kind);
1234 return 0;
1235}
1236
1237void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1238 std::string&& metadataName, std::string&& source,
1239 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001240 const auto [it, _] =
1241 ifs.bindPoints.insert_or_assign(target,
1242 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001243 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001244 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001245}
1246
1247RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1248 const auto ifs = getIfs(storage);
1249 if (!ifs) {
1250 return {};
1251 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001252 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001253 if (normPath.empty()) {
1254 return {};
1255 }
1256 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001257}
1258
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001259RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001260 const auto ifs = getIfs(storage);
1261 if (!ifs) {
1262 return {};
1263 }
1264 return mIncFs->getMetadata(ifs->control, node);
1265}
1266
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001267void IncrementalService::setUidReadTimeouts(StorageId storage,
1268 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001269 using microseconds = std::chrono::microseconds;
1270 using milliseconds = std::chrono::milliseconds;
1271
1272 auto maxPendingTimeUs = microseconds(0);
1273 for (const auto& timeouts : perUidReadTimeouts) {
1274 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1275 }
1276 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyy2b2f5f72021-01-29 11:07:33 -08001277 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001278 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1279 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001280 return;
1281 }
1282
1283 const auto ifs = getIfs(storage);
1284 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001285 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001286 return;
1287 }
1288
1289 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1290 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1291 return;
1292 }
1293
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001294 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1295 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1296 if (checkUidReadTimeouts(storageId, state, timeout)) {
1297 return true;
1298 }
1299 clearUidReadTimeouts(storageId);
1300 return false;
1301 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001302}
1303
1304void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1305 const auto ifs = getIfs(storage);
1306 if (!ifs) {
1307 return;
1308 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001309 mIncFs->setUidReadTimeouts(ifs->control, {});
1310}
1311
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001312bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1313 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001314 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001315 // Reached maximum timeout.
1316 return false;
1317 }
1318 if (state.error) {
1319 // Something is wrong, abort.
1320 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001321 }
1322
1323 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001324 if (state.fullyLoaded && !state.readLogsEnabled) {
1325 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001326 }
1327
1328 const auto timeLeft = timeLimit - Clock::now();
1329 if (timeLeft < Constants::progressUpdateInterval) {
1330 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001331 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001332 }
1333
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001334 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001335}
1336
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001337std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1338 std::unordered_set<std::string_view> mountedRootNames;
1339 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1340 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1341 for (auto [source, target] : binds) {
1342 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1343 LOG(INFO) << " " << path::join(root, source);
1344 }
1345
1346 // Ensure it's a kind of a mount that's managed by IncrementalService
1347 if (path::basename(root) != constants().mount ||
1348 path::basename(backingDir) != constants().backing) {
1349 return;
1350 }
1351 const auto expectedRoot = path::dirname(root);
1352 if (path::dirname(backingDir) != expectedRoot) {
1353 return;
1354 }
1355 if (path::dirname(expectedRoot) != mIncrementalDir) {
1356 return;
1357 }
1358 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1359 return;
1360 }
1361
1362 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1363
1364 // make sure we clean up the mount if it happens to be a bad one.
1365 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1366 auto cleanupFiles = makeCleanup([&]() {
1367 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1368 IncFsMount::cleanupFilesystem(expectedRoot);
1369 });
1370 auto cleanupMounts = makeCleanup([&]() {
1371 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1372 for (auto&& [_, target] : binds) {
1373 mVold->unmountIncFs(std::string(target));
1374 }
1375 mVold->unmountIncFs(std::string(root));
1376 });
1377
1378 auto control = mIncFs->openMount(root);
1379 if (!control) {
1380 LOG(INFO) << "failed to open mount " << root;
1381 return;
1382 }
1383
1384 auto mountRecord =
1385 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1386 path::join(root, constants().infoMdName));
1387 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1388 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1389 return;
1390 }
1391
1392 auto mountId = mountRecord.storage().id();
1393 mNextId = std::max(mNextId, mountId + 1);
1394
1395 DataLoaderParamsParcel dataLoaderParams;
1396 {
1397 const auto& loader = mountRecord.loader();
1398 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1399 dataLoaderParams.packageName = loader.package_name();
1400 dataLoaderParams.className = loader.class_name();
1401 dataLoaderParams.arguments = loader.arguments();
1402 }
1403
1404 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1405 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001406 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001407
Alex Buynytskyy04035452020-06-06 20:15:58 -07001408 // Check if marker file present.
1409 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001410 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001411 }
1412
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001413 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1414 auto d = openDir(root);
1415 while (auto e = ::readdir(d.get())) {
1416 if (e->d_type == DT_REG) {
1417 auto name = std::string_view(e->d_name);
1418 if (name.starts_with(constants().mountpointMdPrefix)) {
1419 permanentBindPoints
1420 .emplace_back(name,
1421 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1422 ifs->control,
1423 path::join(root,
1424 name)));
1425 if (permanentBindPoints.back().second.dest_path().empty() ||
1426 permanentBindPoints.back().second.source_subdir().empty()) {
1427 permanentBindPoints.pop_back();
1428 mIncFs->unlink(ifs->control, path::join(root, name));
1429 } else {
1430 LOG(INFO) << "Permanent bind record: '"
1431 << permanentBindPoints.back().second.source_subdir() << "'->'"
1432 << permanentBindPoints.back().second.dest_path() << "'";
1433 }
1434 }
1435 } else if (e->d_type == DT_DIR) {
1436 if (e->d_name == "."sv || e->d_name == ".."sv) {
1437 continue;
1438 }
1439 auto name = std::string_view(e->d_name);
1440 if (name.starts_with(constants().storagePrefix)) {
1441 int storageId;
1442 const auto res =
1443 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1444 name.data() + name.size(), storageId);
1445 if (res.ec != std::errc{} || *res.ptr != '_') {
1446 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1447 << "' for mount " << expectedRoot;
1448 continue;
1449 }
1450 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1451 if (!inserted) {
1452 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1453 << " for mount " << expectedRoot;
1454 continue;
1455 }
1456 ifs->storages.insert_or_assign(storageId,
1457 IncFsMount::Storage{path::join(root, name)});
1458 mNextId = std::max(mNextId, storageId + 1);
1459 }
1460 }
1461 }
1462
1463 if (ifs->storages.empty()) {
1464 LOG(WARNING) << "No valid storages in mount " << root;
1465 return;
1466 }
1467
1468 // now match the mounted directories with what we expect to have in the metadata
1469 {
1470 std::unique_lock l(mLock, std::defer_lock);
1471 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1472 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1473 [&, bindRecord = bindRecord](auto&& bind) {
1474 return bind.second == bindRecord.dest_path() &&
1475 path::join(root, bind.first) ==
1476 bindRecord.source_subdir();
1477 });
1478 if (mountedIt != binds.end()) {
1479 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1480 << " to mount " << mountedIt->first;
1481 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1482 std::move(*bindRecord.mutable_source_subdir()),
1483 std::move(*bindRecord.mutable_dest_path()),
1484 BindKind::Permanent);
1485 if (mountedIt != binds.end() - 1) {
1486 std::iter_swap(mountedIt, binds.end() - 1);
1487 }
1488 binds = binds.first(binds.size() - 1);
1489 } else {
1490 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1491 << ", mounting";
1492 // doesn't exist - try mounting back
1493 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1494 std::move(*bindRecord.mutable_source_subdir()),
1495 std::move(*bindRecord.mutable_dest_path()),
1496 BindKind::Permanent, l)) {
1497 mIncFs->unlink(ifs->control, metadataFile);
1498 }
1499 }
1500 }
1501 }
1502
1503 // if anything stays in |binds| those are probably temporary binds; system restarted since
1504 // they were mounted - so let's unmount them all.
1505 for (auto&& [source, target] : binds) {
1506 if (source.empty()) {
1507 continue;
1508 }
1509 mVold->unmountIncFs(std::string(target));
1510 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001511 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001512
1513 if (ifs->bindPoints.empty()) {
1514 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1515 deleteStorage(*ifs);
1516 return;
1517 }
1518
1519 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1520 CHECK(ifs->dataLoaderStub);
1521
1522 mountedRootNames.insert(path::basename(ifs->root));
1523
1524 // not locking here at all: we're still in the constructor, no other calls can happen
1525 mMounts[ifs->mountId] = std::move(ifs);
1526 });
1527
1528 return mountedRootNames;
1529}
1530
1531void IncrementalService::mountExistingImages(
1532 const std::unordered_set<std::string_view>& mountedRootNames) {
1533 auto dir = openDir(mIncrementalDir);
1534 if (!dir) {
1535 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1536 return;
1537 }
1538 while (auto entry = ::readdir(dir.get())) {
1539 if (entry->d_type != DT_DIR) {
1540 continue;
1541 }
1542 std::string_view name = entry->d_name;
1543 if (!name.starts_with(constants().mountKeyPrefix)) {
1544 continue;
1545 }
1546 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001547 continue;
1548 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001549 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001550 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001551 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001552 }
1553 }
1554}
1555
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001556bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001557 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001558 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001559
Songchun Fan3c82a302019-11-29 14:23:45 -08001560 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001561 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001562 if (!status.isOk()) {
1563 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1564 return false;
1565 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001566
1567 int cmd = controlParcel.cmd.release().release();
1568 int pendingReads = controlParcel.pendingReads.release().release();
1569 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001570 int blocksWritten =
1571 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1572 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001573
1574 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1575
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001576 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1577 path::join(mountTarget, constants().infoMdName));
1578 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001579 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1580 return false;
1581 }
1582
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001583 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001584 mNextId = std::max(mNextId, ifs->mountId + 1);
1585
Alex Buynytskyy04035452020-06-06 20:15:58 -07001586 // Check if marker file present.
1587 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001588 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001589 }
1590
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001591 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001592 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001593 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001594 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001595 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001596 dataLoaderParams.packageName = loader.package_name();
1597 dataLoaderParams.className = loader.class_name();
1598 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001599 }
1600
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001601 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001602 CHECK(ifs->dataLoaderStub);
1603
Songchun Fan3c82a302019-11-29 14:23:45 -08001604 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001605 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001606 while (auto e = ::readdir(d.get())) {
1607 if (e->d_type == DT_REG) {
1608 auto name = std::string_view(e->d_name);
1609 if (name.starts_with(constants().mountpointMdPrefix)) {
1610 bindPoints.emplace_back(name,
1611 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1612 ifs->control,
1613 path::join(mountTarget,
1614 name)));
1615 if (bindPoints.back().second.dest_path().empty() ||
1616 bindPoints.back().second.source_subdir().empty()) {
1617 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001618 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001619 }
1620 }
1621 } else if (e->d_type == DT_DIR) {
1622 if (e->d_name == "."sv || e->d_name == ".."sv) {
1623 continue;
1624 }
1625 auto name = std::string_view(e->d_name);
1626 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001627 int storageId;
1628 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1629 name.data() + name.size(), storageId);
1630 if (res.ec != std::errc{} || *res.ptr != '_') {
1631 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1632 << root;
1633 continue;
1634 }
1635 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001636 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001637 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001638 << " for mount " << root;
1639 continue;
1640 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001641 ifs->storages.insert_or_assign(storageId,
1642 IncFsMount::Storage{
1643 path::join(root, constants().mount, name)});
1644 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001645 }
1646 }
1647 }
1648
1649 if (ifs->storages.empty()) {
1650 LOG(WARNING) << "No valid storages in mount " << root;
1651 return false;
1652 }
1653
1654 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001655 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001656 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001657 for (auto&& bp : bindPoints) {
1658 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1659 std::move(*bp.second.mutable_source_subdir()),
1660 std::move(*bp.second.mutable_dest_path()),
1661 BindKind::Permanent, l);
1662 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001663 }
1664
1665 if (bindCount == 0) {
1666 LOG(WARNING) << "No valid bind points for mount " << root;
1667 deleteStorage(*ifs);
1668 return false;
1669 }
1670
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001671 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001672 mMounts[ifs->mountId] = std::move(ifs);
1673 return true;
1674}
1675
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001676void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001677 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001678 while (mRunning.load(std::memory_order_relaxed)) {
1679 mLooper->pollAll(kTimeoutMsecs);
1680 }
1681}
1682
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001683void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001684 DataLoaderStatusListener&& statusListener,
1685 const StorageHealthCheckParams& healthCheckParams,
1686 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001687 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001688 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001689 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1690 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1691 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001692 if (ifs.control.blocksWritten() >= 0) {
1693 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1694 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001695 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001696
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001697 ifs.dataLoaderStub =
1698 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001699 std::move(statusListener), healthCheckParams,
1700 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001701
1702 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1703 if (!state.fullyLoaded || state.readLogsEnabled) {
1704 return true;
1705 }
1706
1707 DataLoaderStubPtr dataLoaderStub;
1708 {
1709 const auto ifs = getIfs(storageId);
1710 if (!ifs) {
1711 return false;
1712 }
1713
1714 std::unique_lock l(ifs->lock);
1715 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1716 }
1717
1718 if (dataLoaderStub) {
1719 dataLoaderStub->cleanupResources();
1720 }
1721
1722 return false;
1723 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001724}
1725
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001726template <class Duration>
1727static long elapsedMcs(Duration start, Duration end) {
1728 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1729}
1730
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001731template <class Duration>
1732static constexpr auto castToMs(Duration d) {
1733 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1734}
1735
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001736// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001737// Lib files should be placed next to the APK file in the following matter:
1738// Example:
1739// /path/to/base.apk
1740// /path/to/lib/arm/first.so
1741// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001742bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1743 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001744 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001745 auto start = Clock::now();
1746
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001747 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001748 if (!ifs) {
1749 LOG(ERROR) << "Invalid storage " << storage;
1750 return false;
1751 }
1752
Songchun Fanc8975312020-07-13 12:14:37 -07001753 const auto targetLibPathRelativeToStorage =
1754 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1755 libDirRelativePath);
1756
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001757 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001758 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1759 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001760 << " errno: " << res;
1761 return false;
1762 }
1763
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001764 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001765 ZipArchiveHandle zipFileHandle;
1766 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001767 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1768 return false;
1769 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001770
1771 // Need a shared pointer: will be passing it into all unpacking jobs.
1772 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001773 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001774 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001775 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001776 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1777 return false;
1778 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001779 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001780 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1781
1782 auto openZipTs = Clock::now();
1783
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001784 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1785 incfs::FileId sourceId;
1786 if (mapFiles) {
1787 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1788 if (!incfs::isValidFileId(sourceId)) {
1789 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1790 << "', mapping disabled";
1791 mapFiles = false;
1792 }
1793 }
1794
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001795 std::vector<Job> jobQueue;
1796 ZipEntry entry;
1797 std::string_view fileName;
1798 while (!Next(cookie, &entry, &fileName)) {
1799 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001800 continue;
1801 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001802
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001803 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001804 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001805
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001806 if (!extractNativeLibs) {
1807 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001808 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001809 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1810 return false;
1811 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001812 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001813 LOG(WARNING) << "Library " << fileName
1814 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1815 << entry.offset;
1816 return false;
1817 }
1818 continue;
1819 }
1820
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001821 auto startFileTs = Clock::now();
1822
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001823 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001824 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001825 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001826 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001827 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001828 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001829 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1830 << "; skipping extraction, spent "
1831 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1832 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001833 continue;
1834 }
1835
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001836 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1837 incfs::NewMappedFileParams mappedFileParams = {
1838 .sourceId = sourceId,
1839 .sourceOffset = entry.offset,
1840 .size = entry.uncompressed_length,
1841 };
1842
1843 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1844 mappedFileParams);
1845 res == 0) {
1846 if (perfLoggingEnabled()) {
1847 auto doneTs = Clock::now();
1848 LOG(INFO) << "incfs: Mapped " << libName << ": "
1849 << elapsedMcs(startFileTs, doneTs) << "mcs";
1850 }
1851 continue;
1852 } else {
1853 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1854 << "; falling back to full extraction";
1855 }
1856 }
1857
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001858 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001859 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001860 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001861 .signature = {},
1862 // Metadata of the new lib file is its relative path
1863 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1864 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001865 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001866 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001867 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001868 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001869 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001870 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001871 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001872
1873 auto makeFileTs = Clock::now();
1874
Songchun Fanafaf6e92020-03-18 14:12:20 -07001875 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001876 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001877 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001878 LOG(INFO) << "incfs: Extracted " << libName
1879 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001880 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001881 continue;
1882 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001883
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001884 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1885 libFileId, libPath = std::move(targetLibPath),
1886 makeFileTs]() mutable {
1887 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001888 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001889
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001890 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001891 auto prepareJobTs = Clock::now();
1892 LOG(INFO) << "incfs: Processed " << libName << ": "
1893 << elapsedMcs(startFileTs, prepareJobTs)
1894 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1895 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001896 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001897 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001898
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001899 auto processedTs = Clock::now();
1900
1901 if (!jobQueue.empty()) {
1902 {
1903 std::lock_guard lock(mJobMutex);
1904 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001905 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001906 if (existingJobs.empty()) {
1907 existingJobs = std::move(jobQueue);
1908 } else {
1909 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1910 std::move_iterator(jobQueue.end()));
1911 }
1912 }
1913 }
1914 mJobCondition.notify_all();
1915 }
1916
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001917 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001918 auto end = Clock::now();
1919 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1920 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1921 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001922 << " make files: " << elapsedMcs(openZipTs, processedTs)
1923 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001924 }
1925
1926 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001927}
1928
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001929void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1930 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001931 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001932 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001933 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001934 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001935 return;
1936 }
1937
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001938 auto startedTs = Clock::now();
1939
1940 // Write extracted data to new file
1941 // NOTE: don't zero-initialize memory, it may take a while for nothing
1942 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1943 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001944 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001945 return;
1946 }
1947
1948 auto extractFileTs = Clock::now();
1949
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001950 if (setFileContent(ifs, libFileId, debugLibPath,
1951 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001952 return;
1953 }
1954
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001955 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001956 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001957 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1958 << entry.compressed_length << " -> " << entry.uncompressed_length
1959 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001960 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1961 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001962 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001963 }
1964}
1965
1966bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001967 struct WaitPrinter {
1968 const Clock::time_point startTs = Clock::now();
1969 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001970 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001971 const auto endTs = Clock::now();
1972 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1973 << elapsedMcs(startTs, endTs) << "mcs";
1974 }
1975 }
1976 } waitPrinter;
1977
1978 MountId mount;
1979 {
1980 auto ifs = getIfs(storage);
1981 if (!ifs) {
1982 return true;
1983 }
1984 mount = ifs->mountId;
1985 }
1986
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001987 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001988 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001989 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001990 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001991 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001992 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001993}
1994
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001995int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1996 std::string_view debugFilePath,
1997 std::span<const uint8_t> data) const {
1998 auto startTs = Clock::now();
1999
2000 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2001 if (!writeFd.ok()) {
2002 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2003 << " errno: " << writeFd.get();
2004 return writeFd.get();
2005 }
2006
2007 const auto dataLength = data.size();
2008
2009 auto openFileTs = Clock::now();
2010 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2011 std::vector<IncFsDataBlock> instructions(numBlocks);
2012 for (int i = 0; i < numBlocks; i++) {
2013 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2014 instructions[i] = IncFsDataBlock{
2015 .fileFd = writeFd.get(),
2016 .pageIndex = static_cast<IncFsBlockIndex>(i),
2017 .compression = INCFS_COMPRESSION_KIND_NONE,
2018 .kind = INCFS_BLOCK_KIND_DATA,
2019 .dataSize = static_cast<uint32_t>(blockSize),
2020 .data = reinterpret_cast<const char*>(data.data()),
2021 };
2022 data = data.subspan(blockSize);
2023 }
2024 auto prepareInstsTs = Clock::now();
2025
2026 size_t res = mIncFs->writeBlocks(instructions);
2027 if (res != instructions.size()) {
2028 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2029 return res;
2030 }
2031
2032 if (perfLoggingEnabled()) {
2033 auto endTs = Clock::now();
2034 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2035 << " bytes): " << elapsedMcs(startTs, endTs)
2036 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2037 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2038 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2039 }
2040
2041 return 0;
2042}
2043
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002044incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2045 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002046 std::unique_lock l(mLock);
2047 const auto ifs = getIfsLocked(storage);
2048 if (!ifs) {
2049 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002050 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002051 }
2052 const auto storageInfo = ifs->storages.find(storage);
2053 if (storageInfo == ifs->storages.end()) {
2054 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002055 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002056 }
2057 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002058 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002059}
2060
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002061incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2062 const auto ifs = getIfs(storage);
2063 if (!ifs) {
2064 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2065 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002066 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002067 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002068}
2069
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002070IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002071 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002072 std::unique_lock l(mLock);
2073 const auto ifs = getIfsLocked(storage);
2074 if (!ifs) {
2075 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002076 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002077 }
2078 const auto storageInfo = ifs->storages.find(storage);
2079 if (storageInfo == ifs->storages.end()) {
2080 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002081 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002082 }
2083 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002084 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002085}
2086
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002087IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002088 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002089 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2090 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002091 const auto [filledBlocksCount, totalBlocksCount] =
2092 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002093 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2094 filledBlocksCount == -ENOENT) {
2095 // a kind of a file that's not really being loaded, e.g. a mapped range
2096 // an older IncFS used to return ENOENT in this case, so handle it the same way
2097 return true;
2098 }
Songchun Fan374f7652020-08-20 08:40:29 -07002099 if (filledBlocksCount < 0) {
2100 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002101 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002102 error = filledBlocksCount;
2103 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002104 }
2105 totalBlocks += totalBlocksCount;
2106 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002107 return true;
2108 });
Songchun Fan374f7652020-08-20 08:40:29 -07002109
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002110 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002111}
2112
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002113bool IncrementalService::updateLoadingProgress(StorageId storage,
2114 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002115 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002116 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002117 // Failed to get progress from incfs, abort.
2118 return false;
2119 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002120 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2121 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002122 // Stop updating progress once it is fully loaded
2123 return true;
2124 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002125 addTimedJob(*mProgressUpdateJobQueue, storage,
2126 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002127 [storage, progressListener = std::move(progressListener), this]() mutable {
2128 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002129 });
2130 return true;
2131}
2132
2133bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002134 StorageId storage, StorageLoadingProgressListener progressListener) {
2135 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002136}
2137
2138bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2139 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2140}
2141
Songchun Fan2570ec02020-10-08 17:22:33 -07002142bool IncrementalService::registerStorageHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002143 StorageId storage, const StorageHealthCheckParams& healthCheckParams,
2144 StorageHealthListener healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002145 DataLoaderStubPtr dataLoaderStub;
2146 {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002147 const auto& ifs = getIfs(storage);
Songchun Fan2570ec02020-10-08 17:22:33 -07002148 if (!ifs) {
2149 return false;
2150 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002151 std::unique_lock l(ifs->lock);
Songchun Fan2570ec02020-10-08 17:22:33 -07002152 dataLoaderStub = ifs->dataLoaderStub;
2153 if (!dataLoaderStub) {
2154 return false;
2155 }
2156 }
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002157 dataLoaderStub->setHealthListener(healthCheckParams, std::move(healthListener));
Songchun Fan2570ec02020-10-08 17:22:33 -07002158 return true;
2159}
2160
2161void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002162 registerStorageHealthListener(storage, {}, {});
Songchun Fan2570ec02020-10-08 17:22:33 -07002163}
2164
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002165bool IncrementalService::perfLoggingEnabled() {
2166 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2167 return enabled;
2168}
2169
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002170void IncrementalService::runJobProcessing() {
2171 for (;;) {
2172 std::unique_lock lock(mJobMutex);
2173 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2174 if (!mRunning) {
2175 return;
2176 }
2177
2178 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002179 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002180 auto queue = std::move(it->second);
2181 mJobQueue.erase(it);
2182 lock.unlock();
2183
2184 for (auto&& job : queue) {
2185 job();
2186 }
2187
2188 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002189 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002190 lock.unlock();
2191 mJobCondition.notify_all();
2192 }
2193}
2194
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002195void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002196 sp<IAppOpsCallback> listener;
2197 {
2198 std::unique_lock lock{mCallbacksLock};
2199 auto& cb = mCallbackRegistered[packageName];
2200 if (cb) {
2201 return;
2202 }
2203 cb = new AppOpsListener(*this, packageName);
2204 listener = cb;
2205 }
2206
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002207 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2208 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002209}
2210
2211bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2212 sp<IAppOpsCallback> listener;
2213 {
2214 std::unique_lock lock{mCallbacksLock};
2215 auto found = mCallbackRegistered.find(packageName);
2216 if (found == mCallbackRegistered.end()) {
2217 return false;
2218 }
2219 listener = found->second;
2220 mCallbackRegistered.erase(found);
2221 }
2222
2223 mAppOpsManager->stopWatchingMode(listener);
2224 return true;
2225}
2226
2227void IncrementalService::onAppOpChanged(const std::string& packageName) {
2228 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002229 return;
2230 }
2231
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002232 std::vector<IfsMountPtr> affected;
2233 {
2234 std::lock_guard l(mLock);
2235 affected.reserve(mMounts.size());
2236 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002237 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002238 if (ifs->mountId == id && ifs->dataLoaderStub &&
2239 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002240 affected.push_back(ifs);
2241 }
2242 }
2243 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002244 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002245 std::unique_lock ll(ifs->lock);
2246 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002247 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002248}
2249
Songchun Fana7098592020-09-03 11:45:53 -07002250bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2251 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002252 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002253 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002254 }
Songchun Fana7098592020-09-03 11:45:53 -07002255 timedQueue.addJob(id, after, std::move(what));
2256 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002257}
2258
Songchun Fana7098592020-09-03 11:45:53 -07002259bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002260 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002261 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002262 }
Songchun Fana7098592020-09-03 11:45:53 -07002263 timedQueue.removeJobs(id);
2264 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002265}
2266
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002267void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2268 bool wasEmpty;
2269 {
2270 std::lock_guard l(mIfsStateCallbacksLock);
2271 wasEmpty = mIfsStateCallbacks.empty();
2272 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2273 }
2274 if (wasEmpty) {
2275 addTimedJob(*mTimedQueue, kMaxStorageId, Constants::progressUpdateInterval,
2276 [this]() { processIfsStateCallbacks(); });
2277 }
2278}
2279
2280void IncrementalService::processIfsStateCallbacks() {
2281 StorageId storageId = kInvalidStorageId;
2282 std::vector<IfsStateCallback> local;
2283 while (true) {
2284 {
2285 std::lock_guard l(mIfsStateCallbacksLock);
2286 if (mIfsStateCallbacks.empty()) {
2287 return;
2288 }
2289 IfsStateCallbacks::iterator it;
2290 if (storageId == kInvalidStorageId) {
2291 // First entry, initialize the it.
2292 it = mIfsStateCallbacks.begin();
2293 } else {
2294 // Subsequent entries, update the storageId, and shift to the new one.
2295 it = mIfsStateCallbacks.find(storageId);
2296 if (it == mIfsStateCallbacks.end()) {
2297 // Was removed while processing, too bad.
2298 break;
2299 }
2300
2301 auto& callbacks = it->second;
2302 if (callbacks.empty()) {
2303 std::swap(callbacks, local);
2304 } else {
2305 callbacks.insert(callbacks.end(), local.begin(), local.end());
2306 }
2307 if (callbacks.empty()) {
2308 it = mIfsStateCallbacks.erase(it);
2309 if (mIfsStateCallbacks.empty()) {
2310 return;
2311 }
2312 } else {
2313 ++it;
2314 }
2315 }
2316
2317 if (it == mIfsStateCallbacks.end()) {
2318 break;
2319 }
2320
2321 storageId = it->first;
2322 auto& callbacks = it->second;
2323 if (callbacks.empty()) {
2324 // Invalid case, one extra lookup should be ok.
2325 continue;
2326 }
2327 std::swap(callbacks, local);
2328 }
2329
2330 processIfsStateCallbacks(storageId, local);
2331 }
2332
2333 addTimedJob(*mTimedQueue, kMaxStorageId, Constants::progressUpdateInterval,
2334 [this]() { processIfsStateCallbacks(); });
2335}
2336
2337void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2338 std::vector<IfsStateCallback>& callbacks) {
2339 const auto state = isMountFullyLoaded(storageId);
2340 IfsState storageState = {};
2341 storageState.error = int(state) < 0;
2342 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2343 if (storageState.fullyLoaded) {
2344 const auto ifs = getIfs(storageId);
2345 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2346 }
2347
2348 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2349 if ((*cur)(storageId, storageState)) {
2350 ++cur;
2351 } else {
2352 cur = callbacks.erase(cur);
2353 }
2354 }
2355}
2356
2357void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2358 std::lock_guard l(mIfsStateCallbacksLock);
2359 mIfsStateCallbacks.erase(storageId);
2360}
2361
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002362void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
2363 const auto duration = getMillsSinceOldestPendingRead(storageId);
2364 if (duration >= 0) {
2365 const auto kMetricsMillisSinceOldestPendingRead =
2366 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2367 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2368 }
2369}
2370
2371long IncrementalService::getMillsSinceOldestPendingRead(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002372 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002373 if (!ifs) {
2374 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, invalid storageId: " << storageId;
2375 return -EINVAL;
2376 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002377 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002378 if (!ifs->dataLoaderStub) {
2379 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, no data loader: " << storageId;
2380 return -EINVAL;
2381 }
2382 return ifs->dataLoaderStub->elapsedMsSinceOldestPendingRead();
2383}
2384
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002385IncrementalService::DataLoaderStub::DataLoaderStub(
2386 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2387 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2388 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2389 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002390 : mService(service),
2391 mId(id),
2392 mParams(std::move(params)),
2393 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002394 mStatusListener(std::move(statusListener)),
2395 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002396 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002397 mHealthCheckParams(healthCheckParams) {
2398 if (mHealthListener && !isHealthParamsValid()) {
2399 mHealthListener = {};
2400 }
2401 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002402 // Disable advanced health check statuses.
2403 mHealthCheckParams.blockedTimeoutMs = -1;
2404 }
2405 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002406}
2407
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002408IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002409 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002410 cleanupResources();
2411 }
2412}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002413
2414void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002415 auto now = Clock::now();
2416 {
2417 std::unique_lock lock(mMutex);
2418 mHealthPath.clear();
2419 unregisterFromPendingReads();
2420 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002421 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002422 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002423 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002424
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002425 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002426
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002427 {
2428 std::unique_lock lock(mMutex);
2429 mParams = {};
2430 mControl = {};
2431 mHealthControl = {};
2432 mHealthListener = {};
2433 mStatusCondition.wait_until(lock, now + 60s, [this] {
2434 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2435 });
2436 mStatusListener = {};
2437 mId = kInvalidStorageId;
2438 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002439}
2440
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002441sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2442 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002443 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002444 if (!status.isOk()) {
2445 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2446 return {};
2447 }
2448 if (!dataloader) {
2449 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2450 return {};
2451 }
2452 return dataloader;
2453}
2454
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002455bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2456 return (params().packageName == Constants::systemPackage);
2457}
2458
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002459bool IncrementalService::DataLoaderStub::requestCreate() {
2460 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2461}
2462
2463bool IncrementalService::DataLoaderStub::requestStart() {
2464 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2465}
2466
2467bool IncrementalService::DataLoaderStub::requestDestroy() {
2468 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2469}
2470
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002471bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002472 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002473 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002474 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002475 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002476 return fsmStep();
2477}
2478
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002479void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002480 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002481 mTargetStatus = status;
2482 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002483 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002484 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002485}
2486
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002487std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002488 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002489
2490 const auto now = mService.mClock->now();
2491 const bool healthy = (mPreviousBindDelay == 0ms);
2492
2493 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2494 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2495 LOG(INFO) << "Binding still in progress. "
2496 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
2497 : "Already unhealthy, don't do anything.");
2498 // Binding still in progress.
2499 if (!healthy) {
2500 // Already unhealthy, don't do anything.
2501 return {};
2502 }
2503 // The DL is healthy/freshly bound, ok to retry for a few times.
2504 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2505 // Still within grace period.
2506 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2507 // Retry interval passed, retrying.
2508 mCurrentStatusTs = now;
2509 mPreviousBindDelay = 0ms;
2510 return 0ms;
2511 }
2512 return {};
2513 }
2514 // fallthrough, mark as unhealthy, and retry with delay
2515 }
2516
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002517 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002518 mPreviousBindTs = now;
2519
2520 const auto nonCrashingInterval = std::max(castToMs(now - previousBindTs), 100ms);
2521 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2522 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2523 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002524 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002525 }
2526
2527 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2528 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2529
2530 const auto bindDelayMs =
2531 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2532 maxBindDelayMs)
2533 .count();
2534 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2535 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2536 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002537 return mPreviousBindDelay;
2538}
2539
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002540bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002541 const auto maybeBindDelay = needToBind();
2542 if (!maybeBindDelay) {
2543 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2544 return true;
2545 }
2546 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002547 if (bindDelay > 1s) {
2548 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
2549 << bindDelay.count() / 1000 << "s";
2550 }
2551
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002552 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002553 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2554 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002555 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002556 const bool healthy = (bindDelay == 0ms);
2557 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2558 << (healthy ? ", retrying." : "");
2559
2560 // Internal error, retry for healthy/new DLs.
2561 // Let needToBind migrate it to unhealthy after too many retries.
2562 if (healthy) {
2563 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2564 [this]() { fsmStep(); })) {
2565 // Mark as binding so that we know it's not the DL's fault.
2566 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2567 return true;
2568 }
2569 }
2570
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002571 return false;
2572 }
2573 return true;
2574}
2575
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002576bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002577 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002578 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002579 return false;
2580 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002581 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002582 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002583 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002584 return false;
2585 }
2586 return true;
2587}
2588
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002589bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002590 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002591 if (!dataloader) {
2592 return false;
2593 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002594 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002595 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002596 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002597 return false;
2598 }
2599 return true;
2600}
2601
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002602bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002603 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002604}
2605
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002606bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002607 if (!isValid()) {
2608 return false;
2609 }
2610
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002611 int currentStatus;
2612 int targetStatus;
2613 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002614 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002615 currentStatus = mCurrentStatus;
2616 targetStatus = mTargetStatus;
2617 }
2618
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002619 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002620
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002621 if (currentStatus == targetStatus) {
2622 return true;
2623 }
2624
2625 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002626 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2627 // Do nothing, this is a reset state.
2628 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002629 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002630 switch (currentStatus) {
2631 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2632 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2633 return true;
2634 default:
2635 return destroy();
2636 }
2637 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002638 }
2639 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2640 switch (currentStatus) {
2641 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2642 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2643 return start();
2644 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002645 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002646 }
2647 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2648 switch (currentStatus) {
2649 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002650 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002651 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002652 return bind();
2653 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002654 return create();
2655 }
2656 break;
2657 default:
2658 LOG(ERROR) << "Invalid target status: " << targetStatus
2659 << ", current status: " << currentStatus;
2660 break;
2661 }
2662 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002663}
2664
2665binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002666 if (!isValid()) {
2667 return binder::Status::
2668 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2669 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002670 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002671 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2672 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002673 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2674 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002675 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2676 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2677 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2678 [this, newStatus]() { setCurrentStatus(newStatus); });
2679 return binder::Status::ok();
2680 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002681
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002682 setCurrentStatus(newStatus);
2683 return binder::Status::ok();
2684}
2685
2686void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002687 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002688 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002689 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002690 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002691 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002692 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002693 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002694
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002695 oldStatus = mCurrentStatus;
2696 targetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002697 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002698
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002699 // Change the status.
2700 mCurrentStatus = newStatus;
2701 mCurrentStatusTs = mService.mClock->now();
2702
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002703 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2704 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002705 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2706 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002707 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002708 }
2709
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002710 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002711 << newStatus << " (target " << targetStatus << ")";
2712
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002713 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002714 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002715 }
2716
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002717 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002718
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002719 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002720}
2721
Songchun Fan33093982020-09-10 13:12:39 -07002722binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2723 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002724 if (!isValid()) {
2725 return binder::Status::
2726 fromServiceSpecificError(-EINVAL,
2727 "reportStreamHealth came to invalid DataLoaderStub");
2728 }
2729 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002730 LOG(ERROR) << "reportStreamHealth: mount ID mismatch: expected " << id()
2731 << ", but got: " << mountId;
Songchun Fan2570ec02020-10-08 17:22:33 -07002732 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2733 }
2734 {
2735 std::lock_guard lock(mMutex);
2736 mStreamStatus = newStatus;
2737 }
Songchun Fan33093982020-09-10 13:12:39 -07002738 return binder::Status::ok();
2739}
2740
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002741bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2742 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2743 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002744}
2745
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002746void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002747 int healthStatus) {
2748 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2749 if (healthListener) {
2750 healthListener->onHealthStatus(id(), healthStatus);
2751 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002752}
2753
Songchun Fan2570ec02020-10-08 17:22:33 -07002754static int adjustHealthStatus(int healthStatus, int streamStatus) {
2755 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2756 // everything is good; no need to change status
2757 return healthStatus;
2758 }
2759 int newHeathStatus = healthStatus;
2760 switch (streamStatus) {
2761 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2762 // storage is limited and storage not healthy
2763 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2764 break;
2765 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2766 // fall through
2767 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2768 // fall through
2769 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2770 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2771 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2772 }
2773 // pending/blocked status due to transportation issues is not regarded as unhealthy
2774 break;
2775 default:
2776 break;
2777 }
2778 return newHeathStatus;
2779}
2780
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002781void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2782 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002783
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002784 int healthStatusToReport = -1;
2785 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002786
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002787 {
2788 std::unique_lock lock(mMutex);
2789 unregisterFromPendingReads();
2790
2791 healthListener = mHealthListener;
2792
2793 // Healthcheck depends on timestamp of the oldest pending read.
2794 // 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 -07002795 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2796 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002797 const auto now = Clock::now();
2798 const auto kernelTsUs = getOldestPendingReadTs();
2799 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002800 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2801 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002802 mHealthBase = {now, kernelTsUs};
2803 }
2804
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002805 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2806 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002807 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2808 registerForPendingReads();
2809 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2810 lock.unlock();
2811 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002812 return;
2813 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002814
2815 resetHealthControl();
2816
2817 // Always make sure the data loader is started.
2818 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2819
2820 // Skip any further processing if health check params are invalid.
2821 if (!isHealthParamsValid()) {
2822 LOG(DEBUG) << id()
2823 << ": Skip any further processing if health check params are invalid.";
2824 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2825 lock.unlock();
2826 onHealthStatus(healthListener, healthStatusToReport);
2827 // Triggering data loader start. This is a one-time action.
2828 fsmStep();
2829 return;
2830 }
2831
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002832 // Don't schedule timer job less than 500ms in advance.
2833 static constexpr auto kTolerance = 500ms;
2834
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002835 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2836 const auto unhealthyTimeout =
2837 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2838 const auto unhealthyMonitoring =
2839 std::max(1000ms,
2840 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2841
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002842 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002843
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002844 Milliseconds checkBackAfter;
2845 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002846 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002847 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002848 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002849 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002850 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002851 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002852 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2853 } else {
2854 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002855 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002856 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2857 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002858 // Adjust health status based on stream status
2859 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002860 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002861 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002862 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2863 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002864 }
2865
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002866 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002867 if (healthStatusToReport != -1) {
2868 onHealthStatus(healthListener, healthStatusToReport);
2869 }
2870
2871 fsmStep();
2872}
2873
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002874Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2875 BootClockTsUs kernelTsUs) {
2876 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2877 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2878 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2879}
2880
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002881const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2882 if (mHealthPath.empty()) {
2883 resetHealthControl();
2884 return mHealthControl;
2885 }
2886 if (mHealthControl.pendingReads() < 0) {
2887 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2888 }
2889 if (mHealthControl.pendingReads() < 0) {
2890 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2891 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2892 << mHealthControl.logs() << ")";
2893 }
2894 return mHealthControl;
2895}
2896
2897void IncrementalService::DataLoaderStub::resetHealthControl() {
2898 mHealthControl = {};
2899}
2900
2901BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2902 auto result = kMaxBootClockTsUs;
2903
2904 const auto& control = initializeHealthControl();
2905 if (control.pendingReads() < 0) {
2906 return result;
2907 }
2908
Songchun Fan6944f1e2020-11-06 15:24:24 -08002909 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002910 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002911 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002912 // Clear previous pending reads
2913 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002914 return result;
2915 }
2916
2917 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
Songchun Fan6944f1e2020-11-06 15:24:24 -08002918 << mLastPendingReads.size() << ": " << mLastPendingReads.front().bootClockTsUs;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002919
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002920 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002921}
2922
2923void IncrementalService::DataLoaderStub::registerForPendingReads() {
2924 const auto pendingReadsFd = mHealthControl.pendingReads();
2925 if (pendingReadsFd < 0) {
2926 return;
2927 }
2928
2929 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2930
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002931 mService.mLooper->addFd(
2932 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2933 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002934 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002935 self->updateHealthStatus(/*baseline=*/true);
2936 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002937 },
2938 this);
2939 mService.mLooper->wake();
2940}
2941
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002942BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2943 auto result = kMaxBootClockTsUs;
2944 for (auto&& pendingRead : mLastPendingReads) {
2945 result = std::min(result, pendingRead.bootClockTsUs);
2946 }
2947 return result;
2948}
2949
2950long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
2951 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
2952 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
2953 return 0;
2954 }
2955 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
2956}
2957
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002958void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002959 const auto pendingReadsFd = mHealthControl.pendingReads();
2960 if (pendingReadsFd < 0) {
2961 return;
2962 }
2963
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002964 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2965
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002966 mService.mLooper->removeFd(pendingReadsFd);
2967 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002968}
2969
Songchun Fan2570ec02020-10-08 17:22:33 -07002970void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002971 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002972 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002973 mHealthCheckParams = healthCheckParams;
2974 mHealthListener = std::move(healthListener);
2975 if (!mHealthListener) {
2976 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07002977 }
2978}
2979
Songchun Fan6944f1e2020-11-06 15:24:24 -08002980static std::string toHexString(const RawMetadata& metadata) {
2981 int n = metadata.size();
2982 std::string res(n * 2, '\0');
2983 // Same as incfs::toString(fileId)
2984 static constexpr char kHexChar[] = "0123456789abcdef";
2985 for (int i = 0; i < n; ++i) {
2986 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2987 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2988 }
2989 return res;
2990}
2991
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002992void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002993 dprintf(fd, " dataLoader: {\n");
2994 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002995 dprintf(fd, " currentStatusTs: %lldmcs\n",
2996 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002997 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2998 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002999 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003000 dprintf(fd, " health: {\n");
3001 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3002 dprintf(fd, " base: %lldmcs (%lld)\n",
3003 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3004 (long long)mHealthBase.kernelTsUs);
3005 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3006 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3007 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3008 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003009 dprintf(fd, " lastPendingReads: \n");
3010 const auto control = mService.mIncFs->openMount(mHealthPath);
3011 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003012 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003013 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3014 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3015 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3016 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3017 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003018 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
3019 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
3020 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003021 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003022 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003023 dprintf(fd, " dataLoaderParams: {\n");
3024 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3025 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3026 dprintf(fd, " className: %s\n", params.className.c_str());
3027 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3028 dprintf(fd, " }\n");
3029 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003030}
3031
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003032void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3033 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003034}
3035
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003036binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3037 bool enableReadLogs, int32_t* _aidl_return) {
3038 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3039 return binder::Status::ok();
3040}
3041
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003042FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3043 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3044}
3045
Songchun Fan3c82a302019-11-29 14:23:45 -08003046} // namespace android::incremental