blob: 8b816d02026fd37088bec5dfaee6ced86e30eb90 [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 Buynytskyyc144cc42021-03-31 22:19:42 -0700103static bool getAlwaysEnableReadTimeoutsForSystemDataLoaders() {
104 return android::base::
105 GetBoolProperty("debug.incremental.always_enable_read_timeouts_for_system_dataloaders",
106 true);
107}
108
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700109static bool getEnforceReadLogsMaxIntervalForSystemDataLoaders() {
110 return android::base::GetBoolProperty("debug.incremental.enforce_readlogs_max_interval_for_"
111 "system_dataloaders",
112 false);
113}
114
115static Seconds getReadLogsMaxInterval() {
116 constexpr int limit = duration_cast<Seconds>(Constants::readLogsMaxInterval).count();
117 int readlogs_max_interval_secs =
118 std::min(limit,
119 android::base::GetIntProperty<
120 int>("debug.incremental.readlogs_max_interval_sec", limit));
121 return Seconds{readlogs_max_interval_secs};
122}
123
Songchun Fan3c82a302019-11-29 14:23:45 -0800124template <base::LogSeverity level = base::ERROR>
125bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
126 auto cstr = path::c_str(name);
127 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800128 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800129 PLOG(level) << "Can't create directory '" << name << '\'';
130 return false;
131 }
132 struct stat st;
133 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
134 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
135 return false;
136 }
137 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800138 if (::chmod(cstr, mode)) {
139 PLOG(level) << "Changing permission failed for '" << name << '\'';
140 return false;
141 }
142
Songchun Fan3c82a302019-11-29 14:23:45 -0800143 return true;
144}
145
146static std::string toMountKey(std::string_view path) {
147 if (path.empty()) {
148 return "@none";
149 }
150 if (path == "/"sv) {
151 return "@root";
152 }
153 if (path::isAbsolute(path)) {
154 path.remove_prefix(1);
155 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700156 if (path.size() > 16) {
157 path = path.substr(0, 16);
158 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800159 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700160 std::replace_if(
161 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
162 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800163}
164
165static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
166 std::string_view path) {
167 auto mountKey = toMountKey(path);
168 const auto prefixSize = mountKey.size();
169 for (int counter = 0; counter < 1000;
170 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
171 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800172 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800173 return {mountKey, mountRoot};
174 }
175 }
176 return {};
177}
178
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700179template <class Map>
180typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
181 const auto nextIt = map.upper_bound(path);
182 if (nextIt == map.begin()) {
183 return map.end();
184 }
185 const auto suspectIt = std::prev(nextIt);
186 if (!path::startsWith(path, suspectIt->first)) {
187 return map.end();
188 }
189 return suspectIt;
190}
191
192static base::unique_fd dup(base::borrowed_fd fd) {
193 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
194 return base::unique_fd(res);
195}
196
Songchun Fan3c82a302019-11-29 14:23:45 -0800197template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700198static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800199 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800200 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800201 ProtoMessage message;
202 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
203}
204
205static bool isValidMountTarget(std::string_view path) {
206 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
207}
208
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700209std::string makeUniqueName(std::string_view prefix) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800210 static constexpr auto uuidStringSize = 36;
211
212 uuid_t guid;
213 uuid_generate(guid);
214
215 std::string name;
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700216 const auto prefixSize = prefix.size();
Songchun Fan3c82a302019-11-29 14:23:45 -0800217 name.reserve(prefixSize + uuidStringSize);
218
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700219 name = prefix;
Songchun Fan3c82a302019-11-29 14:23:45 -0800220 name.resize(prefixSize + uuidStringSize);
221 uuid_unparse(guid, name.data() + prefixSize);
222
223 return name;
224}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700225
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700226std::string makeBindMdName() {
227 return makeUniqueName(constants().mountpointMdPrefix);
228}
229
Alex Buynytskyy04035452020-06-06 20:15:58 -0700230static bool checkReadLogsDisabledMarker(std::string_view root) {
231 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
232 struct stat st;
233 return (::stat(markerPath, &st) == 0);
234}
235
Songchun Fan3c82a302019-11-29 14:23:45 -0800236} // namespace
237
238IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700239 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700240 dataLoaderStub->cleanupResources();
241 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700242 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700243 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800244 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
245 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700246 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800247 incrementalService.mVold->unmountIncFs(target);
248 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700249 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800250 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
251 cleanupFilesystem(root);
252}
253
254auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800255 std::string name;
256 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
257 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
258 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800259 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
260 constants().storagePrefix.data(), id, no);
261 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800262 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800263 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800264 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
265 } else if (err != EEXIST) {
266 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
267 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800268 }
269 }
270 nextStorageDirNo = 0;
271 return storages.end();
272}
273
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700274template <class Func>
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700275static auto makeCleanup(Func&& f) requires(!std::is_lvalue_reference_v<Func>) {
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -0700276 // ok to move a 'forwarding' reference here as lvalues are disabled anyway
277 auto deleter = [f = std::move(f)](auto) { // NOLINT
278 f();
279 };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700280 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700281 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
282}
283
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700284static auto openDir(const char* dir) {
285 struct DirCloser {
286 void operator()(DIR* d) const noexcept { ::closedir(d); }
287 };
288 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700289}
290
291static auto openDir(std::string_view dir) {
292 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800293}
294
295static int rmDirContent(const char* path) {
296 auto dir = openDir(path);
297 if (!dir) {
298 return -EINVAL;
299 }
300 while (auto entry = ::readdir(dir.get())) {
301 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
302 continue;
303 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700304 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800305 if (entry->d_type == DT_DIR) {
306 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
307 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
308 return err;
309 }
310 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
311 PLOG(WARNING) << "Failed to rmdir " << fullPath;
312 return err;
313 }
314 } else {
315 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
316 PLOG(WARNING) << "Failed to delete " << fullPath;
317 return err;
318 }
319 }
320 }
321 return 0;
322}
323
Songchun Fan3c82a302019-11-29 14:23:45 -0800324void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800325 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800326 ::rmdir(path::join(root, constants().backing).c_str());
327 ::rmdir(path::join(root, constants().mount).c_str());
328 ::rmdir(path::c_str(root));
329}
330
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700331void IncrementalService::IncFsMount::setFlag(StorageFlags flag, bool value) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700332 if (value) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700333 flags |= flag;
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700334 } else {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700335 flags &= ~flag;
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700336 }
337}
338
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800339IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800340 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800341 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800342 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700343 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700344 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700345 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700346 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700347 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700348 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800349 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800350 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700351 CHECK(mVold) << "Vold service is unavailable";
352 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
353 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
354 CHECK(mJni) << "JNI is unavailable";
355 CHECK(mLooper) << "Looper is unavailable";
356 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700357 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700358 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800359 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700360
361 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700362 mJobProcessor = std::thread([this]() {
363 mJni->initializeForCurrentThread();
364 runJobProcessing();
365 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700366 mCmdLooperThread = std::thread([this]() {
367 mJni->initializeForCurrentThread();
368 runCmdLooper();
369 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700370
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700371 const auto mountedRootNames = adoptMountedInstances();
372 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800373}
374
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700375IncrementalService::~IncrementalService() {
376 {
377 std::lock_guard lock(mJobMutex);
378 mRunning = false;
379 }
380 mJobCondition.notify_all();
381 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700382 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700383 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700384 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700385 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700386 // Ensure that mounts are destroyed while the service is still valid.
387 mBindsByPath.clear();
388 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700389}
Songchun Fan3c82a302019-11-29 14:23:45 -0800390
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700391static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800392 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800393 case IncrementalService::BindKind::Temporary:
394 return "Temporary";
395 case IncrementalService::BindKind::Permanent:
396 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800397 }
398}
399
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700400template <class Duration>
Songchun Fan0dc77722021-05-03 17:13:52 -0700401static int64_t elapsedMcs(Duration start, Duration end) {
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700402 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
403}
404
Songchun Fan0dc77722021-05-03 17:13:52 -0700405int64_t IncrementalService::elapsedUsSinceMonoTs(uint64_t monoTsUs) {
406 const auto now = mClock->now();
407 const auto nowUs = static_cast<uint64_t>(
408 duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count());
Songchun Fand48a25e2021-04-30 09:50:58 -0700409 return nowUs - monoTsUs;
410}
411
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800412void IncrementalService::onDump(int fd) {
413 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -0700414 dprintf(fd, "IncFs features: 0x%x\n", int(mIncFs->features()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800415 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
416
417 std::unique_lock l(mLock);
418
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700419 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800420 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700421 std::unique_lock ll(ifs->lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700422 const IncFsMount& mnt = *ifs;
423 dprintf(fd, " [%d]: {\n", id);
424 if (id != mnt.mountId) {
425 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
426 } else {
427 dprintf(fd, " mountId: %d\n", mnt.mountId);
428 dprintf(fd, " root: %s\n", mnt.root.c_str());
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700429 const auto& metricsInstanceName = ifs->metricsKey;
Songchun Fanf949c372021-04-27 11:26:25 -0700430 dprintf(fd, " metrics instance name: %s\n", path::c_str(metricsInstanceName).get());
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700431 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700432 dprintf(fd, " flags: %d\n", int(mnt.flags));
433 if (mnt.startLoadingTs.time_since_epoch() == Clock::duration::zero()) {
434 dprintf(fd, " not loading\n");
435 } else {
436 dprintf(fd, " startLoading: %llds\n",
437 (long long)(elapsedMcs(mnt.startLoadingTs, Clock::now()) / 1000000));
438 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700439 if (mnt.dataLoaderStub) {
440 mnt.dataLoaderStub->onDump(fd);
441 } else {
442 dprintf(fd, " dataLoader: null\n");
443 }
444 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
445 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700446 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700447 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800448 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700449 }
450 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800451
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700452 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
453 for (auto&& [target, bind] : mnt.bindPoints) {
454 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
455 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
456 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
457 dprintf(fd, " kind: %s\n", toString(bind.kind));
458 }
459 dprintf(fd, " }\n");
Songchun Fanf949c372021-04-27 11:26:25 -0700460
461 dprintf(fd, " incfsMetrics: {\n");
462 const auto incfsMetrics = mIncFs->getMetrics(metricsInstanceName);
463 if (incfsMetrics) {
464 dprintf(fd, " readsDelayedMin: %d\n", incfsMetrics.value().readsDelayedMin);
465 dprintf(fd, " readsDelayedMinUs: %lld\n",
466 (long long)incfsMetrics.value().readsDelayedMinUs);
467 dprintf(fd, " readsDelayedPending: %d\n",
468 incfsMetrics.value().readsDelayedPending);
469 dprintf(fd, " readsDelayedPendingUs: %lld\n",
470 (long long)incfsMetrics.value().readsDelayedPendingUs);
471 dprintf(fd, " readsFailedHashVerification: %d\n",
472 incfsMetrics.value().readsFailedHashVerification);
473 dprintf(fd, " readsFailedOther: %d\n", incfsMetrics.value().readsFailedOther);
474 dprintf(fd, " readsFailedTimedOut: %d\n",
475 incfsMetrics.value().readsFailedTimedOut);
476 } else {
477 dprintf(fd, " Metrics not available. Errno: %d\n", errno);
478 }
479 dprintf(fd, " }\n");
Songchun Fand48a25e2021-04-30 09:50:58 -0700480
481 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
482 const auto errorNo = errno;
483 dprintf(fd, " lastReadError: {\n");
484 if (lastReadError) {
485 if (lastReadError->timestampUs == 0) {
486 dprintf(fd, " No read errors.\n");
487 } else {
488 dprintf(fd, " fileId: %s\n",
489 IncFsWrapper::toString(lastReadError->id).c_str());
490 dprintf(fd, " time: %llu microseconds ago\n",
491 (unsigned long long)elapsedUsSinceMonoTs(lastReadError->timestampUs));
492 dprintf(fd, " blockIndex: %d\n", lastReadError->block);
493 dprintf(fd, " errno: %d\n", lastReadError->errorNo);
494 }
495 } else {
496 dprintf(fd, " Info not available. Errno: %d\n", errorNo);
497 }
498 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800499 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700500 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800501 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700502 dprintf(fd, "}\n");
503 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800504 for (auto&& [target, mountPairIt] : mBindsByPath) {
505 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700506 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
507 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
508 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
509 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800510 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700511 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800512}
513
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800514bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700515 if (!ifs.dataLoaderStub) {
516 return false;
517 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700518 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800519 return true;
520 }
521
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700522 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800523}
524
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700525void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800526 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700527 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800528 }
529
530 std::vector<IfsMountPtr> mounts;
531 {
532 std::lock_guard l(mLock);
533 mounts.reserve(mMounts.size());
534 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700535 std::unique_lock ll(ifs->lock);
536
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800537 if (ifs->mountId != id) {
538 continue;
539 }
540
541 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800542 mounts.push_back(ifs);
543 }
544 }
545 }
546
Alex Buynytskyy69941662020-04-11 21:40:37 -0700547 if (mounts.empty()) {
548 return;
549 }
550
Songchun Fan3c82a302019-11-29 14:23:45 -0800551 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700552 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800553 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700554 std::unique_lock l(ifs->lock);
555 if (ifs->dataLoaderStub) {
556 ifs->dataLoaderStub->requestStart();
557 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800558 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800559 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800560}
561
562auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
563 for (;;) {
564 if (mNextId == kMaxStorageId) {
565 mNextId = 0;
566 }
567 auto id = ++mNextId;
568 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
569 if (inserted) {
570 return it;
571 }
572 }
573}
574
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700575StorageId IncrementalService::createStorage(std::string_view mountPoint,
576 content::pm::DataLoaderParamsParcel dataLoaderParams,
577 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800578 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
579 if (!path::isAbsolute(mountPoint)) {
580 LOG(ERROR) << "path is not absolute: " << mountPoint;
581 return kInvalidStorageId;
582 }
583
584 auto mountNorm = path::normalize(mountPoint);
585 {
586 const auto id = findStorageId(mountNorm);
587 if (id != kInvalidStorageId) {
588 if (options & CreateOptions::OpenExisting) {
589 LOG(INFO) << "Opened existing storage " << id;
590 return id;
591 }
592 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
593 return kInvalidStorageId;
594 }
595 }
596
597 if (!(options & CreateOptions::CreateNew)) {
598 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
599 return kInvalidStorageId;
600 }
601
602 if (!path::isEmptyDir(mountNorm)) {
603 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
604 return kInvalidStorageId;
605 }
606 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
607 if (mountRoot.empty()) {
608 LOG(ERROR) << "Bad mount point";
609 return kInvalidStorageId;
610 }
611 // Make sure the code removes all crap it may create while still failing.
612 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
613 auto firstCleanupOnFailure =
614 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
615
616 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800617 const auto backing = path::join(mountRoot, constants().backing);
618 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800619 return kInvalidStorageId;
620 }
621
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700622 std::string metricsKey;
Songchun Fan3c82a302019-11-29 14:23:45 -0800623 IncFsMount::Control control;
624 {
625 std::lock_guard l(mMountOperationLock);
626 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800627
628 if (auto err = rmDirContent(backing.c_str())) {
629 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
630 return kInvalidStorageId;
631 }
632 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
633 return kInvalidStorageId;
634 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800635 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
636 return kInvalidStorageId;
637 }
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700638 metricsKey = makeUniqueName(mountKey);
639 auto status = mVold->mountIncFs(backing, mountTarget, 0, metricsKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800640 if (!status.isOk()) {
641 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
642 return kInvalidStorageId;
643 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800644 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
645 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800646 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
647 return kInvalidStorageId;
648 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800649 int cmd = controlParcel.cmd.release().release();
650 int pendingReads = controlParcel.pendingReads.release().release();
651 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800652 int blocksWritten =
653 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
654 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800655 }
656
657 std::unique_lock l(mLock);
658 const auto mountIt = getStorageSlotLocked();
659 const auto mountId = mountIt->first;
660 l.unlock();
661
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700662 auto ifs = std::make_shared<IncFsMount>(std::move(mountRoot), std::move(metricsKey), mountId,
663 std::move(control), *this);
Songchun Fan3c82a302019-11-29 14:23:45 -0800664 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
665 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700666 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800667
668 auto secondCleanup = [this, &l](auto itPtr) {
669 if (!l.owns_lock()) {
670 l.lock();
671 }
672 mMounts.erase(*itPtr);
673 };
674 auto secondCleanupOnFailure =
675 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
676
677 const auto storageIt = ifs->makeStorage(ifs->mountId);
678 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800679 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800680 return kInvalidStorageId;
681 }
682
683 {
684 metadata::Mount m;
685 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700686 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700687 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
688 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
689 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800690 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800691 if (auto err =
692 mIncFs->makeFile(ifs->control,
693 path::join(ifs->root, constants().mount,
694 constants().infoMdName),
695 0777, idFromMetadata(metadata),
696 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800697 LOG(ERROR) << "Saving mount metadata failed: " << -err;
698 return kInvalidStorageId;
699 }
700 }
701
702 const auto bk =
703 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800704 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
705 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800706 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800707 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800708 return kInvalidStorageId;
709 }
710
711 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700712 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800713
Songchun Fan3c82a302019-11-29 14:23:45 -0800714 mountIt->second = std::move(ifs);
715 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700716
Songchun Fan3c82a302019-11-29 14:23:45 -0800717 LOG(INFO) << "created storage " << mountId;
718 return mountId;
719}
720
721StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
722 StorageId linkedStorage,
723 IncrementalService::CreateOptions options) {
724 if (!isValidMountTarget(mountPoint)) {
725 LOG(ERROR) << "Mount point is invalid or missing";
726 return kInvalidStorageId;
727 }
728
729 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700730 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800731 if (!ifs) {
732 LOG(ERROR) << "Ifs unavailable";
733 return kInvalidStorageId;
734 }
735
736 const auto mountIt = getStorageSlotLocked();
737 const auto storageId = mountIt->first;
738 const auto storageIt = ifs->makeStorage(storageId);
739 if (storageIt == ifs->storages.end()) {
740 LOG(ERROR) << "Can't create a new storage";
741 mMounts.erase(mountIt);
742 return kInvalidStorageId;
743 }
744
745 l.unlock();
746
747 const auto bk =
748 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800749 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
750 std::string(storageIt->second.name), path::normalize(mountPoint),
751 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800752 err < 0) {
753 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700754 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
755 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800756 return kInvalidStorageId;
757 }
758
759 mountIt->second = ifs;
760 return storageId;
761}
762
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700763bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700764 content::pm::DataLoaderParamsParcel dataLoaderParams,
765 DataLoaderStatusListener statusListener,
766 const StorageHealthCheckParams& healthCheckParams,
767 StorageHealthListener healthListener,
768 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800769 // Per Uid timeouts.
770 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700771 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800772 }
773
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700774 IfsMountPtr ifs;
775 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800776
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700777 // Re-initialize DataLoader.
778 {
779 ifs = getIfs(storageId);
780 if (!ifs) {
781 return false;
782 }
783
784 std::unique_lock l(ifs->lock);
785 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
786 }
787
788 if (dataLoaderStub) {
789 dataLoaderStub->cleanupResources();
790 dataLoaderStub = {};
791 }
792
793 {
794 std::unique_lock l(ifs->lock);
795 if (ifs->dataLoaderStub) {
796 LOG(INFO) << "Skipped data loader stub creation because it already exists";
797 return false;
798 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700799
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700800 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
801 healthCheckParams, std::move(healthListener));
802 CHECK(ifs->dataLoaderStub);
803 dataLoaderStub = ifs->dataLoaderStub;
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700804
805 // Disable long read timeouts for non-system dataloaders.
806 // To be re-enabled after installation is complete.
807 ifs->setReadTimeoutsRequested(dataLoaderStub->isSystemDataLoader() &&
808 getAlwaysEnableReadTimeoutsForSystemDataLoaders());
809 applyStorageParamsLocked(*ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700810 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800811
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700812 if (dataLoaderStub->isSystemDataLoader() &&
813 !getEnforceReadLogsMaxIntervalForSystemDataLoaders()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700814 // Readlogs from system dataloader (adb) can always be collected.
815 ifs->startLoadingTs = TimePoint::max();
816 } else {
817 // Assign time when installation wants the DL to start streaming.
818 const auto startLoadingTs = mClock->now();
819 ifs->startLoadingTs = startLoadingTs;
820 // Setup a callback to disable the readlogs after max interval.
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700821 addTimedJob(*mTimedQueue, storageId, getReadLogsMaxInterval(),
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700822 [this, storageId, startLoadingTs]() {
823 const auto ifs = getIfs(storageId);
824 if (!ifs) {
825 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
826 << storageId;
827 return;
828 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700829 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700830 if (ifs->startLoadingTs != startLoadingTs) {
831 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
832 "installation?): "
833 << storageId;
834 return;
835 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700836 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700837 });
838 }
839
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800840 return dataLoaderStub->requestStart();
841}
842
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700843void IncrementalService::onInstallationComplete(StorageId storage) {
844 IfsMountPtr ifs = getIfs(storage);
845 if (!ifs) {
846 return;
847 }
848
849 // Always enable long read timeouts after installation is complete.
850 std::unique_lock l(ifs->lock);
851 ifs->setReadTimeoutsRequested(true);
852 applyStorageParamsLocked(*ifs);
853}
854
Songchun Fan3c82a302019-11-29 14:23:45 -0800855IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
856 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700857 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800858}
859
860StorageId IncrementalService::findStorageId(std::string_view path) const {
861 std::lock_guard l(mLock);
862 auto it = findStorageLocked(path);
863 if (it == mBindsByPath.end()) {
864 return kInvalidStorageId;
865 }
866 return it->second->second.storage;
867}
868
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800869void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700870 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700871 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800872 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700873 return;
874 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700875
876 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800877 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700878 return;
879 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800880 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700881
882 const auto metadata = constants().readLogsDisabledMarkerName;
883 if (auto err = mIncFs->makeFile(ifs->control,
884 path::join(ifs->root, constants().mount,
885 constants().readLogsDisabledMarkerName),
886 0777, idFromMetadata(metadata), {})) {
887 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
888 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
889 return;
890 }
891
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700892 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700893}
894
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700895int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
896 const auto ifs = getIfs(storageId);
897 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700898 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700899 return -EINVAL;
900 }
901
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700902 std::string packageName;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700903
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700904 {
905 std::unique_lock l(ifs->lock);
906 if (!enableReadLogs) {
907 return disableReadLogsLocked(*ifs);
908 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700909
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700910 if (!ifs->readLogsAllowed()) {
911 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
912 return -EPERM;
913 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700914
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700915 if (!ifs->dataLoaderStub) {
916 // This should never happen - only DL can call enableReadLogs.
917 LOG(ERROR) << "enableReadLogs failed: invalid state";
918 return -EPERM;
919 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700920
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700921 // Check installation time.
922 const auto now = mClock->now();
923 const auto startLoadingTs = ifs->startLoadingTs;
924 if (startLoadingTs <= now && now - startLoadingTs > getReadLogsMaxInterval()) {
925 LOG(ERROR)
926 << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
927 << storageId;
928 return -EPERM;
929 }
930
931 packageName = ifs->dataLoaderStub->params().packageName;
932 ifs->setReadLogsRequested(true);
933 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700934
935 // Check loader usage stats permission and apop.
936 if (auto status =
937 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
938 !status.isOk()) {
939 LOG(ERROR) << " Permission: " << kLoaderUsageStats
940 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700941 return fromBinderStatus(status);
942 }
943
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700944 // Check multiuser permission.
945 if (auto status =
946 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
947 !status.isOk()) {
948 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
949 << " check failed: " << status.toString8();
950 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700951 }
952
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700953 {
954 std::unique_lock l(ifs->lock);
955 if (!ifs->readLogsRequested()) {
956 return 0;
957 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700958 if (auto status = applyStorageParamsLocked(*ifs); status != 0) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700959 return status;
960 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700961 }
962
963 registerAppOpsCallback(packageName);
964
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700965 return 0;
966}
967
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700968int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700969 ifs.setReadLogsRequested(false);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700970 return applyStorageParamsLocked(ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700971}
972
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700973int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700974 os::incremental::IncrementalFileSystemControlParcel control;
975 control.cmd.reset(dup(ifs.control.cmd()));
976 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700977 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700978 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700979 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700980 }
981
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700982 bool enableReadLogs = ifs.readLogsRequested();
983 bool enableReadTimeouts = ifs.readTimeoutsRequested();
984
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700985 std::lock_guard l(mMountOperationLock);
Songchun Fanf6c65bb2021-05-10 16:17:30 -0700986 auto status = mVold->setIncFsMountOptions(control, enableReadLogs, enableReadTimeouts,
987 ifs.metricsKey);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800988 if (status.isOk()) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700989 // Store states.
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800990 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700991 ifs.setReadTimeoutsEnabled(enableReadTimeouts);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700992 } else {
993 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800994 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700995 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700996}
997
Songchun Fan3c82a302019-11-29 14:23:45 -0800998void IncrementalService::deleteStorage(StorageId storageId) {
999 const auto ifs = getIfs(storageId);
1000 if (!ifs) {
1001 return;
1002 }
1003 deleteStorage(*ifs);
1004}
1005
1006void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
1007 std::unique_lock l(ifs.lock);
1008 deleteStorageLocked(ifs, std::move(l));
1009}
1010
1011void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
1012 std::unique_lock<std::mutex>&& ifsLock) {
1013 const auto storages = std::move(ifs.storages);
1014 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
1015 const auto bindPoints = ifs.bindPoints;
1016 ifsLock.unlock();
1017
1018 std::lock_guard l(mLock);
1019 for (auto&& [id, _] : storages) {
1020 if (id != ifs.mountId) {
1021 mMounts.erase(id);
1022 }
1023 }
1024 for (auto&& [path, _] : bindPoints) {
1025 mBindsByPath.erase(path);
1026 }
1027 mMounts.erase(ifs.mountId);
1028}
1029
1030StorageId IncrementalService::openStorage(std::string_view pathInMount) {
1031 if (!path::isAbsolute(pathInMount)) {
1032 return kInvalidStorageId;
1033 }
1034
1035 return findStorageId(path::normalize(pathInMount));
1036}
1037
Songchun Fan3c82a302019-11-29 14:23:45 -08001038IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
1039 std::lock_guard l(mLock);
1040 return getIfsLocked(storage);
1041}
1042
1043const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
1044 auto it = mMounts.find(storage);
1045 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001046 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -07001047 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -08001048 }
1049 return it->second;
1050}
1051
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001052int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
1053 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001054 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001055 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001056 return -EINVAL;
1057 }
1058
1059 const auto ifs = getIfs(storage);
1060 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001061 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001062 return -EINVAL;
1063 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001064
Songchun Fan3c82a302019-11-29 14:23:45 -08001065 std::unique_lock l(ifs->lock);
1066 const auto storageInfo = ifs->storages.find(storage);
1067 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001068 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -08001069 return -EINVAL;
1070 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001071 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001072 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001073 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001074 return -EINVAL;
1075 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001076 l.unlock();
1077 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001078 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
1079 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -08001080}
1081
1082int IncrementalService::unbind(StorageId storage, std::string_view target) {
1083 if (!path::isAbsolute(target)) {
1084 return -EINVAL;
1085 }
1086
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001087 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001088
1089 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
1090 // otherwise there's a chance to unmount something completely unrelated
1091 const auto norm = path::normalize(target);
1092 std::unique_lock l(mLock);
1093 const auto storageIt = mBindsByPath.find(norm);
1094 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
1095 return -EINVAL;
1096 }
1097 const auto bindIt = storageIt->second;
1098 const auto storageId = bindIt->second.storage;
1099 const auto ifs = getIfsLocked(storageId);
1100 if (!ifs) {
1101 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
1102 << " is missing";
1103 return -EFAULT;
1104 }
1105 mBindsByPath.erase(storageIt);
1106 l.unlock();
1107
1108 mVold->unmountIncFs(bindIt->first);
1109 std::unique_lock l2(ifs->lock);
1110 if (ifs->bindPoints.size() <= 1) {
1111 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -07001112 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001113 } else {
1114 const std::string savedFile = std::move(bindIt->second.savedFilename);
1115 ifs->bindPoints.erase(bindIt);
1116 l2.unlock();
1117 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001118 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001119 }
1120 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001121
Songchun Fan3c82a302019-11-29 14:23:45 -08001122 return 0;
1123}
1124
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001125std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001126 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001127 std::string_view path) const {
1128 if (!path::isAbsolute(path)) {
1129 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001130 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001131 auto normPath = path::normalize(path);
1132 if (path::startsWith(normPath, storageIt->second.name)) {
1133 return normPath;
1134 }
1135 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001136 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1137 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001138 return {};
1139 }
1140 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001141}
1142
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001143std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001144 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001145 std::unique_lock l(ifs.lock);
1146 const auto storageInfo = ifs.storages.find(storage);
1147 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001148 return {};
1149 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001150 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001151}
1152
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001153int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001154 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001155 const auto ifs = getIfs(storage);
1156 if (!ifs) {
1157 return -EINVAL;
1158 }
1159 if (data.size() > params.size) {
1160 LOG(ERROR) << "Bad data size - bigger than file size";
1161 return -EINVAL;
1162 }
1163 if (!data.empty() && data.size() != params.size) {
1164 // Writing a page is an irreversible operation, and it can't be updated with additional
1165 // data later. Check that the last written page is complete, or we may break the file.
1166 if (!isPageAligned(data.size())) {
1167 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001168 return -EINVAL;
1169 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001170 }
1171 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1172 if (normPath.empty()) {
1173 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1174 return -EINVAL;
1175 }
1176 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy98a3c8f2021-05-12 13:25:38 -07001177 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile [" << normPath
1178 << "]: " << err;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001179 return err;
1180 }
1181 if (params.size > 0) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001182 if (auto err = mIncFs->reserveSpace(ifs->control, id, params.size)) {
1183 if (err != -EOPNOTSUPP) {
1184 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1185 (void)mIncFs->unlink(ifs->control, normPath);
1186 return err;
1187 } else {
1188 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1189 "may run out of disk later";
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001190 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001191 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001192 if (!data.empty()) {
1193 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001194 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001195 return err;
1196 }
1197 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001198 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001199 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001200}
1201
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001202int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001203 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001204 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001205 if (normPath.empty()) {
1206 return -EINVAL;
1207 }
1208 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001209 }
1210 return -EINVAL;
1211}
1212
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001213int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001214 const auto ifs = getIfs(storageId);
1215 if (!ifs) {
1216 return -EINVAL;
1217 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001218 return makeDirs(*ifs, storageId, path, mode);
1219}
1220
1221int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1222 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001223 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1224 if (normPath.empty()) {
1225 return -EINVAL;
1226 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001227 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001228}
1229
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001230int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1231 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001232 std::unique_lock l(mLock);
1233 auto ifsSrc = getIfsLocked(sourceStorageId);
1234 if (!ifsSrc) {
1235 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001236 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001237 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1238 return -EINVAL;
1239 }
1240 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001241 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1242 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001243 if (normOldPath.empty() || normNewPath.empty()) {
1244 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1245 return -EINVAL;
1246 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001247 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1248 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1249 << " to " << newPath << "[" << normNewPath << "]";
1250 return err;
1251 }
1252 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001253}
1254
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001255int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001256 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001257 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001258 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001259 }
1260 return -EINVAL;
1261}
1262
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001263int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1264 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001265 std::string&& target, BindKind kind,
1266 std::unique_lock<std::mutex>& mainLock) {
1267 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001268 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001269 return -EINVAL;
1270 }
1271
1272 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001273 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001274 if (kind != BindKind::Temporary) {
1275 metadata::BindPoint bp;
1276 bp.set_storage_id(storage);
1277 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001278 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001279 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001280 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001281 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001282 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001283 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1284 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1285 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001286 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001287 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001288 return int(node);
1289 }
1290 }
1291
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001292 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1293 std::move(target), kind, mainLock);
1294 if (res) {
1295 mIncFs->unlink(ifs.control, metadataFullPath);
1296 }
1297 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001298}
1299
1300int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001301 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001302 std::string&& target, BindKind kind,
1303 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001304 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001305 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001306 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001307 if (!status.isOk()) {
1308 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1309 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1310 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1311 : status.serviceSpecificErrorCode() == 0
1312 ? -EFAULT
1313 : status.serviceSpecificErrorCode()
1314 : -EIO;
1315 }
1316 }
1317
1318 if (!mainLock.owns_lock()) {
1319 mainLock.lock();
1320 }
1321 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001322 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1323 std::move(target), kind);
1324 return 0;
1325}
1326
1327void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1328 std::string&& metadataName, std::string&& source,
1329 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001330 const auto [it, _] =
1331 ifs.bindPoints.insert_or_assign(target,
1332 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001333 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001334 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001335}
1336
1337RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1338 const auto ifs = getIfs(storage);
1339 if (!ifs) {
1340 return {};
1341 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001342 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001343 if (normPath.empty()) {
1344 return {};
1345 }
1346 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001347}
1348
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001349RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001350 const auto ifs = getIfs(storage);
1351 if (!ifs) {
1352 return {};
1353 }
1354 return mIncFs->getMetadata(ifs->control, node);
1355}
1356
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001357void IncrementalService::setUidReadTimeouts(StorageId storage,
1358 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001359 using microseconds = std::chrono::microseconds;
1360 using milliseconds = std::chrono::milliseconds;
1361
1362 auto maxPendingTimeUs = microseconds(0);
1363 for (const auto& timeouts : perUidReadTimeouts) {
1364 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1365 }
1366 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07001367 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001368 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1369 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001370 return;
1371 }
1372
1373 const auto ifs = getIfs(storage);
1374 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001375 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001376 return;
1377 }
1378
1379 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1380 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1381 return;
1382 }
1383
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001384 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1385 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1386 if (checkUidReadTimeouts(storageId, state, timeout)) {
1387 return true;
1388 }
1389 clearUidReadTimeouts(storageId);
1390 return false;
1391 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001392}
1393
1394void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1395 const auto ifs = getIfs(storage);
1396 if (!ifs) {
1397 return;
1398 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001399 mIncFs->setUidReadTimeouts(ifs->control, {});
1400}
1401
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001402bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1403 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001404 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001405 // Reached maximum timeout.
1406 return false;
1407 }
1408 if (state.error) {
1409 // Something is wrong, abort.
1410 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001411 }
1412
1413 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001414 if (state.fullyLoaded && !state.readLogsEnabled) {
1415 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001416 }
1417
1418 const auto timeLeft = timeLimit - Clock::now();
1419 if (timeLeft < Constants::progressUpdateInterval) {
1420 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001421 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001422 }
1423
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001424 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001425}
1426
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001427std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1428 std::unordered_set<std::string_view> mountedRootNames;
1429 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1430 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1431 for (auto [source, target] : binds) {
1432 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1433 LOG(INFO) << " " << path::join(root, source);
1434 }
1435
1436 // Ensure it's a kind of a mount that's managed by IncrementalService
1437 if (path::basename(root) != constants().mount ||
1438 path::basename(backingDir) != constants().backing) {
1439 return;
1440 }
1441 const auto expectedRoot = path::dirname(root);
1442 if (path::dirname(backingDir) != expectedRoot) {
1443 return;
1444 }
1445 if (path::dirname(expectedRoot) != mIncrementalDir) {
1446 return;
1447 }
1448 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1449 return;
1450 }
1451
1452 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1453
1454 // make sure we clean up the mount if it happens to be a bad one.
1455 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1456 auto cleanupFiles = makeCleanup([&]() {
1457 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1458 IncFsMount::cleanupFilesystem(expectedRoot);
1459 });
1460 auto cleanupMounts = makeCleanup([&]() {
1461 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1462 for (auto&& [_, target] : binds) {
1463 mVold->unmountIncFs(std::string(target));
1464 }
1465 mVold->unmountIncFs(std::string(root));
1466 });
1467
1468 auto control = mIncFs->openMount(root);
1469 if (!control) {
1470 LOG(INFO) << "failed to open mount " << root;
1471 return;
1472 }
1473
1474 auto mountRecord =
1475 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1476 path::join(root, constants().infoMdName));
1477 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1478 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1479 return;
1480 }
1481
1482 auto mountId = mountRecord.storage().id();
1483 mNextId = std::max(mNextId, mountId + 1);
1484
1485 DataLoaderParamsParcel dataLoaderParams;
1486 {
1487 const auto& loader = mountRecord.loader();
1488 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1489 dataLoaderParams.packageName = loader.package_name();
1490 dataLoaderParams.className = loader.class_name();
1491 dataLoaderParams.arguments = loader.arguments();
1492 }
1493
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001494 // Not way to obtain a real sysfs key at this point - metrics will stop working after "soft"
1495 // reboot.
1496 std::string metricsKey{};
1497 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), std::move(metricsKey),
1498 mountId, std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001499 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001500
Alex Buynytskyy04035452020-06-06 20:15:58 -07001501 // Check if marker file present.
1502 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001503 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001504 }
1505
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001506 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1507 auto d = openDir(root);
1508 while (auto e = ::readdir(d.get())) {
1509 if (e->d_type == DT_REG) {
1510 auto name = std::string_view(e->d_name);
1511 if (name.starts_with(constants().mountpointMdPrefix)) {
1512 permanentBindPoints
1513 .emplace_back(name,
1514 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1515 ifs->control,
1516 path::join(root,
1517 name)));
1518 if (permanentBindPoints.back().second.dest_path().empty() ||
1519 permanentBindPoints.back().second.source_subdir().empty()) {
1520 permanentBindPoints.pop_back();
1521 mIncFs->unlink(ifs->control, path::join(root, name));
1522 } else {
1523 LOG(INFO) << "Permanent bind record: '"
1524 << permanentBindPoints.back().second.source_subdir() << "'->'"
1525 << permanentBindPoints.back().second.dest_path() << "'";
1526 }
1527 }
1528 } else if (e->d_type == DT_DIR) {
1529 if (e->d_name == "."sv || e->d_name == ".."sv) {
1530 continue;
1531 }
1532 auto name = std::string_view(e->d_name);
1533 if (name.starts_with(constants().storagePrefix)) {
1534 int storageId;
1535 const auto res =
1536 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1537 name.data() + name.size(), storageId);
1538 if (res.ec != std::errc{} || *res.ptr != '_') {
1539 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1540 << "' for mount " << expectedRoot;
1541 continue;
1542 }
1543 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1544 if (!inserted) {
1545 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1546 << " for mount " << expectedRoot;
1547 continue;
1548 }
1549 ifs->storages.insert_or_assign(storageId,
1550 IncFsMount::Storage{path::join(root, name)});
1551 mNextId = std::max(mNextId, storageId + 1);
1552 }
1553 }
1554 }
1555
1556 if (ifs->storages.empty()) {
1557 LOG(WARNING) << "No valid storages in mount " << root;
1558 return;
1559 }
1560
1561 // now match the mounted directories with what we expect to have in the metadata
1562 {
1563 std::unique_lock l(mLock, std::defer_lock);
1564 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1565 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1566 [&, bindRecord = bindRecord](auto&& bind) {
1567 return bind.second == bindRecord.dest_path() &&
1568 path::join(root, bind.first) ==
1569 bindRecord.source_subdir();
1570 });
1571 if (mountedIt != binds.end()) {
1572 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1573 << " to mount " << mountedIt->first;
1574 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1575 std::move(*bindRecord.mutable_source_subdir()),
1576 std::move(*bindRecord.mutable_dest_path()),
1577 BindKind::Permanent);
1578 if (mountedIt != binds.end() - 1) {
1579 std::iter_swap(mountedIt, binds.end() - 1);
1580 }
1581 binds = binds.first(binds.size() - 1);
1582 } else {
1583 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1584 << ", mounting";
1585 // doesn't exist - try mounting back
1586 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1587 std::move(*bindRecord.mutable_source_subdir()),
1588 std::move(*bindRecord.mutable_dest_path()),
1589 BindKind::Permanent, l)) {
1590 mIncFs->unlink(ifs->control, metadataFile);
1591 }
1592 }
1593 }
1594 }
1595
1596 // if anything stays in |binds| those are probably temporary binds; system restarted since
1597 // they were mounted - so let's unmount them all.
1598 for (auto&& [source, target] : binds) {
1599 if (source.empty()) {
1600 continue;
1601 }
1602 mVold->unmountIncFs(std::string(target));
1603 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001604 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001605
1606 if (ifs->bindPoints.empty()) {
1607 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1608 deleteStorage(*ifs);
1609 return;
1610 }
1611
1612 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1613 CHECK(ifs->dataLoaderStub);
1614
1615 mountedRootNames.insert(path::basename(ifs->root));
1616
1617 // not locking here at all: we're still in the constructor, no other calls can happen
1618 mMounts[ifs->mountId] = std::move(ifs);
1619 });
1620
1621 return mountedRootNames;
1622}
1623
1624void IncrementalService::mountExistingImages(
1625 const std::unordered_set<std::string_view>& mountedRootNames) {
1626 auto dir = openDir(mIncrementalDir);
1627 if (!dir) {
1628 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1629 return;
1630 }
1631 while (auto entry = ::readdir(dir.get())) {
1632 if (entry->d_type != DT_DIR) {
1633 continue;
1634 }
1635 std::string_view name = entry->d_name;
1636 if (!name.starts_with(constants().mountKeyPrefix)) {
1637 continue;
1638 }
1639 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001640 continue;
1641 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001642 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001643 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001644 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001645 }
1646 }
1647}
1648
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001649bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001650 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001651 const auto backing = path::join(root, constants().backing);
Songchun Fanf949c372021-04-27 11:26:25 -07001652 std::string mountKey(path::basename(path::dirname(mountTarget)));
Songchun Fan3c82a302019-11-29 14:23:45 -08001653
Songchun Fan3c82a302019-11-29 14:23:45 -08001654 IncrementalFileSystemControlParcel controlParcel;
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001655 auto metricsKey = makeUniqueName(mountKey);
1656 auto status = mVold->mountIncFs(backing, mountTarget, 0, metricsKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001657 if (!status.isOk()) {
1658 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1659 return false;
1660 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001661
1662 int cmd = controlParcel.cmd.release().release();
1663 int pendingReads = controlParcel.pendingReads.release().release();
1664 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001665 int blocksWritten =
1666 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1667 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001668
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001669 auto ifs = std::make_shared<IncFsMount>(std::string(root), std::move(metricsKey), -1,
1670 std::move(control), *this);
Songchun Fan3c82a302019-11-29 14:23:45 -08001671
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001672 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1673 path::join(mountTarget, constants().infoMdName));
1674 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001675 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1676 return false;
1677 }
1678
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001679 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001680 mNextId = std::max(mNextId, ifs->mountId + 1);
1681
Alex Buynytskyy04035452020-06-06 20:15:58 -07001682 // Check if marker file present.
1683 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001684 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001685 }
1686
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001687 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001688 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001689 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001690 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001691 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001692 dataLoaderParams.packageName = loader.package_name();
1693 dataLoaderParams.className = loader.class_name();
1694 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001695 }
1696
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001697 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001698 CHECK(ifs->dataLoaderStub);
1699
Songchun Fan3c82a302019-11-29 14:23:45 -08001700 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001701 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001702 while (auto e = ::readdir(d.get())) {
1703 if (e->d_type == DT_REG) {
1704 auto name = std::string_view(e->d_name);
1705 if (name.starts_with(constants().mountpointMdPrefix)) {
1706 bindPoints.emplace_back(name,
1707 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1708 ifs->control,
1709 path::join(mountTarget,
1710 name)));
1711 if (bindPoints.back().second.dest_path().empty() ||
1712 bindPoints.back().second.source_subdir().empty()) {
1713 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001714 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001715 }
1716 }
1717 } else if (e->d_type == DT_DIR) {
1718 if (e->d_name == "."sv || e->d_name == ".."sv) {
1719 continue;
1720 }
1721 auto name = std::string_view(e->d_name);
1722 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001723 int storageId;
1724 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1725 name.data() + name.size(), storageId);
1726 if (res.ec != std::errc{} || *res.ptr != '_') {
1727 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1728 << root;
1729 continue;
1730 }
1731 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001732 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001733 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001734 << " for mount " << root;
1735 continue;
1736 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001737 ifs->storages.insert_or_assign(storageId,
1738 IncFsMount::Storage{
1739 path::join(root, constants().mount, name)});
1740 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001741 }
1742 }
1743 }
1744
1745 if (ifs->storages.empty()) {
1746 LOG(WARNING) << "No valid storages in mount " << root;
1747 return false;
1748 }
1749
1750 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001751 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001752 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001753 for (auto&& bp : bindPoints) {
1754 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1755 std::move(*bp.second.mutable_source_subdir()),
1756 std::move(*bp.second.mutable_dest_path()),
1757 BindKind::Permanent, l);
1758 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001759 }
1760
1761 if (bindCount == 0) {
1762 LOG(WARNING) << "No valid bind points for mount " << root;
1763 deleteStorage(*ifs);
1764 return false;
1765 }
1766
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001767 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001768 mMounts[ifs->mountId] = std::move(ifs);
1769 return true;
1770}
1771
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001772void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001773 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001774 while (mRunning.load(std::memory_order_relaxed)) {
1775 mLooper->pollAll(kTimeoutMsecs);
1776 }
1777}
1778
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001779void IncrementalService::trimReservedSpaceV1(const IncFsMount& ifs) {
1780 mIncFs->forEachFile(ifs.control, [this](auto&& control, auto&& fileId) {
1781 if (mIncFs->isFileFullyLoaded(control, fileId) == incfs::LoadingState::Full) {
1782 mIncFs->reserveSpace(control, fileId, -1);
1783 }
1784 return true;
1785 });
1786}
1787
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001788void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001789 DataLoaderStatusListener&& statusListener,
1790 const StorageHealthCheckParams& healthCheckParams,
1791 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001792 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001793 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001794 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1795 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1796 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001797 if (ifs.control.blocksWritten() >= 0) {
1798 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1799 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001800 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001801
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001802 ifs.dataLoaderStub =
1803 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001804 std::move(statusListener), healthCheckParams,
1805 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001806
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001807 // pre-v2 IncFS doesn't do automatic reserved space trimming - need to run it manually
1808 if (!(mIncFs->features() & incfs::Features::v2)) {
1809 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1810 if (!state.fullyLoaded) {
1811 return true;
1812 }
1813
1814 const auto ifs = getIfs(storageId);
1815 if (!ifs) {
1816 return false;
1817 }
1818 trimReservedSpaceV1(*ifs);
1819 return false;
1820 });
1821 }
1822
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001823 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1824 if (!state.fullyLoaded || state.readLogsEnabled) {
1825 return true;
1826 }
1827
1828 DataLoaderStubPtr dataLoaderStub;
1829 {
1830 const auto ifs = getIfs(storageId);
1831 if (!ifs) {
1832 return false;
1833 }
1834
1835 std::unique_lock l(ifs->lock);
1836 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1837 }
1838
1839 if (dataLoaderStub) {
1840 dataLoaderStub->cleanupResources();
1841 }
1842
1843 return false;
1844 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001845}
1846
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001847template <class Duration>
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001848static constexpr auto castToMs(Duration d) {
1849 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1850}
1851
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001852// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001853// Lib files should be placed next to the APK file in the following matter:
1854// Example:
1855// /path/to/base.apk
1856// /path/to/lib/arm/first.so
1857// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001858bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1859 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001860 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001861 auto start = Clock::now();
1862
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001863 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001864 if (!ifs) {
1865 LOG(ERROR) << "Invalid storage " << storage;
1866 return false;
1867 }
1868
Songchun Fanc8975312020-07-13 12:14:37 -07001869 const auto targetLibPathRelativeToStorage =
1870 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1871 libDirRelativePath);
1872
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001873 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001874 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1875 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001876 << " errno: " << res;
1877 return false;
1878 }
1879
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001880 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001881 ZipArchiveHandle zipFileHandle;
1882 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001883 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1884 return false;
1885 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001886
1887 // Need a shared pointer: will be passing it into all unpacking jobs.
1888 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001889 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001890 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001891 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001892 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1893 return false;
1894 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001895 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001896 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1897
1898 auto openZipTs = Clock::now();
1899
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001900 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1901 incfs::FileId sourceId;
1902 if (mapFiles) {
1903 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1904 if (!incfs::isValidFileId(sourceId)) {
1905 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1906 << "', mapping disabled";
1907 mapFiles = false;
1908 }
1909 }
1910
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001911 std::vector<Job> jobQueue;
1912 ZipEntry entry;
1913 std::string_view fileName;
1914 while (!Next(cookie, &entry, &fileName)) {
1915 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001916 continue;
1917 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001918
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001919 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001920 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001921
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001922 if (!extractNativeLibs) {
1923 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001924 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001925 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1926 return false;
1927 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001928 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001929 LOG(WARNING) << "Library " << fileName
1930 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1931 << entry.offset;
1932 return false;
1933 }
1934 continue;
1935 }
1936
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001937 auto startFileTs = Clock::now();
1938
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001939 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001940 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001941 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001942 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001943 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001944 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001945 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1946 << "; skipping extraction, spent "
1947 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1948 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001949 continue;
1950 }
1951
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001952 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1953 incfs::NewMappedFileParams mappedFileParams = {
1954 .sourceId = sourceId,
1955 .sourceOffset = entry.offset,
1956 .size = entry.uncompressed_length,
1957 };
1958
1959 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1960 mappedFileParams);
1961 res == 0) {
1962 if (perfLoggingEnabled()) {
1963 auto doneTs = Clock::now();
1964 LOG(INFO) << "incfs: Mapped " << libName << ": "
1965 << elapsedMcs(startFileTs, doneTs) << "mcs";
1966 }
1967 continue;
1968 } else {
1969 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1970 << "; falling back to full extraction";
1971 }
1972 }
1973
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001974 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001975 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001976 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001977 .signature = {},
1978 // Metadata of the new lib file is its relative path
1979 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1980 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001981 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001982 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001983 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001984 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001985 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001986 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001987 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001988
1989 auto makeFileTs = Clock::now();
1990
Songchun Fanafaf6e92020-03-18 14:12:20 -07001991 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001992 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001993 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001994 LOG(INFO) << "incfs: Extracted " << libName
1995 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001996 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001997 continue;
1998 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001999
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002000 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
2001 libFileId, libPath = std::move(targetLibPath),
2002 makeFileTs]() mutable {
2003 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002004 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002005
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002006 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002007 auto prepareJobTs = Clock::now();
2008 LOG(INFO) << "incfs: Processed " << libName << ": "
2009 << elapsedMcs(startFileTs, prepareJobTs)
2010 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
2011 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002012 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002013 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002014
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002015 auto processedTs = Clock::now();
2016
2017 if (!jobQueue.empty()) {
2018 {
2019 std::lock_guard lock(mJobMutex);
2020 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002021 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002022 if (existingJobs.empty()) {
2023 existingJobs = std::move(jobQueue);
2024 } else {
2025 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
2026 std::move_iterator(jobQueue.end()));
2027 }
2028 }
2029 }
2030 mJobCondition.notify_all();
2031 }
2032
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002033 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002034 auto end = Clock::now();
2035 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
2036 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
2037 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002038 << " make files: " << elapsedMcs(openZipTs, processedTs)
2039 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002040 }
2041
2042 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002043}
2044
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002045void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
2046 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002047 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002048 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002049 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002050 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002051 return;
2052 }
2053
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002054 auto startedTs = Clock::now();
2055
2056 // Write extracted data to new file
2057 // NOTE: don't zero-initialize memory, it may take a while for nothing
2058 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
2059 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002060 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002061 return;
2062 }
2063
2064 auto extractFileTs = Clock::now();
2065
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002066 if (setFileContent(ifs, libFileId, debugLibPath,
2067 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002068 return;
2069 }
2070
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002071 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002072 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002073 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
2074 << entry.compressed_length << " -> " << entry.uncompressed_length
2075 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002076 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
2077 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002078 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002079 }
2080}
2081
2082bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002083 struct WaitPrinter {
2084 const Clock::time_point startTs = Clock::now();
2085 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002086 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002087 const auto endTs = Clock::now();
2088 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
2089 << elapsedMcs(startTs, endTs) << "mcs";
2090 }
2091 }
2092 } waitPrinter;
2093
2094 MountId mount;
2095 {
2096 auto ifs = getIfs(storage);
2097 if (!ifs) {
2098 return true;
2099 }
2100 mount = ifs->mountId;
2101 }
2102
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002103 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002104 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002105 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002106 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002107 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002108 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002109}
2110
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002111int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
2112 std::string_view debugFilePath,
2113 std::span<const uint8_t> data) const {
2114 auto startTs = Clock::now();
2115
2116 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2117 if (!writeFd.ok()) {
2118 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2119 << " errno: " << writeFd.get();
2120 return writeFd.get();
2121 }
2122
2123 const auto dataLength = data.size();
2124
2125 auto openFileTs = Clock::now();
2126 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2127 std::vector<IncFsDataBlock> instructions(numBlocks);
2128 for (int i = 0; i < numBlocks; i++) {
2129 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2130 instructions[i] = IncFsDataBlock{
2131 .fileFd = writeFd.get(),
2132 .pageIndex = static_cast<IncFsBlockIndex>(i),
2133 .compression = INCFS_COMPRESSION_KIND_NONE,
2134 .kind = INCFS_BLOCK_KIND_DATA,
2135 .dataSize = static_cast<uint32_t>(blockSize),
2136 .data = reinterpret_cast<const char*>(data.data()),
2137 };
2138 data = data.subspan(blockSize);
2139 }
2140 auto prepareInstsTs = Clock::now();
2141
2142 size_t res = mIncFs->writeBlocks(instructions);
2143 if (res != instructions.size()) {
2144 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2145 return res;
2146 }
2147
2148 if (perfLoggingEnabled()) {
2149 auto endTs = Clock::now();
2150 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2151 << " bytes): " << elapsedMcs(startTs, endTs)
2152 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2153 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2154 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2155 }
2156
2157 return 0;
2158}
2159
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002160incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2161 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002162 std::unique_lock l(mLock);
2163 const auto ifs = getIfsLocked(storage);
2164 if (!ifs) {
2165 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002166 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002167 }
2168 const auto storageInfo = ifs->storages.find(storage);
2169 if (storageInfo == ifs->storages.end()) {
2170 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002171 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002172 }
2173 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002174 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002175}
2176
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002177incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2178 const auto ifs = getIfs(storage);
2179 if (!ifs) {
2180 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2181 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002182 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002183 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002184}
2185
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002186IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002187 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002188 std::unique_lock l(mLock);
2189 const auto ifs = getIfsLocked(storage);
2190 if (!ifs) {
2191 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002192 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002193 }
2194 const auto storageInfo = ifs->storages.find(storage);
2195 if (storageInfo == ifs->storages.end()) {
2196 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002197 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002198 }
2199 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002200 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002201}
2202
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002203IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002204 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002205 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2206 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002207 const auto [filledBlocksCount, totalBlocksCount] =
2208 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002209 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2210 filledBlocksCount == -ENOENT) {
2211 // a kind of a file that's not really being loaded, e.g. a mapped range
2212 // an older IncFS used to return ENOENT in this case, so handle it the same way
2213 return true;
2214 }
Songchun Fan374f7652020-08-20 08:40:29 -07002215 if (filledBlocksCount < 0) {
2216 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002217 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002218 error = filledBlocksCount;
2219 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002220 }
2221 totalBlocks += totalBlocksCount;
2222 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002223 return true;
2224 });
Songchun Fan374f7652020-08-20 08:40:29 -07002225
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002226 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002227}
2228
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002229bool IncrementalService::updateLoadingProgress(StorageId storage,
2230 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002231 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002232 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002233 // Failed to get progress from incfs, abort.
2234 return false;
2235 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002236 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2237 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002238 // Stop updating progress once it is fully loaded
2239 return true;
2240 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002241 addTimedJob(*mProgressUpdateJobQueue, storage,
2242 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002243 [storage, progressListener = std::move(progressListener), this]() mutable {
2244 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002245 });
2246 return true;
2247}
2248
2249bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002250 StorageId storage, StorageLoadingProgressListener progressListener) {
2251 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002252}
2253
2254bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2255 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2256}
2257
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002258bool IncrementalService::perfLoggingEnabled() {
2259 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2260 return enabled;
2261}
2262
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002263void IncrementalService::runJobProcessing() {
2264 for (;;) {
2265 std::unique_lock lock(mJobMutex);
2266 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2267 if (!mRunning) {
2268 return;
2269 }
2270
2271 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002272 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002273 auto queue = std::move(it->second);
2274 mJobQueue.erase(it);
2275 lock.unlock();
2276
2277 for (auto&& job : queue) {
2278 job();
2279 }
2280
2281 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002282 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002283 lock.unlock();
2284 mJobCondition.notify_all();
2285 }
2286}
2287
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002288void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002289 sp<IAppOpsCallback> listener;
2290 {
2291 std::unique_lock lock{mCallbacksLock};
2292 auto& cb = mCallbackRegistered[packageName];
2293 if (cb) {
2294 return;
2295 }
2296 cb = new AppOpsListener(*this, packageName);
2297 listener = cb;
2298 }
2299
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002300 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2301 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002302}
2303
2304bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2305 sp<IAppOpsCallback> listener;
2306 {
2307 std::unique_lock lock{mCallbacksLock};
2308 auto found = mCallbackRegistered.find(packageName);
2309 if (found == mCallbackRegistered.end()) {
2310 return false;
2311 }
2312 listener = found->second;
2313 mCallbackRegistered.erase(found);
2314 }
2315
2316 mAppOpsManager->stopWatchingMode(listener);
2317 return true;
2318}
2319
2320void IncrementalService::onAppOpChanged(const std::string& packageName) {
2321 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002322 return;
2323 }
2324
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002325 std::vector<IfsMountPtr> affected;
2326 {
2327 std::lock_guard l(mLock);
2328 affected.reserve(mMounts.size());
2329 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002330 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002331 if (ifs->mountId == id && ifs->dataLoaderStub &&
2332 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002333 affected.push_back(ifs);
2334 }
2335 }
2336 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002337 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002338 std::unique_lock ll(ifs->lock);
2339 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002340 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002341}
2342
Songchun Fana7098592020-09-03 11:45:53 -07002343bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2344 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002345 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002346 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002347 }
Songchun Fana7098592020-09-03 11:45:53 -07002348 timedQueue.addJob(id, after, std::move(what));
2349 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002350}
2351
Songchun Fana7098592020-09-03 11:45:53 -07002352bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002353 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002354 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002355 }
Songchun Fana7098592020-09-03 11:45:53 -07002356 timedQueue.removeJobs(id);
2357 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002358}
2359
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002360void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2361 bool wasEmpty;
2362 {
2363 std::lock_guard l(mIfsStateCallbacksLock);
2364 wasEmpty = mIfsStateCallbacks.empty();
2365 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2366 }
2367 if (wasEmpty) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002368 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002369 [this]() { processIfsStateCallbacks(); });
2370 }
2371}
2372
2373void IncrementalService::processIfsStateCallbacks() {
2374 StorageId storageId = kInvalidStorageId;
2375 std::vector<IfsStateCallback> local;
2376 while (true) {
2377 {
2378 std::lock_guard l(mIfsStateCallbacksLock);
2379 if (mIfsStateCallbacks.empty()) {
2380 return;
2381 }
2382 IfsStateCallbacks::iterator it;
2383 if (storageId == kInvalidStorageId) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002384 // First entry, initialize the |it|.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002385 it = mIfsStateCallbacks.begin();
2386 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002387 // Subsequent entries, update the |storageId|, and shift to the new one (not that
2388 // it guarantees much about updated items, but at least the loop will finish).
2389 it = mIfsStateCallbacks.lower_bound(storageId);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002390 if (it == mIfsStateCallbacks.end()) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002391 // Nothing else left, too bad.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002392 break;
2393 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002394 if (it->first != storageId) {
2395 local.clear(); // Was removed during processing, forget the old callbacks.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002396 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002397 // Put the 'surviving' callbacks back into the map and advance the position.
2398 auto& callbacks = it->second;
2399 if (callbacks.empty()) {
2400 std::swap(callbacks, local);
2401 } else {
2402 callbacks.insert(callbacks.end(), std::move_iterator(local.begin()),
2403 std::move_iterator(local.end()));
2404 local.clear();
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002405 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002406 if (callbacks.empty()) {
2407 it = mIfsStateCallbacks.erase(it);
2408 if (mIfsStateCallbacks.empty()) {
2409 return;
2410 }
2411 } else {
2412 ++it;
2413 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002414 }
2415 }
2416
2417 if (it == mIfsStateCallbacks.end()) {
2418 break;
2419 }
2420
2421 storageId = it->first;
2422 auto& callbacks = it->second;
2423 if (callbacks.empty()) {
2424 // Invalid case, one extra lookup should be ok.
2425 continue;
2426 }
2427 std::swap(callbacks, local);
2428 }
2429
2430 processIfsStateCallbacks(storageId, local);
2431 }
2432
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002433 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002434 [this]() { processIfsStateCallbacks(); });
2435}
2436
2437void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2438 std::vector<IfsStateCallback>& callbacks) {
2439 const auto state = isMountFullyLoaded(storageId);
2440 IfsState storageState = {};
2441 storageState.error = int(state) < 0;
2442 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2443 if (storageState.fullyLoaded) {
2444 const auto ifs = getIfs(storageId);
2445 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2446 }
2447
2448 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2449 if ((*cur)(storageId, storageState)) {
2450 ++cur;
2451 } else {
2452 cur = callbacks.erase(cur);
2453 }
2454 }
2455}
2456
2457void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2458 std::lock_guard l(mIfsStateCallbacksLock);
2459 mIfsStateCallbacks.erase(storageId);
2460}
2461
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002462void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002463 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002464 if (!ifs) {
Songchun Fan9471be52021-04-21 17:49:27 -07002465 LOG(ERROR) << "getMetrics failed, invalid storageId: " << storageId;
2466 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002467 }
Songchun Fan0dc77722021-05-03 17:13:52 -07002468 const auto& kMetricsReadLogsEnabled =
Songchun Fan9471be52021-04-21 17:49:27 -07002469 os::incremental::BnIncrementalService::METRICS_READ_LOGS_ENABLED();
Songchun Fan0dc77722021-05-03 17:13:52 -07002470 result->putBoolean(String16(kMetricsReadLogsEnabled.c_str()), ifs->readLogsEnabled() != 0);
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07002471 const auto incfsMetrics = mIncFs->getMetrics(ifs->metricsKey);
Songchun Fan0dc77722021-05-03 17:13:52 -07002472 if (incfsMetrics) {
2473 const auto& kMetricsTotalDelayedReads =
2474 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS();
2475 const auto totalDelayedReads =
2476 incfsMetrics->readsDelayedMin + incfsMetrics->readsDelayedPending;
2477 result->putInt(String16(kMetricsTotalDelayedReads.c_str()), totalDelayedReads);
2478 const auto& kMetricsTotalFailedReads =
2479 os::incremental::BnIncrementalService::METRICS_TOTAL_FAILED_READS();
2480 const auto totalFailedReads = incfsMetrics->readsFailedTimedOut +
2481 incfsMetrics->readsFailedHashVerification + incfsMetrics->readsFailedOther;
2482 result->putInt(String16(kMetricsTotalFailedReads.c_str()), totalFailedReads);
2483 const auto& kMetricsTotalDelayedReadsMillis =
2484 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS_MILLIS();
2485 const int64_t totalDelayedReadsMillis =
2486 (incfsMetrics->readsDelayedMinUs + incfsMetrics->readsDelayedPendingUs) / 1000;
2487 result->putLong(String16(kMetricsTotalDelayedReadsMillis.c_str()), totalDelayedReadsMillis);
2488 }
2489 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
2490 if (lastReadError && lastReadError->timestampUs != 0) {
2491 const auto& kMetricsMillisSinceLastReadError =
2492 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_READ_ERROR();
2493 result->putLong(String16(kMetricsMillisSinceLastReadError.c_str()),
2494 (int64_t)elapsedUsSinceMonoTs(lastReadError->timestampUs) / 1000);
2495 const auto& kMetricsLastReadErrorNo =
2496 os::incremental::BnIncrementalService::METRICS_LAST_READ_ERROR_NUMBER();
2497 result->putInt(String16(kMetricsLastReadErrorNo.c_str()), lastReadError->errorNo);
2498 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002499 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002500 if (!ifs->dataLoaderStub) {
Songchun Fan9471be52021-04-21 17:49:27 -07002501 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002502 }
Songchun Fan9471be52021-04-21 17:49:27 -07002503 ifs->dataLoaderStub->getMetrics(result);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002504}
2505
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002506IncrementalService::DataLoaderStub::DataLoaderStub(
2507 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2508 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2509 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2510 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002511 : mService(service),
2512 mId(id),
2513 mParams(std::move(params)),
2514 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002515 mStatusListener(std::move(statusListener)),
2516 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002517 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002518 mHealthCheckParams(healthCheckParams) {
2519 if (mHealthListener && !isHealthParamsValid()) {
2520 mHealthListener = {};
2521 }
2522 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002523 // Disable advanced health check statuses.
2524 mHealthCheckParams.blockedTimeoutMs = -1;
2525 }
2526 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002527}
2528
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002529IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002530 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002531 cleanupResources();
2532 }
2533}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002534
2535void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002536 auto now = Clock::now();
2537 {
2538 std::unique_lock lock(mMutex);
2539 mHealthPath.clear();
2540 unregisterFromPendingReads();
2541 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002542 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002543 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002544 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002545
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002546 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002547
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002548 {
2549 std::unique_lock lock(mMutex);
2550 mParams = {};
2551 mControl = {};
2552 mHealthControl = {};
2553 mHealthListener = {};
2554 mStatusCondition.wait_until(lock, now + 60s, [this] {
2555 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2556 });
2557 mStatusListener = {};
2558 mId = kInvalidStorageId;
2559 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002560}
2561
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002562sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2563 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002564 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002565 if (!status.isOk()) {
2566 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2567 return {};
2568 }
2569 if (!dataloader) {
2570 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2571 return {};
2572 }
2573 return dataloader;
2574}
2575
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002576bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2577 return (params().packageName == Constants::systemPackage);
2578}
2579
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002580bool IncrementalService::DataLoaderStub::requestCreate() {
2581 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2582}
2583
2584bool IncrementalService::DataLoaderStub::requestStart() {
2585 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2586}
2587
2588bool IncrementalService::DataLoaderStub::requestDestroy() {
2589 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2590}
2591
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002592bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002593 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002594 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002595 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002596 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002597 return fsmStep();
2598}
2599
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002600void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002601 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002602 mTargetStatus = status;
2603 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002604 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002605 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002606}
2607
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002608std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002609 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002610
2611 const auto now = mService.mClock->now();
2612 const bool healthy = (mPreviousBindDelay == 0ms);
2613
2614 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2615 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2616 LOG(INFO) << "Binding still in progress. "
2617 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002618 : "Already unhealthy, don't do anything.")
2619 << " for storage " << mId;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002620 // Binding still in progress.
2621 if (!healthy) {
2622 // Already unhealthy, don't do anything.
2623 return {};
2624 }
2625 // The DL is healthy/freshly bound, ok to retry for a few times.
2626 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2627 // Still within grace period.
2628 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2629 // Retry interval passed, retrying.
2630 mCurrentStatusTs = now;
2631 mPreviousBindDelay = 0ms;
2632 return 0ms;
2633 }
2634 return {};
2635 }
2636 // fallthrough, mark as unhealthy, and retry with delay
2637 }
2638
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002639 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002640 mPreviousBindTs = now;
2641
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002642 const auto nonCrashingInterval =
2643 std::max(castToMs(now - previousBindTs - mPreviousBindDelay), 100ms);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002644 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2645 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2646 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002647 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002648 }
2649
2650 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2651 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2652
2653 const auto bindDelayMs =
2654 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2655 maxBindDelayMs)
2656 .count();
2657 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -07002658 // rand() is enough, not worth maintaining a full-blown <rand> object for delay jitter
2659 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - // NOLINT
2660 bindDelayJitterRangeMs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002661 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002662 return mPreviousBindDelay;
2663}
2664
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002665bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002666 const auto maybeBindDelay = needToBind();
2667 if (!maybeBindDelay) {
2668 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2669 return true;
2670 }
2671 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002672 if (bindDelay > 1s) {
2673 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002674 << bindDelay.count() / 1000 << "s"
2675 << " for storage " << mId;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002676 }
2677
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002678 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002679 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2680 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002681 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002682 const bool healthy = (bindDelay == 0ms);
2683 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2684 << (healthy ? ", retrying." : "");
2685
2686 // Internal error, retry for healthy/new DLs.
2687 // Let needToBind migrate it to unhealthy after too many retries.
2688 if (healthy) {
2689 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2690 [this]() { fsmStep(); })) {
2691 // Mark as binding so that we know it's not the DL's fault.
2692 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2693 return true;
2694 }
2695 }
2696
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002697 return false;
2698 }
2699 return true;
2700}
2701
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002702bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002703 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002704 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002705 return false;
2706 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002707 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002708 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002709 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002710 return false;
2711 }
2712 return true;
2713}
2714
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002715bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002716 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002717 if (!dataloader) {
2718 return false;
2719 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002720 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002721 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002722 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002723 return false;
2724 }
2725 return true;
2726}
2727
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002728bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002729 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002730}
2731
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002732bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002733 if (!isValid()) {
2734 return false;
2735 }
2736
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002737 int currentStatus;
2738 int targetStatus;
2739 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002740 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002741 currentStatus = mCurrentStatus;
2742 targetStatus = mTargetStatus;
2743 }
2744
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002745 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002746
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002747 if (currentStatus == targetStatus) {
2748 return true;
2749 }
2750
2751 switch (targetStatus) {
2752 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002753 switch (currentStatus) {
2754 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2755 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2756 return true;
2757 default:
2758 return destroy();
2759 }
2760 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002761 }
2762 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2763 switch (currentStatus) {
2764 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2765 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2766 return start();
2767 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002768 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002769 }
2770 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2771 switch (currentStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002772 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002773 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2774 // Before binding need to make sure we are unbound.
2775 // Otherwise we'll get stuck binding.
2776 return destroy();
2777 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002778 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002779 return bind();
2780 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002781 return create();
2782 }
2783 break;
2784 default:
2785 LOG(ERROR) << "Invalid target status: " << targetStatus
2786 << ", current status: " << currentStatus;
2787 break;
2788 }
2789 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002790}
2791
2792binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002793 if (!isValid()) {
2794 return binder::Status::
2795 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2796 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002797 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002798 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2799 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002800 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2801 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002802 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2803 newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002804 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2805 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2806 [this, newStatus]() { setCurrentStatus(newStatus); });
2807 return binder::Status::ok();
2808 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002809
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002810 setCurrentStatus(newStatus);
2811 return binder::Status::ok();
2812}
2813
2814void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002815 int oldStatus, oldTargetStatus, newTargetStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002816 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002817 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002818 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002819 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002820 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002821 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002822
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002823 oldStatus = mCurrentStatus;
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002824 oldTargetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002825 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002826
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002827 // Change the status.
2828 mCurrentStatus = newStatus;
2829 mCurrentStatusTs = mService.mClock->now();
2830
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002831 switch (mCurrentStatus) {
2832 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2833 // Unavailable, retry.
2834 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2835 break;
2836 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2837 // Unrecoverable, just unbind.
2838 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2839 break;
2840 default:
2841 break;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002842 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002843
2844 newTargetStatus = mTargetStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002845 }
2846
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002847 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002848 << newStatus << " (target " << oldTargetStatus << " -> " << newTargetStatus << ")";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002849
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002850 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002851 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002852 }
2853
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002854 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002855
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002856 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002857}
2858
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002859bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2860 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2861 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002862}
2863
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002864void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002865 int healthStatus) {
2866 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2867 if (healthListener) {
2868 healthListener->onHealthStatus(id(), healthStatus);
2869 }
Songchun Fan9471be52021-04-21 17:49:27 -07002870 mHealthStatus = healthStatus;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002871}
2872
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002873void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2874 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002875
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002876 int healthStatusToReport = -1;
2877 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002878
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002879 {
2880 std::unique_lock lock(mMutex);
2881 unregisterFromPendingReads();
2882
2883 healthListener = mHealthListener;
2884
2885 // Healthcheck depends on timestamp of the oldest pending read.
2886 // 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 -07002887 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2888 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002889 const auto now = Clock::now();
2890 const auto kernelTsUs = getOldestPendingReadTs();
2891 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002892 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2893 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002894 mHealthBase = {now, kernelTsUs};
2895 }
2896
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002897 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2898 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002899 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2900 registerForPendingReads();
2901 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2902 lock.unlock();
2903 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002904 return;
2905 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002906
2907 resetHealthControl();
2908
2909 // Always make sure the data loader is started.
2910 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2911
2912 // Skip any further processing if health check params are invalid.
2913 if (!isHealthParamsValid()) {
2914 LOG(DEBUG) << id()
2915 << ": Skip any further processing if health check params are invalid.";
2916 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2917 lock.unlock();
2918 onHealthStatus(healthListener, healthStatusToReport);
2919 // Triggering data loader start. This is a one-time action.
2920 fsmStep();
2921 return;
2922 }
2923
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002924 // Don't schedule timer job less than 500ms in advance.
2925 static constexpr auto kTolerance = 500ms;
2926
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002927 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2928 const auto unhealthyTimeout =
2929 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2930 const auto unhealthyMonitoring =
2931 std::max(1000ms,
2932 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2933
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002934 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002935
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002936 Milliseconds checkBackAfter;
2937 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002938 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002939 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002940 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002941 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002942 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002943 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002944 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2945 } else {
2946 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002947 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002948 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2949 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002950 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002951 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002952 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2953 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002954 }
2955
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002956 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002957 if (healthStatusToReport != -1) {
2958 onHealthStatus(healthListener, healthStatusToReport);
2959 }
2960
2961 fsmStep();
2962}
2963
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002964Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2965 BootClockTsUs kernelTsUs) {
2966 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2967 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2968 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2969}
2970
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002971const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2972 if (mHealthPath.empty()) {
2973 resetHealthControl();
2974 return mHealthControl;
2975 }
2976 if (mHealthControl.pendingReads() < 0) {
2977 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2978 }
2979 if (mHealthControl.pendingReads() < 0) {
2980 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2981 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2982 << mHealthControl.logs() << ")";
2983 }
2984 return mHealthControl;
2985}
2986
2987void IncrementalService::DataLoaderStub::resetHealthControl() {
2988 mHealthControl = {};
2989}
2990
2991BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2992 auto result = kMaxBootClockTsUs;
2993
2994 const auto& control = initializeHealthControl();
2995 if (control.pendingReads() < 0) {
2996 return result;
2997 }
2998
Songchun Fan6944f1e2020-11-06 15:24:24 -08002999 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003000 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08003001 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003002 // Clear previous pending reads
3003 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003004 return result;
3005 }
3006
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07003007 LOG(DEBUG) << id() << ": pendingReads: fd(" << control.pendingReads() << "), count("
3008 << mLastPendingReads.size() << "), block: " << mLastPendingReads.front().block
3009 << ", time: " << mLastPendingReads.front().bootClockTsUs
3010 << ", uid: " << mLastPendingReads.front().uid;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003011
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003012 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003013}
3014
3015void IncrementalService::DataLoaderStub::registerForPendingReads() {
3016 const auto pendingReadsFd = mHealthControl.pendingReads();
3017 if (pendingReadsFd < 0) {
3018 return;
3019 }
3020
3021 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
3022
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003023 mService.mLooper->addFd(
3024 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
3025 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07003026 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003027 self->updateHealthStatus(/*baseline=*/true);
3028 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003029 },
3030 this);
3031 mService.mLooper->wake();
3032}
3033
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003034BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
3035 auto result = kMaxBootClockTsUs;
3036 for (auto&& pendingRead : mLastPendingReads) {
3037 result = std::min(result, pendingRead.bootClockTsUs);
3038 }
3039 return result;
3040}
3041
Songchun Fan9471be52021-04-21 17:49:27 -07003042void IncrementalService::DataLoaderStub::getMetrics(android::os::PersistableBundle* result) {
3043 const auto duration = elapsedMsSinceOldestPendingRead();
3044 if (duration >= 0) {
Songchun Fan0dc77722021-05-03 17:13:52 -07003045 const auto& kMetricsMillisSinceOldestPendingRead =
Songchun Fan9471be52021-04-21 17:49:27 -07003046 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
Songchun Fan0dc77722021-05-03 17:13:52 -07003047 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.c_str()), duration);
Songchun Fan9471be52021-04-21 17:49:27 -07003048 }
Songchun Fan0dc77722021-05-03 17:13:52 -07003049 const auto& kMetricsStorageHealthStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003050 os::incremental::BnIncrementalService::METRICS_STORAGE_HEALTH_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003051 result->putInt(String16(kMetricsStorageHealthStatusCode.c_str()), mHealthStatus);
3052 const auto& kMetricsDataLoaderStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003053 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003054 result->putInt(String16(kMetricsDataLoaderStatusCode.c_str()), mCurrentStatus);
3055 const auto& kMetricsMillisSinceLastDataLoaderBind =
Songchun Fan9471be52021-04-21 17:49:27 -07003056 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_DATA_LOADER_BIND();
Songchun Fan0dc77722021-05-03 17:13:52 -07003057 result->putLong(String16(kMetricsMillisSinceLastDataLoaderBind.c_str()),
3058 elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000);
3059 const auto& kMetricsDataLoaderBindDelayMillis =
Songchun Fan9471be52021-04-21 17:49:27 -07003060 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_BIND_DELAY_MILLIS();
Songchun Fan0dc77722021-05-03 17:13:52 -07003061 result->putLong(String16(kMetricsDataLoaderBindDelayMillis.c_str()),
3062 mPreviousBindDelay.count());
Songchun Fan9471be52021-04-21 17:49:27 -07003063}
3064
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003065long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
3066 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
3067 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
3068 return 0;
3069 }
3070 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
3071}
3072
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07003073void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003074 const auto pendingReadsFd = mHealthControl.pendingReads();
3075 if (pendingReadsFd < 0) {
3076 return;
3077 }
3078
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003079 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
3080
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003081 mService.mLooper->removeFd(pendingReadsFd);
3082 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003083}
3084
Songchun Fan2570ec02020-10-08 17:22:33 -07003085void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003086 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07003087 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003088 mHealthCheckParams = healthCheckParams;
3089 mHealthListener = std::move(healthListener);
3090 if (!mHealthListener) {
3091 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07003092 }
3093}
3094
Songchun Fan6944f1e2020-11-06 15:24:24 -08003095static std::string toHexString(const RawMetadata& metadata) {
3096 int n = metadata.size();
3097 std::string res(n * 2, '\0');
3098 // Same as incfs::toString(fileId)
3099 static constexpr char kHexChar[] = "0123456789abcdef";
3100 for (int i = 0; i < n; ++i) {
3101 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
3102 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
3103 }
3104 return res;
3105}
3106
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003107void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003108 dprintf(fd, " dataLoader: {\n");
3109 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08003110 dprintf(fd, " currentStatusTs: %lldmcs\n",
3111 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003112 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
3113 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003114 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003115 dprintf(fd, " health: {\n");
3116 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3117 dprintf(fd, " base: %lldmcs (%lld)\n",
3118 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3119 (long long)mHealthBase.kernelTsUs);
3120 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3121 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3122 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3123 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003124 dprintf(fd, " lastPendingReads: \n");
3125 const auto control = mService.mIncFs->openMount(mHealthPath);
3126 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003127 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003128 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3129 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3130 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3131 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3132 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003133 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
Songchun Fan9471be52021-04-21 17:49:27 -07003134 (long long)(elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000000),
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003135 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003136 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003137 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003138 dprintf(fd, " dataLoaderParams: {\n");
3139 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3140 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3141 dprintf(fd, " className: %s\n", params.className.c_str());
3142 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3143 dprintf(fd, " }\n");
3144 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003145}
3146
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003147void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3148 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003149}
3150
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003151binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3152 bool enableReadLogs, int32_t* _aidl_return) {
3153 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3154 return binder::Status::ok();
3155}
3156
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003157FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3158 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3159}
3160
Songchun Fan3c82a302019-11-29 14:23:45 -08003161} // namespace android::incremental