blob: 51b270c42bdee792443d49fc6cc507313d4ea7f5 [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);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700986 auto status = mVold->setIncFsMountOptions(control, enableReadLogs, enableReadTimeouts);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800987 if (status.isOk()) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700988 // Store states.
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800989 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700990 ifs.setReadTimeoutsEnabled(enableReadTimeouts);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700991 } else {
992 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800993 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700994 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700995}
996
Songchun Fan3c82a302019-11-29 14:23:45 -0800997void IncrementalService::deleteStorage(StorageId storageId) {
998 const auto ifs = getIfs(storageId);
999 if (!ifs) {
1000 return;
1001 }
1002 deleteStorage(*ifs);
1003}
1004
1005void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
1006 std::unique_lock l(ifs.lock);
1007 deleteStorageLocked(ifs, std::move(l));
1008}
1009
1010void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
1011 std::unique_lock<std::mutex>&& ifsLock) {
1012 const auto storages = std::move(ifs.storages);
1013 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
1014 const auto bindPoints = ifs.bindPoints;
1015 ifsLock.unlock();
1016
1017 std::lock_guard l(mLock);
1018 for (auto&& [id, _] : storages) {
1019 if (id != ifs.mountId) {
1020 mMounts.erase(id);
1021 }
1022 }
1023 for (auto&& [path, _] : bindPoints) {
1024 mBindsByPath.erase(path);
1025 }
1026 mMounts.erase(ifs.mountId);
1027}
1028
1029StorageId IncrementalService::openStorage(std::string_view pathInMount) {
1030 if (!path::isAbsolute(pathInMount)) {
1031 return kInvalidStorageId;
1032 }
1033
1034 return findStorageId(path::normalize(pathInMount));
1035}
1036
Songchun Fan3c82a302019-11-29 14:23:45 -08001037IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
1038 std::lock_guard l(mLock);
1039 return getIfsLocked(storage);
1040}
1041
1042const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
1043 auto it = mMounts.find(storage);
1044 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001045 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -07001046 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -08001047 }
1048 return it->second;
1049}
1050
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001051int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
1052 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001053 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001054 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001055 return -EINVAL;
1056 }
1057
1058 const auto ifs = getIfs(storage);
1059 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001060 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001061 return -EINVAL;
1062 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001063
Songchun Fan3c82a302019-11-29 14:23:45 -08001064 std::unique_lock l(ifs->lock);
1065 const auto storageInfo = ifs->storages.find(storage);
1066 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001067 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -08001068 return -EINVAL;
1069 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001070 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001071 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001072 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001073 return -EINVAL;
1074 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001075 l.unlock();
1076 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001077 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
1078 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -08001079}
1080
1081int IncrementalService::unbind(StorageId storage, std::string_view target) {
1082 if (!path::isAbsolute(target)) {
1083 return -EINVAL;
1084 }
1085
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001086 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001087
1088 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
1089 // otherwise there's a chance to unmount something completely unrelated
1090 const auto norm = path::normalize(target);
1091 std::unique_lock l(mLock);
1092 const auto storageIt = mBindsByPath.find(norm);
1093 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
1094 return -EINVAL;
1095 }
1096 const auto bindIt = storageIt->second;
1097 const auto storageId = bindIt->second.storage;
1098 const auto ifs = getIfsLocked(storageId);
1099 if (!ifs) {
1100 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
1101 << " is missing";
1102 return -EFAULT;
1103 }
1104 mBindsByPath.erase(storageIt);
1105 l.unlock();
1106
1107 mVold->unmountIncFs(bindIt->first);
1108 std::unique_lock l2(ifs->lock);
1109 if (ifs->bindPoints.size() <= 1) {
1110 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -07001111 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001112 } else {
1113 const std::string savedFile = std::move(bindIt->second.savedFilename);
1114 ifs->bindPoints.erase(bindIt);
1115 l2.unlock();
1116 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001117 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001118 }
1119 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001120
Songchun Fan3c82a302019-11-29 14:23:45 -08001121 return 0;
1122}
1123
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001124std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001125 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001126 std::string_view path) const {
1127 if (!path::isAbsolute(path)) {
1128 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001129 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001130 auto normPath = path::normalize(path);
1131 if (path::startsWith(normPath, storageIt->second.name)) {
1132 return normPath;
1133 }
1134 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001135 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1136 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001137 return {};
1138 }
1139 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001140}
1141
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001142std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001143 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001144 std::unique_lock l(ifs.lock);
1145 const auto storageInfo = ifs.storages.find(storage);
1146 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001147 return {};
1148 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001149 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001150}
1151
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001152int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001153 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001154 const auto ifs = getIfs(storage);
1155 if (!ifs) {
1156 return -EINVAL;
1157 }
1158 if (data.size() > params.size) {
1159 LOG(ERROR) << "Bad data size - bigger than file size";
1160 return -EINVAL;
1161 }
1162 if (!data.empty() && data.size() != params.size) {
1163 // Writing a page is an irreversible operation, and it can't be updated with additional
1164 // data later. Check that the last written page is complete, or we may break the file.
1165 if (!isPageAligned(data.size())) {
1166 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001167 return -EINVAL;
1168 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001169 }
1170 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1171 if (normPath.empty()) {
1172 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1173 return -EINVAL;
1174 }
1175 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1176 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1177 return err;
1178 }
1179 if (params.size > 0) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001180 if (auto err = mIncFs->reserveSpace(ifs->control, id, params.size)) {
1181 if (err != -EOPNOTSUPP) {
1182 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1183 (void)mIncFs->unlink(ifs->control, normPath);
1184 return err;
1185 } else {
1186 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1187 "may run out of disk later";
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001188 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001189 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001190 if (!data.empty()) {
1191 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001192 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001193 return err;
1194 }
1195 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001196 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001197 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001198}
1199
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001200int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001201 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001202 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001203 if (normPath.empty()) {
1204 return -EINVAL;
1205 }
1206 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001207 }
1208 return -EINVAL;
1209}
1210
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001211int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001212 const auto ifs = getIfs(storageId);
1213 if (!ifs) {
1214 return -EINVAL;
1215 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001216 return makeDirs(*ifs, storageId, path, mode);
1217}
1218
1219int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1220 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001221 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1222 if (normPath.empty()) {
1223 return -EINVAL;
1224 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001225 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001226}
1227
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001228int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1229 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001230 std::unique_lock l(mLock);
1231 auto ifsSrc = getIfsLocked(sourceStorageId);
1232 if (!ifsSrc) {
1233 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001234 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001235 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1236 return -EINVAL;
1237 }
1238 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001239 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1240 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001241 if (normOldPath.empty() || normNewPath.empty()) {
1242 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1243 return -EINVAL;
1244 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001245 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1246 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1247 << " to " << newPath << "[" << normNewPath << "]";
1248 return err;
1249 }
1250 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001251}
1252
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001253int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001254 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001255 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001256 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001257 }
1258 return -EINVAL;
1259}
1260
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001261int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1262 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001263 std::string&& target, BindKind kind,
1264 std::unique_lock<std::mutex>& mainLock) {
1265 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001266 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001267 return -EINVAL;
1268 }
1269
1270 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001271 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001272 if (kind != BindKind::Temporary) {
1273 metadata::BindPoint bp;
1274 bp.set_storage_id(storage);
1275 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001276 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001277 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001278 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001279 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001280 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001281 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1282 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1283 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001284 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001285 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001286 return int(node);
1287 }
1288 }
1289
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001290 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1291 std::move(target), kind, mainLock);
1292 if (res) {
1293 mIncFs->unlink(ifs.control, metadataFullPath);
1294 }
1295 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001296}
1297
1298int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001299 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001300 std::string&& target, BindKind kind,
1301 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001302 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001303 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001304 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001305 if (!status.isOk()) {
1306 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1307 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1308 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1309 : status.serviceSpecificErrorCode() == 0
1310 ? -EFAULT
1311 : status.serviceSpecificErrorCode()
1312 : -EIO;
1313 }
1314 }
1315
1316 if (!mainLock.owns_lock()) {
1317 mainLock.lock();
1318 }
1319 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001320 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1321 std::move(target), kind);
1322 return 0;
1323}
1324
1325void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1326 std::string&& metadataName, std::string&& source,
1327 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001328 const auto [it, _] =
1329 ifs.bindPoints.insert_or_assign(target,
1330 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001331 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001332 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001333}
1334
1335RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1336 const auto ifs = getIfs(storage);
1337 if (!ifs) {
1338 return {};
1339 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001340 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001341 if (normPath.empty()) {
1342 return {};
1343 }
1344 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001345}
1346
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001347RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001348 const auto ifs = getIfs(storage);
1349 if (!ifs) {
1350 return {};
1351 }
1352 return mIncFs->getMetadata(ifs->control, node);
1353}
1354
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001355void IncrementalService::setUidReadTimeouts(StorageId storage,
1356 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001357 using microseconds = std::chrono::microseconds;
1358 using milliseconds = std::chrono::milliseconds;
1359
1360 auto maxPendingTimeUs = microseconds(0);
1361 for (const auto& timeouts : perUidReadTimeouts) {
1362 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1363 }
1364 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07001365 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001366 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1367 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001368 return;
1369 }
1370
1371 const auto ifs = getIfs(storage);
1372 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001373 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001374 return;
1375 }
1376
1377 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1378 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1379 return;
1380 }
1381
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001382 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1383 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1384 if (checkUidReadTimeouts(storageId, state, timeout)) {
1385 return true;
1386 }
1387 clearUidReadTimeouts(storageId);
1388 return false;
1389 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001390}
1391
1392void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1393 const auto ifs = getIfs(storage);
1394 if (!ifs) {
1395 return;
1396 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001397 mIncFs->setUidReadTimeouts(ifs->control, {});
1398}
1399
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001400bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1401 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001402 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001403 // Reached maximum timeout.
1404 return false;
1405 }
1406 if (state.error) {
1407 // Something is wrong, abort.
1408 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001409 }
1410
1411 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001412 if (state.fullyLoaded && !state.readLogsEnabled) {
1413 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001414 }
1415
1416 const auto timeLeft = timeLimit - Clock::now();
1417 if (timeLeft < Constants::progressUpdateInterval) {
1418 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001419 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001420 }
1421
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001422 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001423}
1424
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001425std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1426 std::unordered_set<std::string_view> mountedRootNames;
1427 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1428 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1429 for (auto [source, target] : binds) {
1430 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1431 LOG(INFO) << " " << path::join(root, source);
1432 }
1433
1434 // Ensure it's a kind of a mount that's managed by IncrementalService
1435 if (path::basename(root) != constants().mount ||
1436 path::basename(backingDir) != constants().backing) {
1437 return;
1438 }
1439 const auto expectedRoot = path::dirname(root);
1440 if (path::dirname(backingDir) != expectedRoot) {
1441 return;
1442 }
1443 if (path::dirname(expectedRoot) != mIncrementalDir) {
1444 return;
1445 }
1446 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1447 return;
1448 }
1449
1450 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1451
1452 // make sure we clean up the mount if it happens to be a bad one.
1453 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1454 auto cleanupFiles = makeCleanup([&]() {
1455 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1456 IncFsMount::cleanupFilesystem(expectedRoot);
1457 });
1458 auto cleanupMounts = makeCleanup([&]() {
1459 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1460 for (auto&& [_, target] : binds) {
1461 mVold->unmountIncFs(std::string(target));
1462 }
1463 mVold->unmountIncFs(std::string(root));
1464 });
1465
1466 auto control = mIncFs->openMount(root);
1467 if (!control) {
1468 LOG(INFO) << "failed to open mount " << root;
1469 return;
1470 }
1471
1472 auto mountRecord =
1473 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1474 path::join(root, constants().infoMdName));
1475 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1476 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1477 return;
1478 }
1479
1480 auto mountId = mountRecord.storage().id();
1481 mNextId = std::max(mNextId, mountId + 1);
1482
1483 DataLoaderParamsParcel dataLoaderParams;
1484 {
1485 const auto& loader = mountRecord.loader();
1486 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1487 dataLoaderParams.packageName = loader.package_name();
1488 dataLoaderParams.className = loader.class_name();
1489 dataLoaderParams.arguments = loader.arguments();
1490 }
1491
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001492 // Not way to obtain a real sysfs key at this point - metrics will stop working after "soft"
1493 // reboot.
1494 std::string metricsKey{};
1495 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), std::move(metricsKey),
1496 mountId, std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001497 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001498
Alex Buynytskyy04035452020-06-06 20:15:58 -07001499 // Check if marker file present.
1500 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001501 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001502 }
1503
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001504 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1505 auto d = openDir(root);
1506 while (auto e = ::readdir(d.get())) {
1507 if (e->d_type == DT_REG) {
1508 auto name = std::string_view(e->d_name);
1509 if (name.starts_with(constants().mountpointMdPrefix)) {
1510 permanentBindPoints
1511 .emplace_back(name,
1512 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1513 ifs->control,
1514 path::join(root,
1515 name)));
1516 if (permanentBindPoints.back().second.dest_path().empty() ||
1517 permanentBindPoints.back().second.source_subdir().empty()) {
1518 permanentBindPoints.pop_back();
1519 mIncFs->unlink(ifs->control, path::join(root, name));
1520 } else {
1521 LOG(INFO) << "Permanent bind record: '"
1522 << permanentBindPoints.back().second.source_subdir() << "'->'"
1523 << permanentBindPoints.back().second.dest_path() << "'";
1524 }
1525 }
1526 } else if (e->d_type == DT_DIR) {
1527 if (e->d_name == "."sv || e->d_name == ".."sv) {
1528 continue;
1529 }
1530 auto name = std::string_view(e->d_name);
1531 if (name.starts_with(constants().storagePrefix)) {
1532 int storageId;
1533 const auto res =
1534 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1535 name.data() + name.size(), storageId);
1536 if (res.ec != std::errc{} || *res.ptr != '_') {
1537 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1538 << "' for mount " << expectedRoot;
1539 continue;
1540 }
1541 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1542 if (!inserted) {
1543 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1544 << " for mount " << expectedRoot;
1545 continue;
1546 }
1547 ifs->storages.insert_or_assign(storageId,
1548 IncFsMount::Storage{path::join(root, name)});
1549 mNextId = std::max(mNextId, storageId + 1);
1550 }
1551 }
1552 }
1553
1554 if (ifs->storages.empty()) {
1555 LOG(WARNING) << "No valid storages in mount " << root;
1556 return;
1557 }
1558
1559 // now match the mounted directories with what we expect to have in the metadata
1560 {
1561 std::unique_lock l(mLock, std::defer_lock);
1562 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1563 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1564 [&, bindRecord = bindRecord](auto&& bind) {
1565 return bind.second == bindRecord.dest_path() &&
1566 path::join(root, bind.first) ==
1567 bindRecord.source_subdir();
1568 });
1569 if (mountedIt != binds.end()) {
1570 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1571 << " to mount " << mountedIt->first;
1572 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1573 std::move(*bindRecord.mutable_source_subdir()),
1574 std::move(*bindRecord.mutable_dest_path()),
1575 BindKind::Permanent);
1576 if (mountedIt != binds.end() - 1) {
1577 std::iter_swap(mountedIt, binds.end() - 1);
1578 }
1579 binds = binds.first(binds.size() - 1);
1580 } else {
1581 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1582 << ", mounting";
1583 // doesn't exist - try mounting back
1584 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1585 std::move(*bindRecord.mutable_source_subdir()),
1586 std::move(*bindRecord.mutable_dest_path()),
1587 BindKind::Permanent, l)) {
1588 mIncFs->unlink(ifs->control, metadataFile);
1589 }
1590 }
1591 }
1592 }
1593
1594 // if anything stays in |binds| those are probably temporary binds; system restarted since
1595 // they were mounted - so let's unmount them all.
1596 for (auto&& [source, target] : binds) {
1597 if (source.empty()) {
1598 continue;
1599 }
1600 mVold->unmountIncFs(std::string(target));
1601 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001602 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001603
1604 if (ifs->bindPoints.empty()) {
1605 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1606 deleteStorage(*ifs);
1607 return;
1608 }
1609
1610 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1611 CHECK(ifs->dataLoaderStub);
1612
1613 mountedRootNames.insert(path::basename(ifs->root));
1614
1615 // not locking here at all: we're still in the constructor, no other calls can happen
1616 mMounts[ifs->mountId] = std::move(ifs);
1617 });
1618
1619 return mountedRootNames;
1620}
1621
1622void IncrementalService::mountExistingImages(
1623 const std::unordered_set<std::string_view>& mountedRootNames) {
1624 auto dir = openDir(mIncrementalDir);
1625 if (!dir) {
1626 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1627 return;
1628 }
1629 while (auto entry = ::readdir(dir.get())) {
1630 if (entry->d_type != DT_DIR) {
1631 continue;
1632 }
1633 std::string_view name = entry->d_name;
1634 if (!name.starts_with(constants().mountKeyPrefix)) {
1635 continue;
1636 }
1637 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001638 continue;
1639 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001640 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001641 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001642 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001643 }
1644 }
1645}
1646
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001647bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001648 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001649 const auto backing = path::join(root, constants().backing);
Songchun Fanf949c372021-04-27 11:26:25 -07001650 std::string mountKey(path::basename(path::dirname(mountTarget)));
Songchun Fan3c82a302019-11-29 14:23:45 -08001651
Songchun Fan3c82a302019-11-29 14:23:45 -08001652 IncrementalFileSystemControlParcel controlParcel;
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001653 auto metricsKey = makeUniqueName(mountKey);
1654 auto status = mVold->mountIncFs(backing, mountTarget, 0, metricsKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001655 if (!status.isOk()) {
1656 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1657 return false;
1658 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001659
1660 int cmd = controlParcel.cmd.release().release();
1661 int pendingReads = controlParcel.pendingReads.release().release();
1662 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001663 int blocksWritten =
1664 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1665 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001666
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001667 auto ifs = std::make_shared<IncFsMount>(std::string(root), std::move(metricsKey), -1,
1668 std::move(control), *this);
Songchun Fan3c82a302019-11-29 14:23:45 -08001669
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001670 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1671 path::join(mountTarget, constants().infoMdName));
1672 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001673 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1674 return false;
1675 }
1676
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001677 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001678 mNextId = std::max(mNextId, ifs->mountId + 1);
1679
Alex Buynytskyy04035452020-06-06 20:15:58 -07001680 // Check if marker file present.
1681 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001682 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001683 }
1684
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001685 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001686 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001687 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001688 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001689 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001690 dataLoaderParams.packageName = loader.package_name();
1691 dataLoaderParams.className = loader.class_name();
1692 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001693 }
1694
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001695 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001696 CHECK(ifs->dataLoaderStub);
1697
Songchun Fan3c82a302019-11-29 14:23:45 -08001698 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001699 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001700 while (auto e = ::readdir(d.get())) {
1701 if (e->d_type == DT_REG) {
1702 auto name = std::string_view(e->d_name);
1703 if (name.starts_with(constants().mountpointMdPrefix)) {
1704 bindPoints.emplace_back(name,
1705 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1706 ifs->control,
1707 path::join(mountTarget,
1708 name)));
1709 if (bindPoints.back().second.dest_path().empty() ||
1710 bindPoints.back().second.source_subdir().empty()) {
1711 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001712 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001713 }
1714 }
1715 } else if (e->d_type == DT_DIR) {
1716 if (e->d_name == "."sv || e->d_name == ".."sv) {
1717 continue;
1718 }
1719 auto name = std::string_view(e->d_name);
1720 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001721 int storageId;
1722 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1723 name.data() + name.size(), storageId);
1724 if (res.ec != std::errc{} || *res.ptr != '_') {
1725 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1726 << root;
1727 continue;
1728 }
1729 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001730 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001731 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001732 << " for mount " << root;
1733 continue;
1734 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001735 ifs->storages.insert_or_assign(storageId,
1736 IncFsMount::Storage{
1737 path::join(root, constants().mount, name)});
1738 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001739 }
1740 }
1741 }
1742
1743 if (ifs->storages.empty()) {
1744 LOG(WARNING) << "No valid storages in mount " << root;
1745 return false;
1746 }
1747
1748 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001749 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001750 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001751 for (auto&& bp : bindPoints) {
1752 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1753 std::move(*bp.second.mutable_source_subdir()),
1754 std::move(*bp.second.mutable_dest_path()),
1755 BindKind::Permanent, l);
1756 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001757 }
1758
1759 if (bindCount == 0) {
1760 LOG(WARNING) << "No valid bind points for mount " << root;
1761 deleteStorage(*ifs);
1762 return false;
1763 }
1764
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001765 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001766 mMounts[ifs->mountId] = std::move(ifs);
1767 return true;
1768}
1769
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001770void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001771 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001772 while (mRunning.load(std::memory_order_relaxed)) {
1773 mLooper->pollAll(kTimeoutMsecs);
1774 }
1775}
1776
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001777void IncrementalService::trimReservedSpaceV1(const IncFsMount& ifs) {
1778 mIncFs->forEachFile(ifs.control, [this](auto&& control, auto&& fileId) {
1779 if (mIncFs->isFileFullyLoaded(control, fileId) == incfs::LoadingState::Full) {
1780 mIncFs->reserveSpace(control, fileId, -1);
1781 }
1782 return true;
1783 });
1784}
1785
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001786void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001787 DataLoaderStatusListener&& statusListener,
1788 const StorageHealthCheckParams& healthCheckParams,
1789 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001790 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001791 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001792 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1793 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1794 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001795 if (ifs.control.blocksWritten() >= 0) {
1796 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1797 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001798 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001799
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001800 ifs.dataLoaderStub =
1801 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001802 std::move(statusListener), healthCheckParams,
1803 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001804
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001805 // pre-v2 IncFS doesn't do automatic reserved space trimming - need to run it manually
1806 if (!(mIncFs->features() & incfs::Features::v2)) {
1807 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1808 if (!state.fullyLoaded) {
1809 return true;
1810 }
1811
1812 const auto ifs = getIfs(storageId);
1813 if (!ifs) {
1814 return false;
1815 }
1816 trimReservedSpaceV1(*ifs);
1817 return false;
1818 });
1819 }
1820
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001821 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1822 if (!state.fullyLoaded || state.readLogsEnabled) {
1823 return true;
1824 }
1825
1826 DataLoaderStubPtr dataLoaderStub;
1827 {
1828 const auto ifs = getIfs(storageId);
1829 if (!ifs) {
1830 return false;
1831 }
1832
1833 std::unique_lock l(ifs->lock);
1834 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1835 }
1836
1837 if (dataLoaderStub) {
1838 dataLoaderStub->cleanupResources();
1839 }
1840
1841 return false;
1842 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001843}
1844
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001845template <class Duration>
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001846static constexpr auto castToMs(Duration d) {
1847 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1848}
1849
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001850// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001851// Lib files should be placed next to the APK file in the following matter:
1852// Example:
1853// /path/to/base.apk
1854// /path/to/lib/arm/first.so
1855// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001856bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1857 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001858 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001859 auto start = Clock::now();
1860
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001861 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001862 if (!ifs) {
1863 LOG(ERROR) << "Invalid storage " << storage;
1864 return false;
1865 }
1866
Songchun Fanc8975312020-07-13 12:14:37 -07001867 const auto targetLibPathRelativeToStorage =
1868 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1869 libDirRelativePath);
1870
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001871 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001872 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1873 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001874 << " errno: " << res;
1875 return false;
1876 }
1877
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001878 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001879 ZipArchiveHandle zipFileHandle;
1880 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001881 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1882 return false;
1883 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001884
1885 // Need a shared pointer: will be passing it into all unpacking jobs.
1886 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001887 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001888 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001889 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001890 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1891 return false;
1892 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001893 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001894 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1895
1896 auto openZipTs = Clock::now();
1897
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001898 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1899 incfs::FileId sourceId;
1900 if (mapFiles) {
1901 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1902 if (!incfs::isValidFileId(sourceId)) {
1903 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1904 << "', mapping disabled";
1905 mapFiles = false;
1906 }
1907 }
1908
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001909 std::vector<Job> jobQueue;
1910 ZipEntry entry;
1911 std::string_view fileName;
1912 while (!Next(cookie, &entry, &fileName)) {
1913 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001914 continue;
1915 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001916
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001917 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001918 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001919
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001920 if (!extractNativeLibs) {
1921 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001922 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001923 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1924 return false;
1925 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001926 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001927 LOG(WARNING) << "Library " << fileName
1928 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1929 << entry.offset;
1930 return false;
1931 }
1932 continue;
1933 }
1934
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001935 auto startFileTs = Clock::now();
1936
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001937 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001938 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001939 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001940 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001941 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001942 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001943 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1944 << "; skipping extraction, spent "
1945 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1946 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001947 continue;
1948 }
1949
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001950 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1951 incfs::NewMappedFileParams mappedFileParams = {
1952 .sourceId = sourceId,
1953 .sourceOffset = entry.offset,
1954 .size = entry.uncompressed_length,
1955 };
1956
1957 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1958 mappedFileParams);
1959 res == 0) {
1960 if (perfLoggingEnabled()) {
1961 auto doneTs = Clock::now();
1962 LOG(INFO) << "incfs: Mapped " << libName << ": "
1963 << elapsedMcs(startFileTs, doneTs) << "mcs";
1964 }
1965 continue;
1966 } else {
1967 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1968 << "; falling back to full extraction";
1969 }
1970 }
1971
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001972 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001973 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001974 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001975 .signature = {},
1976 // Metadata of the new lib file is its relative path
1977 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1978 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001979 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001980 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001981 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001982 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001983 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001984 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001985 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001986
1987 auto makeFileTs = Clock::now();
1988
Songchun Fanafaf6e92020-03-18 14:12:20 -07001989 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001990 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001991 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001992 LOG(INFO) << "incfs: Extracted " << libName
1993 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001994 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001995 continue;
1996 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001997
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001998 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1999 libFileId, libPath = std::move(targetLibPath),
2000 makeFileTs]() mutable {
2001 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002002 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002003
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002004 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002005 auto prepareJobTs = Clock::now();
2006 LOG(INFO) << "incfs: Processed " << libName << ": "
2007 << elapsedMcs(startFileTs, prepareJobTs)
2008 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
2009 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002010 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002011 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002012
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002013 auto processedTs = Clock::now();
2014
2015 if (!jobQueue.empty()) {
2016 {
2017 std::lock_guard lock(mJobMutex);
2018 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002019 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002020 if (existingJobs.empty()) {
2021 existingJobs = std::move(jobQueue);
2022 } else {
2023 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
2024 std::move_iterator(jobQueue.end()));
2025 }
2026 }
2027 }
2028 mJobCondition.notify_all();
2029 }
2030
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002031 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002032 auto end = Clock::now();
2033 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
2034 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
2035 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002036 << " make files: " << elapsedMcs(openZipTs, processedTs)
2037 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002038 }
2039
2040 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002041}
2042
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002043void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
2044 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002045 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002046 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002047 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002048 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002049 return;
2050 }
2051
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002052 auto startedTs = Clock::now();
2053
2054 // Write extracted data to new file
2055 // NOTE: don't zero-initialize memory, it may take a while for nothing
2056 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
2057 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002058 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002059 return;
2060 }
2061
2062 auto extractFileTs = Clock::now();
2063
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002064 if (setFileContent(ifs, libFileId, debugLibPath,
2065 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002066 return;
2067 }
2068
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002069 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002070 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002071 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
2072 << entry.compressed_length << " -> " << entry.uncompressed_length
2073 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002074 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
2075 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002076 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002077 }
2078}
2079
2080bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002081 struct WaitPrinter {
2082 const Clock::time_point startTs = Clock::now();
2083 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002084 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002085 const auto endTs = Clock::now();
2086 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
2087 << elapsedMcs(startTs, endTs) << "mcs";
2088 }
2089 }
2090 } waitPrinter;
2091
2092 MountId mount;
2093 {
2094 auto ifs = getIfs(storage);
2095 if (!ifs) {
2096 return true;
2097 }
2098 mount = ifs->mountId;
2099 }
2100
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002101 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002102 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002103 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002104 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002105 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002106 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002107}
2108
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002109int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
2110 std::string_view debugFilePath,
2111 std::span<const uint8_t> data) const {
2112 auto startTs = Clock::now();
2113
2114 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2115 if (!writeFd.ok()) {
2116 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2117 << " errno: " << writeFd.get();
2118 return writeFd.get();
2119 }
2120
2121 const auto dataLength = data.size();
2122
2123 auto openFileTs = Clock::now();
2124 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2125 std::vector<IncFsDataBlock> instructions(numBlocks);
2126 for (int i = 0; i < numBlocks; i++) {
2127 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2128 instructions[i] = IncFsDataBlock{
2129 .fileFd = writeFd.get(),
2130 .pageIndex = static_cast<IncFsBlockIndex>(i),
2131 .compression = INCFS_COMPRESSION_KIND_NONE,
2132 .kind = INCFS_BLOCK_KIND_DATA,
2133 .dataSize = static_cast<uint32_t>(blockSize),
2134 .data = reinterpret_cast<const char*>(data.data()),
2135 };
2136 data = data.subspan(blockSize);
2137 }
2138 auto prepareInstsTs = Clock::now();
2139
2140 size_t res = mIncFs->writeBlocks(instructions);
2141 if (res != instructions.size()) {
2142 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2143 return res;
2144 }
2145
2146 if (perfLoggingEnabled()) {
2147 auto endTs = Clock::now();
2148 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2149 << " bytes): " << elapsedMcs(startTs, endTs)
2150 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2151 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2152 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2153 }
2154
2155 return 0;
2156}
2157
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002158incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2159 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002160 std::unique_lock l(mLock);
2161 const auto ifs = getIfsLocked(storage);
2162 if (!ifs) {
2163 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002164 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002165 }
2166 const auto storageInfo = ifs->storages.find(storage);
2167 if (storageInfo == ifs->storages.end()) {
2168 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002169 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002170 }
2171 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002172 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002173}
2174
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002175incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2176 const auto ifs = getIfs(storage);
2177 if (!ifs) {
2178 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2179 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002180 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002181 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002182}
2183
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002184IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002185 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002186 std::unique_lock l(mLock);
2187 const auto ifs = getIfsLocked(storage);
2188 if (!ifs) {
2189 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002190 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002191 }
2192 const auto storageInfo = ifs->storages.find(storage);
2193 if (storageInfo == ifs->storages.end()) {
2194 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002195 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002196 }
2197 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002198 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002199}
2200
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002201IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002202 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002203 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2204 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002205 const auto [filledBlocksCount, totalBlocksCount] =
2206 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002207 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2208 filledBlocksCount == -ENOENT) {
2209 // a kind of a file that's not really being loaded, e.g. a mapped range
2210 // an older IncFS used to return ENOENT in this case, so handle it the same way
2211 return true;
2212 }
Songchun Fan374f7652020-08-20 08:40:29 -07002213 if (filledBlocksCount < 0) {
2214 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002215 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002216 error = filledBlocksCount;
2217 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002218 }
2219 totalBlocks += totalBlocksCount;
2220 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002221 return true;
2222 });
Songchun Fan374f7652020-08-20 08:40:29 -07002223
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002224 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002225}
2226
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002227bool IncrementalService::updateLoadingProgress(StorageId storage,
2228 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002229 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002230 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002231 // Failed to get progress from incfs, abort.
2232 return false;
2233 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002234 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2235 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002236 // Stop updating progress once it is fully loaded
2237 return true;
2238 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002239 addTimedJob(*mProgressUpdateJobQueue, storage,
2240 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002241 [storage, progressListener = std::move(progressListener), this]() mutable {
2242 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002243 });
2244 return true;
2245}
2246
2247bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002248 StorageId storage, StorageLoadingProgressListener progressListener) {
2249 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002250}
2251
2252bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2253 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2254}
2255
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002256bool IncrementalService::perfLoggingEnabled() {
2257 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2258 return enabled;
2259}
2260
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002261void IncrementalService::runJobProcessing() {
2262 for (;;) {
2263 std::unique_lock lock(mJobMutex);
2264 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2265 if (!mRunning) {
2266 return;
2267 }
2268
2269 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002270 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002271 auto queue = std::move(it->second);
2272 mJobQueue.erase(it);
2273 lock.unlock();
2274
2275 for (auto&& job : queue) {
2276 job();
2277 }
2278
2279 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002280 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002281 lock.unlock();
2282 mJobCondition.notify_all();
2283 }
2284}
2285
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002286void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002287 sp<IAppOpsCallback> listener;
2288 {
2289 std::unique_lock lock{mCallbacksLock};
2290 auto& cb = mCallbackRegistered[packageName];
2291 if (cb) {
2292 return;
2293 }
2294 cb = new AppOpsListener(*this, packageName);
2295 listener = cb;
2296 }
2297
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002298 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2299 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002300}
2301
2302bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2303 sp<IAppOpsCallback> listener;
2304 {
2305 std::unique_lock lock{mCallbacksLock};
2306 auto found = mCallbackRegistered.find(packageName);
2307 if (found == mCallbackRegistered.end()) {
2308 return false;
2309 }
2310 listener = found->second;
2311 mCallbackRegistered.erase(found);
2312 }
2313
2314 mAppOpsManager->stopWatchingMode(listener);
2315 return true;
2316}
2317
2318void IncrementalService::onAppOpChanged(const std::string& packageName) {
2319 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002320 return;
2321 }
2322
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002323 std::vector<IfsMountPtr> affected;
2324 {
2325 std::lock_guard l(mLock);
2326 affected.reserve(mMounts.size());
2327 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002328 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002329 if (ifs->mountId == id && ifs->dataLoaderStub &&
2330 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002331 affected.push_back(ifs);
2332 }
2333 }
2334 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002335 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002336 std::unique_lock ll(ifs->lock);
2337 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002338 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002339}
2340
Songchun Fana7098592020-09-03 11:45:53 -07002341bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2342 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002343 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002344 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002345 }
Songchun Fana7098592020-09-03 11:45:53 -07002346 timedQueue.addJob(id, after, std::move(what));
2347 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002348}
2349
Songchun Fana7098592020-09-03 11:45:53 -07002350bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002351 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002352 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002353 }
Songchun Fana7098592020-09-03 11:45:53 -07002354 timedQueue.removeJobs(id);
2355 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002356}
2357
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002358void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2359 bool wasEmpty;
2360 {
2361 std::lock_guard l(mIfsStateCallbacksLock);
2362 wasEmpty = mIfsStateCallbacks.empty();
2363 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2364 }
2365 if (wasEmpty) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002366 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002367 [this]() { processIfsStateCallbacks(); });
2368 }
2369}
2370
2371void IncrementalService::processIfsStateCallbacks() {
2372 StorageId storageId = kInvalidStorageId;
2373 std::vector<IfsStateCallback> local;
2374 while (true) {
2375 {
2376 std::lock_guard l(mIfsStateCallbacksLock);
2377 if (mIfsStateCallbacks.empty()) {
2378 return;
2379 }
2380 IfsStateCallbacks::iterator it;
2381 if (storageId == kInvalidStorageId) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002382 // First entry, initialize the |it|.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002383 it = mIfsStateCallbacks.begin();
2384 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002385 // Subsequent entries, update the |storageId|, and shift to the new one (not that
2386 // it guarantees much about updated items, but at least the loop will finish).
2387 it = mIfsStateCallbacks.lower_bound(storageId);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002388 if (it == mIfsStateCallbacks.end()) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002389 // Nothing else left, too bad.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002390 break;
2391 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002392 if (it->first != storageId) {
2393 local.clear(); // Was removed during processing, forget the old callbacks.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002394 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002395 // Put the 'surviving' callbacks back into the map and advance the position.
2396 auto& callbacks = it->second;
2397 if (callbacks.empty()) {
2398 std::swap(callbacks, local);
2399 } else {
2400 callbacks.insert(callbacks.end(), std::move_iterator(local.begin()),
2401 std::move_iterator(local.end()));
2402 local.clear();
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002403 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002404 if (callbacks.empty()) {
2405 it = mIfsStateCallbacks.erase(it);
2406 if (mIfsStateCallbacks.empty()) {
2407 return;
2408 }
2409 } else {
2410 ++it;
2411 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002412 }
2413 }
2414
2415 if (it == mIfsStateCallbacks.end()) {
2416 break;
2417 }
2418
2419 storageId = it->first;
2420 auto& callbacks = it->second;
2421 if (callbacks.empty()) {
2422 // Invalid case, one extra lookup should be ok.
2423 continue;
2424 }
2425 std::swap(callbacks, local);
2426 }
2427
2428 processIfsStateCallbacks(storageId, local);
2429 }
2430
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002431 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002432 [this]() { processIfsStateCallbacks(); });
2433}
2434
2435void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2436 std::vector<IfsStateCallback>& callbacks) {
2437 const auto state = isMountFullyLoaded(storageId);
2438 IfsState storageState = {};
2439 storageState.error = int(state) < 0;
2440 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2441 if (storageState.fullyLoaded) {
2442 const auto ifs = getIfs(storageId);
2443 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2444 }
2445
2446 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2447 if ((*cur)(storageId, storageState)) {
2448 ++cur;
2449 } else {
2450 cur = callbacks.erase(cur);
2451 }
2452 }
2453}
2454
2455void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2456 std::lock_guard l(mIfsStateCallbacksLock);
2457 mIfsStateCallbacks.erase(storageId);
2458}
2459
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002460void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002461 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002462 if (!ifs) {
Songchun Fan9471be52021-04-21 17:49:27 -07002463 LOG(ERROR) << "getMetrics failed, invalid storageId: " << storageId;
2464 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002465 }
Songchun Fan0dc77722021-05-03 17:13:52 -07002466 const auto& kMetricsReadLogsEnabled =
Songchun Fan9471be52021-04-21 17:49:27 -07002467 os::incremental::BnIncrementalService::METRICS_READ_LOGS_ENABLED();
Songchun Fan0dc77722021-05-03 17:13:52 -07002468 result->putBoolean(String16(kMetricsReadLogsEnabled.c_str()), ifs->readLogsEnabled() != 0);
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07002469 const auto incfsMetrics = mIncFs->getMetrics(ifs->metricsKey);
Songchun Fan0dc77722021-05-03 17:13:52 -07002470 if (incfsMetrics) {
2471 const auto& kMetricsTotalDelayedReads =
2472 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS();
2473 const auto totalDelayedReads =
2474 incfsMetrics->readsDelayedMin + incfsMetrics->readsDelayedPending;
2475 result->putInt(String16(kMetricsTotalDelayedReads.c_str()), totalDelayedReads);
2476 const auto& kMetricsTotalFailedReads =
2477 os::incremental::BnIncrementalService::METRICS_TOTAL_FAILED_READS();
2478 const auto totalFailedReads = incfsMetrics->readsFailedTimedOut +
2479 incfsMetrics->readsFailedHashVerification + incfsMetrics->readsFailedOther;
2480 result->putInt(String16(kMetricsTotalFailedReads.c_str()), totalFailedReads);
2481 const auto& kMetricsTotalDelayedReadsMillis =
2482 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS_MILLIS();
2483 const int64_t totalDelayedReadsMillis =
2484 (incfsMetrics->readsDelayedMinUs + incfsMetrics->readsDelayedPendingUs) / 1000;
2485 result->putLong(String16(kMetricsTotalDelayedReadsMillis.c_str()), totalDelayedReadsMillis);
2486 }
2487 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
2488 if (lastReadError && lastReadError->timestampUs != 0) {
2489 const auto& kMetricsMillisSinceLastReadError =
2490 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_READ_ERROR();
2491 result->putLong(String16(kMetricsMillisSinceLastReadError.c_str()),
2492 (int64_t)elapsedUsSinceMonoTs(lastReadError->timestampUs) / 1000);
2493 const auto& kMetricsLastReadErrorNo =
2494 os::incremental::BnIncrementalService::METRICS_LAST_READ_ERROR_NUMBER();
2495 result->putInt(String16(kMetricsLastReadErrorNo.c_str()), lastReadError->errorNo);
2496 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002497 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002498 if (!ifs->dataLoaderStub) {
Songchun Fan9471be52021-04-21 17:49:27 -07002499 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002500 }
Songchun Fan9471be52021-04-21 17:49:27 -07002501 ifs->dataLoaderStub->getMetrics(result);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002502}
2503
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002504IncrementalService::DataLoaderStub::DataLoaderStub(
2505 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2506 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2507 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2508 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002509 : mService(service),
2510 mId(id),
2511 mParams(std::move(params)),
2512 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002513 mStatusListener(std::move(statusListener)),
2514 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002515 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002516 mHealthCheckParams(healthCheckParams) {
2517 if (mHealthListener && !isHealthParamsValid()) {
2518 mHealthListener = {};
2519 }
2520 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002521 // Disable advanced health check statuses.
2522 mHealthCheckParams.blockedTimeoutMs = -1;
2523 }
2524 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002525}
2526
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002527IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002528 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002529 cleanupResources();
2530 }
2531}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002532
2533void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002534 auto now = Clock::now();
2535 {
2536 std::unique_lock lock(mMutex);
2537 mHealthPath.clear();
2538 unregisterFromPendingReads();
2539 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002540 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002541 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002542 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002543
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002544 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002545
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002546 {
2547 std::unique_lock lock(mMutex);
2548 mParams = {};
2549 mControl = {};
2550 mHealthControl = {};
2551 mHealthListener = {};
2552 mStatusCondition.wait_until(lock, now + 60s, [this] {
2553 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2554 });
2555 mStatusListener = {};
2556 mId = kInvalidStorageId;
2557 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002558}
2559
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002560sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2561 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002562 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002563 if (!status.isOk()) {
2564 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2565 return {};
2566 }
2567 if (!dataloader) {
2568 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2569 return {};
2570 }
2571 return dataloader;
2572}
2573
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002574bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2575 return (params().packageName == Constants::systemPackage);
2576}
2577
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002578bool IncrementalService::DataLoaderStub::requestCreate() {
2579 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2580}
2581
2582bool IncrementalService::DataLoaderStub::requestStart() {
2583 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2584}
2585
2586bool IncrementalService::DataLoaderStub::requestDestroy() {
2587 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2588}
2589
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002590bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002591 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002592 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002593 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002594 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002595 return fsmStep();
2596}
2597
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002598void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002599 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002600 mTargetStatus = status;
2601 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002602 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002603 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002604}
2605
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002606std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002607 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002608
2609 const auto now = mService.mClock->now();
2610 const bool healthy = (mPreviousBindDelay == 0ms);
2611
2612 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2613 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2614 LOG(INFO) << "Binding still in progress. "
2615 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002616 : "Already unhealthy, don't do anything.")
2617 << " for storage " << mId;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002618 // Binding still in progress.
2619 if (!healthy) {
2620 // Already unhealthy, don't do anything.
2621 return {};
2622 }
2623 // The DL is healthy/freshly bound, ok to retry for a few times.
2624 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2625 // Still within grace period.
2626 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2627 // Retry interval passed, retrying.
2628 mCurrentStatusTs = now;
2629 mPreviousBindDelay = 0ms;
2630 return 0ms;
2631 }
2632 return {};
2633 }
2634 // fallthrough, mark as unhealthy, and retry with delay
2635 }
2636
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002637 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002638 mPreviousBindTs = now;
2639
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002640 const auto nonCrashingInterval =
2641 std::max(castToMs(now - previousBindTs - mPreviousBindDelay), 100ms);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002642 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2643 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2644 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002645 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002646 }
2647
2648 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2649 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2650
2651 const auto bindDelayMs =
2652 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2653 maxBindDelayMs)
2654 .count();
2655 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -07002656 // rand() is enough, not worth maintaining a full-blown <rand> object for delay jitter
2657 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - // NOLINT
2658 bindDelayJitterRangeMs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002659 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002660 return mPreviousBindDelay;
2661}
2662
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002663bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002664 const auto maybeBindDelay = needToBind();
2665 if (!maybeBindDelay) {
2666 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2667 return true;
2668 }
2669 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002670 if (bindDelay > 1s) {
2671 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002672 << bindDelay.count() / 1000 << "s"
2673 << " for storage " << mId;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002674 }
2675
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002676 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002677 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2678 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002679 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002680 const bool healthy = (bindDelay == 0ms);
2681 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2682 << (healthy ? ", retrying." : "");
2683
2684 // Internal error, retry for healthy/new DLs.
2685 // Let needToBind migrate it to unhealthy after too many retries.
2686 if (healthy) {
2687 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2688 [this]() { fsmStep(); })) {
2689 // Mark as binding so that we know it's not the DL's fault.
2690 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2691 return true;
2692 }
2693 }
2694
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002695 return false;
2696 }
2697 return true;
2698}
2699
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002700bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002701 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002702 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002703 return false;
2704 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002705 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002706 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002707 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002708 return false;
2709 }
2710 return true;
2711}
2712
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002713bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002714 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002715 if (!dataloader) {
2716 return false;
2717 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002718 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002719 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002720 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002721 return false;
2722 }
2723 return true;
2724}
2725
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002726bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002727 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002728}
2729
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002730bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002731 if (!isValid()) {
2732 return false;
2733 }
2734
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002735 int currentStatus;
2736 int targetStatus;
2737 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002738 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002739 currentStatus = mCurrentStatus;
2740 targetStatus = mTargetStatus;
2741 }
2742
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002743 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002744
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002745 if (currentStatus == targetStatus) {
2746 return true;
2747 }
2748
2749 switch (targetStatus) {
2750 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002751 switch (currentStatus) {
2752 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2753 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2754 return true;
2755 default:
2756 return destroy();
2757 }
2758 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002759 }
2760 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2761 switch (currentStatus) {
2762 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2763 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2764 return start();
2765 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002766 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002767 }
2768 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2769 switch (currentStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002770 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002771 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2772 // Before binding need to make sure we are unbound.
2773 // Otherwise we'll get stuck binding.
2774 return destroy();
2775 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002776 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002777 return bind();
2778 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002779 return create();
2780 }
2781 break;
2782 default:
2783 LOG(ERROR) << "Invalid target status: " << targetStatus
2784 << ", current status: " << currentStatus;
2785 break;
2786 }
2787 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002788}
2789
2790binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002791 if (!isValid()) {
2792 return binder::Status::
2793 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2794 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002795 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002796 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2797 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002798 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2799 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002800 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2801 newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002802 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2803 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2804 [this, newStatus]() { setCurrentStatus(newStatus); });
2805 return binder::Status::ok();
2806 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002807
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002808 setCurrentStatus(newStatus);
2809 return binder::Status::ok();
2810}
2811
2812void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002813 int oldStatus, oldTargetStatus, newTargetStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002814 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002815 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002816 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002817 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002818 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002819 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002820
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002821 oldStatus = mCurrentStatus;
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002822 oldTargetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002823 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002824
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002825 // Change the status.
2826 mCurrentStatus = newStatus;
2827 mCurrentStatusTs = mService.mClock->now();
2828
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002829 switch (mCurrentStatus) {
2830 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2831 // Unavailable, retry.
2832 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2833 break;
2834 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2835 // Unrecoverable, just unbind.
2836 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2837 break;
2838 default:
2839 break;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002840 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002841
2842 newTargetStatus = mTargetStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002843 }
2844
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002845 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002846 << newStatus << " (target " << oldTargetStatus << " -> " << newTargetStatus << ")";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002847
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002848 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002849 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002850 }
2851
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002852 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002853
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002854 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002855}
2856
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002857bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2858 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2859 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002860}
2861
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002862void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002863 int healthStatus) {
2864 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2865 if (healthListener) {
2866 healthListener->onHealthStatus(id(), healthStatus);
2867 }
Songchun Fan9471be52021-04-21 17:49:27 -07002868 mHealthStatus = healthStatus;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002869}
2870
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002871void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2872 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002873
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002874 int healthStatusToReport = -1;
2875 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002876
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002877 {
2878 std::unique_lock lock(mMutex);
2879 unregisterFromPendingReads();
2880
2881 healthListener = mHealthListener;
2882
2883 // Healthcheck depends on timestamp of the oldest pending read.
2884 // 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 -07002885 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2886 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002887 const auto now = Clock::now();
2888 const auto kernelTsUs = getOldestPendingReadTs();
2889 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002890 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2891 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002892 mHealthBase = {now, kernelTsUs};
2893 }
2894
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002895 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2896 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002897 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2898 registerForPendingReads();
2899 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2900 lock.unlock();
2901 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002902 return;
2903 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002904
2905 resetHealthControl();
2906
2907 // Always make sure the data loader is started.
2908 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2909
2910 // Skip any further processing if health check params are invalid.
2911 if (!isHealthParamsValid()) {
2912 LOG(DEBUG) << id()
2913 << ": Skip any further processing if health check params are invalid.";
2914 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2915 lock.unlock();
2916 onHealthStatus(healthListener, healthStatusToReport);
2917 // Triggering data loader start. This is a one-time action.
2918 fsmStep();
2919 return;
2920 }
2921
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002922 // Don't schedule timer job less than 500ms in advance.
2923 static constexpr auto kTolerance = 500ms;
2924
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002925 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2926 const auto unhealthyTimeout =
2927 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2928 const auto unhealthyMonitoring =
2929 std::max(1000ms,
2930 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2931
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002932 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002933
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002934 Milliseconds checkBackAfter;
2935 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002936 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002937 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002938 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002939 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002940 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002941 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002942 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2943 } else {
2944 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002945 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002946 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2947 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002948 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002949 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002950 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2951 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002952 }
2953
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002954 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002955 if (healthStatusToReport != -1) {
2956 onHealthStatus(healthListener, healthStatusToReport);
2957 }
2958
2959 fsmStep();
2960}
2961
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002962Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2963 BootClockTsUs kernelTsUs) {
2964 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2965 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2966 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2967}
2968
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002969const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2970 if (mHealthPath.empty()) {
2971 resetHealthControl();
2972 return mHealthControl;
2973 }
2974 if (mHealthControl.pendingReads() < 0) {
2975 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2976 }
2977 if (mHealthControl.pendingReads() < 0) {
2978 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2979 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2980 << mHealthControl.logs() << ")";
2981 }
2982 return mHealthControl;
2983}
2984
2985void IncrementalService::DataLoaderStub::resetHealthControl() {
2986 mHealthControl = {};
2987}
2988
2989BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2990 auto result = kMaxBootClockTsUs;
2991
2992 const auto& control = initializeHealthControl();
2993 if (control.pendingReads() < 0) {
2994 return result;
2995 }
2996
Songchun Fan6944f1e2020-11-06 15:24:24 -08002997 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002998 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002999 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003000 // Clear previous pending reads
3001 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003002 return result;
3003 }
3004
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07003005 LOG(DEBUG) << id() << ": pendingReads: fd(" << control.pendingReads() << "), count("
3006 << mLastPendingReads.size() << "), block: " << mLastPendingReads.front().block
3007 << ", time: " << mLastPendingReads.front().bootClockTsUs
3008 << ", uid: " << mLastPendingReads.front().uid;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003009
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003010 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003011}
3012
3013void IncrementalService::DataLoaderStub::registerForPendingReads() {
3014 const auto pendingReadsFd = mHealthControl.pendingReads();
3015 if (pendingReadsFd < 0) {
3016 return;
3017 }
3018
3019 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
3020
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003021 mService.mLooper->addFd(
3022 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
3023 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07003024 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003025 self->updateHealthStatus(/*baseline=*/true);
3026 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003027 },
3028 this);
3029 mService.mLooper->wake();
3030}
3031
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003032BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
3033 auto result = kMaxBootClockTsUs;
3034 for (auto&& pendingRead : mLastPendingReads) {
3035 result = std::min(result, pendingRead.bootClockTsUs);
3036 }
3037 return result;
3038}
3039
Songchun Fan9471be52021-04-21 17:49:27 -07003040void IncrementalService::DataLoaderStub::getMetrics(android::os::PersistableBundle* result) {
3041 const auto duration = elapsedMsSinceOldestPendingRead();
3042 if (duration >= 0) {
Songchun Fan0dc77722021-05-03 17:13:52 -07003043 const auto& kMetricsMillisSinceOldestPendingRead =
Songchun Fan9471be52021-04-21 17:49:27 -07003044 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
Songchun Fan0dc77722021-05-03 17:13:52 -07003045 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.c_str()), duration);
Songchun Fan9471be52021-04-21 17:49:27 -07003046 }
Songchun Fan0dc77722021-05-03 17:13:52 -07003047 const auto& kMetricsStorageHealthStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003048 os::incremental::BnIncrementalService::METRICS_STORAGE_HEALTH_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003049 result->putInt(String16(kMetricsStorageHealthStatusCode.c_str()), mHealthStatus);
3050 const auto& kMetricsDataLoaderStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003051 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003052 result->putInt(String16(kMetricsDataLoaderStatusCode.c_str()), mCurrentStatus);
3053 const auto& kMetricsMillisSinceLastDataLoaderBind =
Songchun Fan9471be52021-04-21 17:49:27 -07003054 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_DATA_LOADER_BIND();
Songchun Fan0dc77722021-05-03 17:13:52 -07003055 result->putLong(String16(kMetricsMillisSinceLastDataLoaderBind.c_str()),
3056 elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000);
3057 const auto& kMetricsDataLoaderBindDelayMillis =
Songchun Fan9471be52021-04-21 17:49:27 -07003058 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_BIND_DELAY_MILLIS();
Songchun Fan0dc77722021-05-03 17:13:52 -07003059 result->putLong(String16(kMetricsDataLoaderBindDelayMillis.c_str()),
3060 mPreviousBindDelay.count());
Songchun Fan9471be52021-04-21 17:49:27 -07003061}
3062
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003063long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
3064 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
3065 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
3066 return 0;
3067 }
3068 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
3069}
3070
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07003071void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003072 const auto pendingReadsFd = mHealthControl.pendingReads();
3073 if (pendingReadsFd < 0) {
3074 return;
3075 }
3076
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003077 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
3078
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003079 mService.mLooper->removeFd(pendingReadsFd);
3080 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003081}
3082
Songchun Fan2570ec02020-10-08 17:22:33 -07003083void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003084 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07003085 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003086 mHealthCheckParams = healthCheckParams;
3087 mHealthListener = std::move(healthListener);
3088 if (!mHealthListener) {
3089 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07003090 }
3091}
3092
Songchun Fan6944f1e2020-11-06 15:24:24 -08003093static std::string toHexString(const RawMetadata& metadata) {
3094 int n = metadata.size();
3095 std::string res(n * 2, '\0');
3096 // Same as incfs::toString(fileId)
3097 static constexpr char kHexChar[] = "0123456789abcdef";
3098 for (int i = 0; i < n; ++i) {
3099 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
3100 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
3101 }
3102 return res;
3103}
3104
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003105void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003106 dprintf(fd, " dataLoader: {\n");
3107 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08003108 dprintf(fd, " currentStatusTs: %lldmcs\n",
3109 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003110 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
3111 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003112 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003113 dprintf(fd, " health: {\n");
3114 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3115 dprintf(fd, " base: %lldmcs (%lld)\n",
3116 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3117 (long long)mHealthBase.kernelTsUs);
3118 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3119 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3120 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3121 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003122 dprintf(fd, " lastPendingReads: \n");
3123 const auto control = mService.mIncFs->openMount(mHealthPath);
3124 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003125 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003126 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3127 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3128 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3129 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3130 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003131 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
Songchun Fan9471be52021-04-21 17:49:27 -07003132 (long long)(elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000000),
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003133 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003134 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003135 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003136 dprintf(fd, " dataLoaderParams: {\n");
3137 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3138 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3139 dprintf(fd, " className: %s\n", params.className.c_str());
3140 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3141 dprintf(fd, " }\n");
3142 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003143}
3144
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003145void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3146 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003147}
3148
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003149binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3150 bool enableReadLogs, int32_t* _aidl_return) {
3151 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3152 return binder::Status::ok();
3153}
3154
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003155FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3156 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3157}
3158
Songchun Fan3c82a302019-11-29 14:23:45 -08003159} // namespace android::incremental