blob: 24699d9dc9d8b9bfdd2b7300bceb9d847b0439dd [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "IncrementalService"
18
19#include "IncrementalService.h"
20
Songchun Fan3c82a302019-11-29 14:23:45 -080021#include <android-base/logging.h>
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -070022#include <android-base/no_destructor.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080023#include <android-base/properties.h>
24#include <android-base/stringprintf.h>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070025#include <binder/AppOpsManager.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080026#include <binder/Status.h>
27#include <sys/stat.h>
28#include <uuid/uuid.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080029
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070030#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080031#include <ctime>
Songchun Fan3c82a302019-11-29 14:23:45 -080032#include <iterator>
33#include <span>
Songchun Fan3c82a302019-11-29 14:23:45 -080034#include <type_traits>
35
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070036#include "IncrementalServiceValidation.h"
Songchun Fan3c82a302019-11-29 14:23:45 -080037#include "Metadata.pb.h"
38
39using namespace std::literals;
Songchun Fan3c82a302019-11-29 14:23:45 -080040
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -080041constexpr const char* kLoaderUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070042constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070043
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -080044constexpr const char* kInteractAcrossUsers = "android.permission.INTERACT_ACROSS_USERS";
45
Songchun Fan3c82a302019-11-29 14:23:45 -080046namespace android::incremental {
47
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070048using content::pm::DataLoaderParamsParcel;
49using content::pm::FileSystemControlParcel;
50using content::pm::IDataLoader;
51
Songchun Fan3c82a302019-11-29 14:23:45 -080052namespace {
53
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070054using IncrementalFileSystemControlParcel = os::incremental::IncrementalFileSystemControlParcel;
Songchun Fan3c82a302019-11-29 14:23:45 -080055
56struct Constants {
57 static constexpr auto backing = "backing_store"sv;
58 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080059 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080060 static constexpr auto storagePrefix = "st"sv;
61 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
62 static constexpr auto infoMdName = ".info"sv;
Alex Buynytskyy04035452020-06-06 20:15:58 -070063 static constexpr auto readLogsDisabledMarkerName = ".readlogs_disabled"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080064 static constexpr auto libDir = "lib"sv;
65 static constexpr auto libSuffix = ".so"sv;
66 static constexpr auto blockSize = 4096;
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -070067 static constexpr auto systemPackage = "android"sv;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -080068
Alex Buynytskyy060c9d62021-02-18 20:55:17 -080069 static constexpr auto userStatusDelay = 100ms;
70
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -080071 static constexpr auto progressUpdateInterval = 1000ms;
72 static constexpr auto perUidTimeoutOffset = progressUpdateInterval * 2;
73 static constexpr auto minPerUidTimeout = progressUpdateInterval * 3;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080074
75 // If DL was up and not crashing for 10mins, we consider it healthy and reset all delays.
76 static constexpr auto healthyDataLoaderUptime = 10min;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -080077
78 // For healthy DLs, we'll retry every ~5secs for ~10min
79 static constexpr auto bindRetryInterval = 5s;
80 static constexpr auto bindGracePeriod = 10min;
81
82 static constexpr auto bindingTimeout = 1min;
83
Alex Buynytskyy7b3e06e2021-03-23 11:29:05 -070084 // 1s, 10s, 100s (~2min), 1000s (~15min), 10000s (~3hrs)
85 static constexpr auto minBindDelay = 1s;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080086 static constexpr auto maxBindDelay = 10000s;
87 static constexpr auto bindDelayMultiplier = 10;
88 static constexpr auto bindDelayJitterDivider = 10;
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -070089
90 // Max interval after system invoked the DL when readlog collection can be enabled.
91 static constexpr auto readLogsMaxInterval = 2h;
Songchun Fan3c82a302019-11-29 14:23:45 -080092};
93
94static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070095 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080096 return c;
97}
98
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -070099static bool isPageAligned(IncFsSize s) {
100 return (s & (Constants::blockSize - 1)) == 0;
101}
102
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700103static bool getAlwaysEnableReadTimeoutsForSystemDataLoaders() {
104 return android::base::
105 GetBoolProperty("debug.incremental.always_enable_read_timeouts_for_system_dataloaders",
106 true);
107}
108
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700109static bool getEnforceReadLogsMaxIntervalForSystemDataLoaders() {
110 return android::base::GetBoolProperty("debug.incremental.enforce_readlogs_max_interval_for_"
111 "system_dataloaders",
112 false);
113}
114
115static Seconds getReadLogsMaxInterval() {
116 constexpr int limit = duration_cast<Seconds>(Constants::readLogsMaxInterval).count();
117 int readlogs_max_interval_secs =
118 std::min(limit,
119 android::base::GetIntProperty<
120 int>("debug.incremental.readlogs_max_interval_sec", limit));
121 return Seconds{readlogs_max_interval_secs};
122}
123
Songchun Fan3c82a302019-11-29 14:23:45 -0800124template <base::LogSeverity level = base::ERROR>
125bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
126 auto cstr = path::c_str(name);
127 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800128 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800129 PLOG(level) << "Can't create directory '" << name << '\'';
130 return false;
131 }
132 struct stat st;
133 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
134 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
135 return false;
136 }
137 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800138 if (::chmod(cstr, mode)) {
139 PLOG(level) << "Changing permission failed for '" << name << '\'';
140 return false;
141 }
142
Songchun Fan3c82a302019-11-29 14:23:45 -0800143 return true;
144}
145
146static std::string toMountKey(std::string_view path) {
147 if (path.empty()) {
148 return "@none";
149 }
150 if (path == "/"sv) {
151 return "@root";
152 }
153 if (path::isAbsolute(path)) {
154 path.remove_prefix(1);
155 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700156 if (path.size() > 16) {
157 path = path.substr(0, 16);
158 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800159 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700160 std::replace_if(
161 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
162 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800163}
164
165static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
166 std::string_view path) {
167 auto mountKey = toMountKey(path);
168 const auto prefixSize = mountKey.size();
169 for (int counter = 0; counter < 1000;
170 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
171 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800172 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800173 return {mountKey, mountRoot};
174 }
175 }
176 return {};
177}
178
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700179template <class Map>
180typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
181 const auto nextIt = map.upper_bound(path);
182 if (nextIt == map.begin()) {
183 return map.end();
184 }
185 const auto suspectIt = std::prev(nextIt);
186 if (!path::startsWith(path, suspectIt->first)) {
187 return map.end();
188 }
189 return suspectIt;
190}
191
192static base::unique_fd dup(base::borrowed_fd fd) {
193 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
194 return base::unique_fd(res);
195}
196
Songchun Fan3c82a302019-11-29 14:23:45 -0800197template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700198static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800199 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800200 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800201 ProtoMessage message;
202 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
203}
204
205static bool isValidMountTarget(std::string_view path) {
206 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
207}
208
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700209std::string makeUniqueName(std::string_view prefix) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800210 static constexpr auto uuidStringSize = 36;
211
212 uuid_t guid;
213 uuid_generate(guid);
214
215 std::string name;
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700216 const auto prefixSize = prefix.size();
Songchun Fan3c82a302019-11-29 14:23:45 -0800217 name.reserve(prefixSize + uuidStringSize);
218
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700219 name = prefix;
Songchun Fan3c82a302019-11-29 14:23:45 -0800220 name.resize(prefixSize + uuidStringSize);
221 uuid_unparse(guid, name.data() + prefixSize);
222
223 return name;
224}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700225
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700226std::string makeBindMdName() {
227 return makeUniqueName(constants().mountpointMdPrefix);
228}
229
Alex Buynytskyy04035452020-06-06 20:15:58 -0700230static bool checkReadLogsDisabledMarker(std::string_view root) {
231 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
232 struct stat st;
233 return (::stat(markerPath, &st) == 0);
234}
235
Songchun Fan3c82a302019-11-29 14:23:45 -0800236} // namespace
237
238IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700239 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700240 dataLoaderStub->cleanupResources();
241 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700242 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700243 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800244 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
245 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700246 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800247 incrementalService.mVold->unmountIncFs(target);
248 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700249 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800250 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
251 cleanupFilesystem(root);
252}
253
254auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800255 std::string name;
256 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
257 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
258 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800259 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
260 constants().storagePrefix.data(), id, no);
261 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800262 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800263 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800264 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
265 } else if (err != EEXIST) {
266 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
267 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800268 }
269 }
270 nextStorageDirNo = 0;
271 return storages.end();
272}
273
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700274template <class Func>
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700275static auto makeCleanup(Func&& f) requires(!std::is_lvalue_reference_v<Func>) {
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -0700276 // ok to move a 'forwarding' reference here as lvalues are disabled anyway
277 auto deleter = [f = std::move(f)](auto) { // NOLINT
278 f();
279 };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700280 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700281 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
282}
283
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700284static auto openDir(const char* dir) {
285 struct DirCloser {
286 void operator()(DIR* d) const noexcept { ::closedir(d); }
287 };
288 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700289}
290
291static auto openDir(std::string_view dir) {
292 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800293}
294
295static int rmDirContent(const char* path) {
296 auto dir = openDir(path);
297 if (!dir) {
298 return -EINVAL;
299 }
300 while (auto entry = ::readdir(dir.get())) {
301 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
302 continue;
303 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700304 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800305 if (entry->d_type == DT_DIR) {
306 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
307 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
308 return err;
309 }
310 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
311 PLOG(WARNING) << "Failed to rmdir " << fullPath;
312 return err;
313 }
314 } else {
315 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
316 PLOG(WARNING) << "Failed to delete " << fullPath;
317 return err;
318 }
319 }
320 }
321 return 0;
322}
323
Songchun Fan3c82a302019-11-29 14:23:45 -0800324void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800325 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800326 ::rmdir(path::join(root, constants().backing).c_str());
327 ::rmdir(path::join(root, constants().mount).c_str());
328 ::rmdir(path::c_str(root));
329}
330
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700331void IncrementalService::IncFsMount::setFlag(StorageFlags flag, bool value) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700332 if (value) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700333 flags |= flag;
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700334 } else {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700335 flags &= ~flag;
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700336 }
337}
338
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800339IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800340 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800341 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800342 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700343 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700344 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700345 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700346 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700347 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700348 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800349 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800350 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700351 CHECK(mVold) << "Vold service is unavailable";
352 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
353 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
354 CHECK(mJni) << "JNI is unavailable";
355 CHECK(mLooper) << "Looper is unavailable";
356 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700357 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700358 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800359 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700360
361 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700362 mJobProcessor = std::thread([this]() {
363 mJni->initializeForCurrentThread();
364 runJobProcessing();
365 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700366 mCmdLooperThread = std::thread([this]() {
367 mJni->initializeForCurrentThread();
368 runCmdLooper();
369 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700370
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700371 const auto mountedRootNames = adoptMountedInstances();
372 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800373}
374
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700375IncrementalService::~IncrementalService() {
376 {
377 std::lock_guard lock(mJobMutex);
378 mRunning = false;
379 }
380 mJobCondition.notify_all();
381 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700382 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700383 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700384 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700385 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700386 // Ensure that mounts are destroyed while the service is still valid.
387 mBindsByPath.clear();
388 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700389}
Songchun Fan3c82a302019-11-29 14:23:45 -0800390
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700391static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800392 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800393 case IncrementalService::BindKind::Temporary:
394 return "Temporary";
395 case IncrementalService::BindKind::Permanent:
396 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800397 }
398}
399
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700400template <class Duration>
Songchun Fan0dc77722021-05-03 17:13:52 -0700401static int64_t elapsedMcs(Duration start, Duration end) {
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700402 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
403}
404
Songchun Fan0dc77722021-05-03 17:13:52 -0700405int64_t IncrementalService::elapsedUsSinceMonoTs(uint64_t monoTsUs) {
406 const auto now = mClock->now();
407 const auto nowUs = static_cast<uint64_t>(
408 duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count());
Songchun Fand48a25e2021-04-30 09:50:58 -0700409 return nowUs - monoTsUs;
410}
411
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800412void IncrementalService::onDump(int fd) {
413 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -0700414 dprintf(fd, "IncFs features: 0x%x\n", int(mIncFs->features()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800415 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
416
417 std::unique_lock l(mLock);
418
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700419 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800420 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700421 std::unique_lock ll(ifs->lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700422 const IncFsMount& mnt = *ifs;
423 dprintf(fd, " [%d]: {\n", id);
424 if (id != mnt.mountId) {
425 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
426 } else {
427 dprintf(fd, " mountId: %d\n", mnt.mountId);
428 dprintf(fd, " root: %s\n", mnt.root.c_str());
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700429 const auto& metricsInstanceName = ifs->metricsKey;
Songchun Fanf949c372021-04-27 11:26:25 -0700430 dprintf(fd, " metrics instance name: %s\n", path::c_str(metricsInstanceName).get());
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700431 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700432 dprintf(fd, " flags: %d\n", int(mnt.flags));
433 if (mnt.startLoadingTs.time_since_epoch() == Clock::duration::zero()) {
434 dprintf(fd, " not loading\n");
435 } else {
436 dprintf(fd, " startLoading: %llds\n",
437 (long long)(elapsedMcs(mnt.startLoadingTs, Clock::now()) / 1000000));
438 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700439 if (mnt.dataLoaderStub) {
440 mnt.dataLoaderStub->onDump(fd);
441 } else {
442 dprintf(fd, " dataLoader: null\n");
443 }
444 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
445 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700446 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700447 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800448 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700449 }
450 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800451
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700452 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
453 for (auto&& [target, bind] : mnt.bindPoints) {
454 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
455 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
456 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
457 dprintf(fd, " kind: %s\n", toString(bind.kind));
458 }
459 dprintf(fd, " }\n");
Songchun Fanf949c372021-04-27 11:26:25 -0700460
461 dprintf(fd, " incfsMetrics: {\n");
462 const auto incfsMetrics = mIncFs->getMetrics(metricsInstanceName);
463 if (incfsMetrics) {
464 dprintf(fd, " readsDelayedMin: %d\n", incfsMetrics.value().readsDelayedMin);
465 dprintf(fd, " readsDelayedMinUs: %lld\n",
466 (long long)incfsMetrics.value().readsDelayedMinUs);
467 dprintf(fd, " readsDelayedPending: %d\n",
468 incfsMetrics.value().readsDelayedPending);
469 dprintf(fd, " readsDelayedPendingUs: %lld\n",
470 (long long)incfsMetrics.value().readsDelayedPendingUs);
471 dprintf(fd, " readsFailedHashVerification: %d\n",
472 incfsMetrics.value().readsFailedHashVerification);
473 dprintf(fd, " readsFailedOther: %d\n", incfsMetrics.value().readsFailedOther);
474 dprintf(fd, " readsFailedTimedOut: %d\n",
475 incfsMetrics.value().readsFailedTimedOut);
476 } else {
477 dprintf(fd, " Metrics not available. Errno: %d\n", errno);
478 }
479 dprintf(fd, " }\n");
Songchun Fand48a25e2021-04-30 09:50:58 -0700480
481 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
482 const auto errorNo = errno;
483 dprintf(fd, " lastReadError: {\n");
484 if (lastReadError) {
485 if (lastReadError->timestampUs == 0) {
486 dprintf(fd, " No read errors.\n");
487 } else {
488 dprintf(fd, " fileId: %s\n",
489 IncFsWrapper::toString(lastReadError->id).c_str());
490 dprintf(fd, " time: %llu microseconds ago\n",
491 (unsigned long long)elapsedUsSinceMonoTs(lastReadError->timestampUs));
492 dprintf(fd, " blockIndex: %d\n", lastReadError->block);
493 dprintf(fd, " errno: %d\n", lastReadError->errorNo);
494 }
495 } else {
496 dprintf(fd, " Info not available. Errno: %d\n", errorNo);
497 }
498 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800499 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700500 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800501 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700502 dprintf(fd, "}\n");
503 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800504 for (auto&& [target, mountPairIt] : mBindsByPath) {
505 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700506 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
507 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
508 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
509 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800510 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700511 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800512}
513
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800514bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700515 if (!ifs.dataLoaderStub) {
516 return false;
517 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700518 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800519 return true;
520 }
521
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700522 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800523}
524
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700525void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800526 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700527 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800528 }
529
530 std::vector<IfsMountPtr> mounts;
531 {
532 std::lock_guard l(mLock);
533 mounts.reserve(mMounts.size());
534 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700535 std::unique_lock ll(ifs->lock);
536
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800537 if (ifs->mountId != id) {
538 continue;
539 }
540
541 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800542 mounts.push_back(ifs);
543 }
544 }
545 }
546
Alex Buynytskyy69941662020-04-11 21:40:37 -0700547 if (mounts.empty()) {
548 return;
549 }
550
Songchun Fan3c82a302019-11-29 14:23:45 -0800551 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700552 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800553 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700554 std::unique_lock l(ifs->lock);
555 if (ifs->dataLoaderStub) {
556 ifs->dataLoaderStub->requestStart();
557 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800558 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800559 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800560}
561
562auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
563 for (;;) {
564 if (mNextId == kMaxStorageId) {
565 mNextId = 0;
566 }
567 auto id = ++mNextId;
568 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
569 if (inserted) {
570 return it;
571 }
572 }
573}
574
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700575StorageId IncrementalService::createStorage(std::string_view mountPoint,
576 content::pm::DataLoaderParamsParcel dataLoaderParams,
577 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800578 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
579 if (!path::isAbsolute(mountPoint)) {
580 LOG(ERROR) << "path is not absolute: " << mountPoint;
581 return kInvalidStorageId;
582 }
583
584 auto mountNorm = path::normalize(mountPoint);
585 {
586 const auto id = findStorageId(mountNorm);
587 if (id != kInvalidStorageId) {
588 if (options & CreateOptions::OpenExisting) {
589 LOG(INFO) << "Opened existing storage " << id;
590 return id;
591 }
592 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
593 return kInvalidStorageId;
594 }
595 }
596
597 if (!(options & CreateOptions::CreateNew)) {
598 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
599 return kInvalidStorageId;
600 }
601
602 if (!path::isEmptyDir(mountNorm)) {
603 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
604 return kInvalidStorageId;
605 }
606 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
607 if (mountRoot.empty()) {
608 LOG(ERROR) << "Bad mount point";
609 return kInvalidStorageId;
610 }
611 // Make sure the code removes all crap it may create while still failing.
612 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
613 auto firstCleanupOnFailure =
614 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
615
616 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800617 const auto backing = path::join(mountRoot, constants().backing);
618 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800619 return kInvalidStorageId;
620 }
621
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700622 std::string metricsKey;
Songchun Fan3c82a302019-11-29 14:23:45 -0800623 IncFsMount::Control control;
624 {
625 std::lock_guard l(mMountOperationLock);
626 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800627
628 if (auto err = rmDirContent(backing.c_str())) {
629 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
630 return kInvalidStorageId;
631 }
632 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
633 return kInvalidStorageId;
634 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800635 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
636 return kInvalidStorageId;
637 }
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700638 metricsKey = makeUniqueName(mountKey);
639 auto status = mVold->mountIncFs(backing, mountTarget, 0, metricsKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800640 if (!status.isOk()) {
641 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
642 return kInvalidStorageId;
643 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800644 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
645 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800646 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
647 return kInvalidStorageId;
648 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800649 int cmd = controlParcel.cmd.release().release();
650 int pendingReads = controlParcel.pendingReads.release().release();
651 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800652 int blocksWritten =
653 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
654 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800655 }
656
657 std::unique_lock l(mLock);
658 const auto mountIt = getStorageSlotLocked();
659 const auto mountId = mountIt->first;
660 l.unlock();
661
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700662 auto ifs = std::make_shared<IncFsMount>(std::move(mountRoot), std::move(metricsKey), mountId,
663 std::move(control), *this);
Songchun Fan3c82a302019-11-29 14:23:45 -0800664 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
665 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700666 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800667
668 auto secondCleanup = [this, &l](auto itPtr) {
669 if (!l.owns_lock()) {
670 l.lock();
671 }
672 mMounts.erase(*itPtr);
673 };
674 auto secondCleanupOnFailure =
675 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
676
677 const auto storageIt = ifs->makeStorage(ifs->mountId);
678 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800679 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800680 return kInvalidStorageId;
681 }
682
683 {
684 metadata::Mount m;
685 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700686 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700687 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
688 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
689 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800690 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800691 if (auto err =
692 mIncFs->makeFile(ifs->control,
693 path::join(ifs->root, constants().mount,
694 constants().infoMdName),
695 0777, idFromMetadata(metadata),
696 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800697 LOG(ERROR) << "Saving mount metadata failed: " << -err;
698 return kInvalidStorageId;
699 }
700 }
701
702 const auto bk =
703 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800704 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
705 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800706 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800707 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800708 return kInvalidStorageId;
709 }
710
711 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700712 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800713
Songchun Fan3c82a302019-11-29 14:23:45 -0800714 mountIt->second = std::move(ifs);
715 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700716
Songchun Fan3c82a302019-11-29 14:23:45 -0800717 LOG(INFO) << "created storage " << mountId;
718 return mountId;
719}
720
721StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
722 StorageId linkedStorage,
723 IncrementalService::CreateOptions options) {
724 if (!isValidMountTarget(mountPoint)) {
725 LOG(ERROR) << "Mount point is invalid or missing";
726 return kInvalidStorageId;
727 }
728
729 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700730 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800731 if (!ifs) {
732 LOG(ERROR) << "Ifs unavailable";
733 return kInvalidStorageId;
734 }
735
736 const auto mountIt = getStorageSlotLocked();
737 const auto storageId = mountIt->first;
738 const auto storageIt = ifs->makeStorage(storageId);
739 if (storageIt == ifs->storages.end()) {
740 LOG(ERROR) << "Can't create a new storage";
741 mMounts.erase(mountIt);
742 return kInvalidStorageId;
743 }
744
745 l.unlock();
746
747 const auto bk =
748 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800749 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
750 std::string(storageIt->second.name), path::normalize(mountPoint),
751 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800752 err < 0) {
753 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700754 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
755 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800756 return kInvalidStorageId;
757 }
758
759 mountIt->second = ifs;
760 return storageId;
761}
762
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700763bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700764 content::pm::DataLoaderParamsParcel dataLoaderParams,
765 DataLoaderStatusListener statusListener,
766 const StorageHealthCheckParams& healthCheckParams,
767 StorageHealthListener healthListener,
768 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800769 // Per Uid timeouts.
770 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700771 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800772 }
773
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700774 IfsMountPtr ifs;
775 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800776
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700777 // Re-initialize DataLoader.
778 {
779 ifs = getIfs(storageId);
780 if (!ifs) {
781 return false;
782 }
783
784 std::unique_lock l(ifs->lock);
785 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
786 }
787
788 if (dataLoaderStub) {
789 dataLoaderStub->cleanupResources();
790 dataLoaderStub = {};
791 }
792
793 {
794 std::unique_lock l(ifs->lock);
795 if (ifs->dataLoaderStub) {
796 LOG(INFO) << "Skipped data loader stub creation because it already exists";
797 return false;
798 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700799
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700800 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
801 healthCheckParams, std::move(healthListener));
802 CHECK(ifs->dataLoaderStub);
803 dataLoaderStub = ifs->dataLoaderStub;
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700804
805 // Disable long read timeouts for non-system dataloaders.
806 // To be re-enabled after installation is complete.
807 ifs->setReadTimeoutsRequested(dataLoaderStub->isSystemDataLoader() &&
808 getAlwaysEnableReadTimeoutsForSystemDataLoaders());
809 applyStorageParamsLocked(*ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700810 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800811
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700812 if (dataLoaderStub->isSystemDataLoader() &&
813 !getEnforceReadLogsMaxIntervalForSystemDataLoaders()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700814 // Readlogs from system dataloader (adb) can always be collected.
815 ifs->startLoadingTs = TimePoint::max();
816 } else {
817 // Assign time when installation wants the DL to start streaming.
818 const auto startLoadingTs = mClock->now();
819 ifs->startLoadingTs = startLoadingTs;
820 // Setup a callback to disable the readlogs after max interval.
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700821 addTimedJob(*mTimedQueue, storageId, getReadLogsMaxInterval(),
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700822 [this, storageId, startLoadingTs]() {
823 const auto ifs = getIfs(storageId);
824 if (!ifs) {
825 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
826 << storageId;
827 return;
828 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700829 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700830 if (ifs->startLoadingTs != startLoadingTs) {
831 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
832 "installation?): "
833 << storageId;
834 return;
835 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700836 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700837 });
838 }
839
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800840 return dataLoaderStub->requestStart();
841}
842
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700843void IncrementalService::onInstallationComplete(StorageId storage) {
844 IfsMountPtr ifs = getIfs(storage);
845 if (!ifs) {
846 return;
847 }
848
849 // Always enable long read timeouts after installation is complete.
850 std::unique_lock l(ifs->lock);
851 ifs->setReadTimeoutsRequested(true);
852 applyStorageParamsLocked(*ifs);
853}
854
Songchun Fan3c82a302019-11-29 14:23:45 -0800855IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
856 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700857 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800858}
859
860StorageId IncrementalService::findStorageId(std::string_view path) const {
861 std::lock_guard l(mLock);
862 auto it = findStorageLocked(path);
863 if (it == mBindsByPath.end()) {
864 return kInvalidStorageId;
865 }
866 return it->second->second.storage;
867}
868
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800869void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700870 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700871 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800872 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700873 return;
874 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700875
876 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800877 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700878 return;
879 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800880 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700881
882 const auto metadata = constants().readLogsDisabledMarkerName;
883 if (auto err = mIncFs->makeFile(ifs->control,
884 path::join(ifs->root, constants().mount,
885 constants().readLogsDisabledMarkerName),
886 0777, idFromMetadata(metadata), {})) {
887 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
888 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
889 return;
890 }
891
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700892 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700893}
894
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700895int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
896 const auto ifs = getIfs(storageId);
897 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700898 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700899 return -EINVAL;
900 }
901
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700902 std::string packageName;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700903
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700904 {
905 std::unique_lock l(ifs->lock);
906 if (!enableReadLogs) {
907 return disableReadLogsLocked(*ifs);
908 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700909
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700910 if (!ifs->readLogsAllowed()) {
911 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
912 return -EPERM;
913 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700914
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700915 if (!ifs->dataLoaderStub) {
916 // This should never happen - only DL can call enableReadLogs.
917 LOG(ERROR) << "enableReadLogs failed: invalid state";
918 return -EPERM;
919 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700920
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700921 // Check installation time.
922 const auto now = mClock->now();
923 const auto startLoadingTs = ifs->startLoadingTs;
924 if (startLoadingTs <= now && now - startLoadingTs > getReadLogsMaxInterval()) {
925 LOG(ERROR)
926 << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
927 << storageId;
928 return -EPERM;
929 }
930
931 packageName = ifs->dataLoaderStub->params().packageName;
932 ifs->setReadLogsRequested(true);
933 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700934
935 // Check loader usage stats permission and apop.
936 if (auto status =
937 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
938 !status.isOk()) {
939 LOG(ERROR) << " Permission: " << kLoaderUsageStats
940 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700941 return fromBinderStatus(status);
942 }
943
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700944 // Check multiuser permission.
945 if (auto status =
946 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
947 !status.isOk()) {
948 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
949 << " check failed: " << status.toString8();
950 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700951 }
952
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700953 {
954 std::unique_lock l(ifs->lock);
955 if (!ifs->readLogsRequested()) {
956 return 0;
957 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700958 if (auto status = applyStorageParamsLocked(*ifs); status != 0) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700959 return status;
960 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700961 }
962
963 registerAppOpsCallback(packageName);
964
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700965 return 0;
966}
967
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700968int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700969 ifs.setReadLogsRequested(false);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700970 return applyStorageParamsLocked(ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700971}
972
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700973int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700974 os::incremental::IncrementalFileSystemControlParcel control;
975 control.cmd.reset(dup(ifs.control.cmd()));
976 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700977 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700978 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700979 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700980 }
981
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700982 bool enableReadLogs = ifs.readLogsRequested();
983 bool enableReadTimeouts = ifs.readTimeoutsRequested();
984
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700985 std::lock_guard l(mMountOperationLock);
Songchun Fanf6c65bb2021-05-10 16:17:30 -0700986 auto status = mVold->setIncFsMountOptions(control, enableReadLogs, enableReadTimeouts,
987 ifs.metricsKey);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800988 if (status.isOk()) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700989 // Store states.
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800990 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700991 ifs.setReadTimeoutsEnabled(enableReadTimeouts);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700992 } else {
993 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800994 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700995 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700996}
997
Songchun Fan3c82a302019-11-29 14:23:45 -0800998void IncrementalService::deleteStorage(StorageId storageId) {
999 const auto ifs = getIfs(storageId);
1000 if (!ifs) {
1001 return;
1002 }
1003 deleteStorage(*ifs);
1004}
1005
1006void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
1007 std::unique_lock l(ifs.lock);
1008 deleteStorageLocked(ifs, std::move(l));
1009}
1010
1011void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
1012 std::unique_lock<std::mutex>&& ifsLock) {
1013 const auto storages = std::move(ifs.storages);
1014 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
1015 const auto bindPoints = ifs.bindPoints;
1016 ifsLock.unlock();
1017
1018 std::lock_guard l(mLock);
1019 for (auto&& [id, _] : storages) {
1020 if (id != ifs.mountId) {
1021 mMounts.erase(id);
1022 }
1023 }
1024 for (auto&& [path, _] : bindPoints) {
1025 mBindsByPath.erase(path);
1026 }
1027 mMounts.erase(ifs.mountId);
1028}
1029
1030StorageId IncrementalService::openStorage(std::string_view pathInMount) {
1031 if (!path::isAbsolute(pathInMount)) {
1032 return kInvalidStorageId;
1033 }
1034
1035 return findStorageId(path::normalize(pathInMount));
1036}
1037
Songchun Fan3c82a302019-11-29 14:23:45 -08001038IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
1039 std::lock_guard l(mLock);
1040 return getIfsLocked(storage);
1041}
1042
1043const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
1044 auto it = mMounts.find(storage);
1045 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001046 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -07001047 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -08001048 }
1049 return it->second;
1050}
1051
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001052int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
1053 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001054 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001055 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001056 return -EINVAL;
1057 }
1058
1059 const auto ifs = getIfs(storage);
1060 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001061 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001062 return -EINVAL;
1063 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001064
Songchun Fan3c82a302019-11-29 14:23:45 -08001065 std::unique_lock l(ifs->lock);
1066 const auto storageInfo = ifs->storages.find(storage);
1067 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001068 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -08001069 return -EINVAL;
1070 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001071 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001072 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001073 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001074 return -EINVAL;
1075 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001076 l.unlock();
1077 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001078 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
1079 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -08001080}
1081
1082int IncrementalService::unbind(StorageId storage, std::string_view target) {
1083 if (!path::isAbsolute(target)) {
1084 return -EINVAL;
1085 }
1086
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001087 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001088
1089 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
1090 // otherwise there's a chance to unmount something completely unrelated
1091 const auto norm = path::normalize(target);
1092 std::unique_lock l(mLock);
1093 const auto storageIt = mBindsByPath.find(norm);
1094 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
1095 return -EINVAL;
1096 }
1097 const auto bindIt = storageIt->second;
1098 const auto storageId = bindIt->second.storage;
1099 const auto ifs = getIfsLocked(storageId);
1100 if (!ifs) {
1101 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
1102 << " is missing";
1103 return -EFAULT;
1104 }
1105 mBindsByPath.erase(storageIt);
1106 l.unlock();
1107
1108 mVold->unmountIncFs(bindIt->first);
1109 std::unique_lock l2(ifs->lock);
1110 if (ifs->bindPoints.size() <= 1) {
1111 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -07001112 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001113 } else {
1114 const std::string savedFile = std::move(bindIt->second.savedFilename);
1115 ifs->bindPoints.erase(bindIt);
1116 l2.unlock();
1117 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001118 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001119 }
1120 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001121
Songchun Fan3c82a302019-11-29 14:23:45 -08001122 return 0;
1123}
1124
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001125std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001126 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001127 std::string_view path) const {
1128 if (!path::isAbsolute(path)) {
1129 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001130 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001131 auto normPath = path::normalize(path);
1132 if (path::startsWith(normPath, storageIt->second.name)) {
1133 return normPath;
1134 }
1135 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001136 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1137 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001138 return {};
1139 }
1140 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001141}
1142
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001143std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001144 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001145 std::unique_lock l(ifs.lock);
1146 const auto storageInfo = ifs.storages.find(storage);
1147 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001148 return {};
1149 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001150 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001151}
1152
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001153int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001154 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001155 const auto ifs = getIfs(storage);
1156 if (!ifs) {
1157 return -EINVAL;
1158 }
1159 if (data.size() > params.size) {
1160 LOG(ERROR) << "Bad data size - bigger than file size";
1161 return -EINVAL;
1162 }
1163 if (!data.empty() && data.size() != params.size) {
1164 // Writing a page is an irreversible operation, and it can't be updated with additional
1165 // data later. Check that the last written page is complete, or we may break the file.
1166 if (!isPageAligned(data.size())) {
1167 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001168 return -EINVAL;
1169 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001170 }
1171 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1172 if (normPath.empty()) {
1173 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1174 return -EINVAL;
1175 }
1176 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1177 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1178 return err;
1179 }
1180 if (params.size > 0) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001181 if (auto err = mIncFs->reserveSpace(ifs->control, id, params.size)) {
1182 if (err != -EOPNOTSUPP) {
1183 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1184 (void)mIncFs->unlink(ifs->control, normPath);
1185 return err;
1186 } else {
1187 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1188 "may run out of disk later";
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001189 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001190 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001191 if (!data.empty()) {
1192 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001193 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001194 return err;
1195 }
1196 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001197 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001198 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001199}
1200
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001201int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001202 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001203 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001204 if (normPath.empty()) {
1205 return -EINVAL;
1206 }
1207 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001208 }
1209 return -EINVAL;
1210}
1211
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001212int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001213 const auto ifs = getIfs(storageId);
1214 if (!ifs) {
1215 return -EINVAL;
1216 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001217 return makeDirs(*ifs, storageId, path, mode);
1218}
1219
1220int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1221 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001222 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1223 if (normPath.empty()) {
1224 return -EINVAL;
1225 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001226 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001227}
1228
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001229int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1230 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001231 std::unique_lock l(mLock);
1232 auto ifsSrc = getIfsLocked(sourceStorageId);
1233 if (!ifsSrc) {
1234 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001235 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001236 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1237 return -EINVAL;
1238 }
1239 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001240 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1241 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001242 if (normOldPath.empty() || normNewPath.empty()) {
1243 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1244 return -EINVAL;
1245 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001246 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1247 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1248 << " to " << newPath << "[" << normNewPath << "]";
1249 return err;
1250 }
1251 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001252}
1253
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001254int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001255 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001256 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001257 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001258 }
1259 return -EINVAL;
1260}
1261
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001262int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1263 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001264 std::string&& target, BindKind kind,
1265 std::unique_lock<std::mutex>& mainLock) {
1266 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001267 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001268 return -EINVAL;
1269 }
1270
1271 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001272 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001273 if (kind != BindKind::Temporary) {
1274 metadata::BindPoint bp;
1275 bp.set_storage_id(storage);
1276 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001277 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001278 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001279 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001280 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001281 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001282 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1283 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1284 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001285 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001286 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001287 return int(node);
1288 }
1289 }
1290
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001291 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1292 std::move(target), kind, mainLock);
1293 if (res) {
1294 mIncFs->unlink(ifs.control, metadataFullPath);
1295 }
1296 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001297}
1298
1299int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001300 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001301 std::string&& target, BindKind kind,
1302 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001303 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001304 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001305 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001306 if (!status.isOk()) {
1307 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1308 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1309 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1310 : status.serviceSpecificErrorCode() == 0
1311 ? -EFAULT
1312 : status.serviceSpecificErrorCode()
1313 : -EIO;
1314 }
1315 }
1316
1317 if (!mainLock.owns_lock()) {
1318 mainLock.lock();
1319 }
1320 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001321 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1322 std::move(target), kind);
1323 return 0;
1324}
1325
1326void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1327 std::string&& metadataName, std::string&& source,
1328 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001329 const auto [it, _] =
1330 ifs.bindPoints.insert_or_assign(target,
1331 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001332 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001333 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001334}
1335
1336RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1337 const auto ifs = getIfs(storage);
1338 if (!ifs) {
1339 return {};
1340 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001341 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001342 if (normPath.empty()) {
1343 return {};
1344 }
1345 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001346}
1347
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001348RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001349 const auto ifs = getIfs(storage);
1350 if (!ifs) {
1351 return {};
1352 }
1353 return mIncFs->getMetadata(ifs->control, node);
1354}
1355
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001356void IncrementalService::setUidReadTimeouts(StorageId storage,
1357 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001358 using microseconds = std::chrono::microseconds;
1359 using milliseconds = std::chrono::milliseconds;
1360
1361 auto maxPendingTimeUs = microseconds(0);
1362 for (const auto& timeouts : perUidReadTimeouts) {
1363 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1364 }
1365 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07001366 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001367 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1368 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001369 return;
1370 }
1371
1372 const auto ifs = getIfs(storage);
1373 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001374 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001375 return;
1376 }
1377
1378 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1379 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1380 return;
1381 }
1382
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001383 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1384 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1385 if (checkUidReadTimeouts(storageId, state, timeout)) {
1386 return true;
1387 }
1388 clearUidReadTimeouts(storageId);
1389 return false;
1390 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001391}
1392
1393void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1394 const auto ifs = getIfs(storage);
1395 if (!ifs) {
1396 return;
1397 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001398 mIncFs->setUidReadTimeouts(ifs->control, {});
1399}
1400
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001401bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1402 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001403 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001404 // Reached maximum timeout.
1405 return false;
1406 }
1407 if (state.error) {
1408 // Something is wrong, abort.
1409 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001410 }
1411
1412 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001413 if (state.fullyLoaded && !state.readLogsEnabled) {
1414 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001415 }
1416
1417 const auto timeLeft = timeLimit - Clock::now();
1418 if (timeLeft < Constants::progressUpdateInterval) {
1419 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001420 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001421 }
1422
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001423 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001424}
1425
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001426std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1427 std::unordered_set<std::string_view> mountedRootNames;
1428 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1429 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1430 for (auto [source, target] : binds) {
1431 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1432 LOG(INFO) << " " << path::join(root, source);
1433 }
1434
1435 // Ensure it's a kind of a mount that's managed by IncrementalService
1436 if (path::basename(root) != constants().mount ||
1437 path::basename(backingDir) != constants().backing) {
1438 return;
1439 }
1440 const auto expectedRoot = path::dirname(root);
1441 if (path::dirname(backingDir) != expectedRoot) {
1442 return;
1443 }
1444 if (path::dirname(expectedRoot) != mIncrementalDir) {
1445 return;
1446 }
1447 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1448 return;
1449 }
1450
1451 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1452
1453 // make sure we clean up the mount if it happens to be a bad one.
1454 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1455 auto cleanupFiles = makeCleanup([&]() {
1456 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1457 IncFsMount::cleanupFilesystem(expectedRoot);
1458 });
1459 auto cleanupMounts = makeCleanup([&]() {
1460 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1461 for (auto&& [_, target] : binds) {
1462 mVold->unmountIncFs(std::string(target));
1463 }
1464 mVold->unmountIncFs(std::string(root));
1465 });
1466
1467 auto control = mIncFs->openMount(root);
1468 if (!control) {
1469 LOG(INFO) << "failed to open mount " << root;
1470 return;
1471 }
1472
1473 auto mountRecord =
1474 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1475 path::join(root, constants().infoMdName));
1476 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1477 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1478 return;
1479 }
1480
1481 auto mountId = mountRecord.storage().id();
1482 mNextId = std::max(mNextId, mountId + 1);
1483
1484 DataLoaderParamsParcel dataLoaderParams;
1485 {
1486 const auto& loader = mountRecord.loader();
1487 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1488 dataLoaderParams.packageName = loader.package_name();
1489 dataLoaderParams.className = loader.class_name();
1490 dataLoaderParams.arguments = loader.arguments();
1491 }
1492
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001493 // Not way to obtain a real sysfs key at this point - metrics will stop working after "soft"
1494 // reboot.
1495 std::string metricsKey{};
1496 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), std::move(metricsKey),
1497 mountId, std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001498 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001499
Alex Buynytskyy04035452020-06-06 20:15:58 -07001500 // Check if marker file present.
1501 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001502 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001503 }
1504
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001505 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1506 auto d = openDir(root);
1507 while (auto e = ::readdir(d.get())) {
1508 if (e->d_type == DT_REG) {
1509 auto name = std::string_view(e->d_name);
1510 if (name.starts_with(constants().mountpointMdPrefix)) {
1511 permanentBindPoints
1512 .emplace_back(name,
1513 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1514 ifs->control,
1515 path::join(root,
1516 name)));
1517 if (permanentBindPoints.back().second.dest_path().empty() ||
1518 permanentBindPoints.back().second.source_subdir().empty()) {
1519 permanentBindPoints.pop_back();
1520 mIncFs->unlink(ifs->control, path::join(root, name));
1521 } else {
1522 LOG(INFO) << "Permanent bind record: '"
1523 << permanentBindPoints.back().second.source_subdir() << "'->'"
1524 << permanentBindPoints.back().second.dest_path() << "'";
1525 }
1526 }
1527 } else if (e->d_type == DT_DIR) {
1528 if (e->d_name == "."sv || e->d_name == ".."sv) {
1529 continue;
1530 }
1531 auto name = std::string_view(e->d_name);
1532 if (name.starts_with(constants().storagePrefix)) {
1533 int storageId;
1534 const auto res =
1535 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1536 name.data() + name.size(), storageId);
1537 if (res.ec != std::errc{} || *res.ptr != '_') {
1538 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1539 << "' for mount " << expectedRoot;
1540 continue;
1541 }
1542 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1543 if (!inserted) {
1544 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1545 << " for mount " << expectedRoot;
1546 continue;
1547 }
1548 ifs->storages.insert_or_assign(storageId,
1549 IncFsMount::Storage{path::join(root, name)});
1550 mNextId = std::max(mNextId, storageId + 1);
1551 }
1552 }
1553 }
1554
1555 if (ifs->storages.empty()) {
1556 LOG(WARNING) << "No valid storages in mount " << root;
1557 return;
1558 }
1559
1560 // now match the mounted directories with what we expect to have in the metadata
1561 {
1562 std::unique_lock l(mLock, std::defer_lock);
1563 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1564 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1565 [&, bindRecord = bindRecord](auto&& bind) {
1566 return bind.second == bindRecord.dest_path() &&
1567 path::join(root, bind.first) ==
1568 bindRecord.source_subdir();
1569 });
1570 if (mountedIt != binds.end()) {
1571 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1572 << " to mount " << mountedIt->first;
1573 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1574 std::move(*bindRecord.mutable_source_subdir()),
1575 std::move(*bindRecord.mutable_dest_path()),
1576 BindKind::Permanent);
1577 if (mountedIt != binds.end() - 1) {
1578 std::iter_swap(mountedIt, binds.end() - 1);
1579 }
1580 binds = binds.first(binds.size() - 1);
1581 } else {
1582 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1583 << ", mounting";
1584 // doesn't exist - try mounting back
1585 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1586 std::move(*bindRecord.mutable_source_subdir()),
1587 std::move(*bindRecord.mutable_dest_path()),
1588 BindKind::Permanent, l)) {
1589 mIncFs->unlink(ifs->control, metadataFile);
1590 }
1591 }
1592 }
1593 }
1594
1595 // if anything stays in |binds| those are probably temporary binds; system restarted since
1596 // they were mounted - so let's unmount them all.
1597 for (auto&& [source, target] : binds) {
1598 if (source.empty()) {
1599 continue;
1600 }
1601 mVold->unmountIncFs(std::string(target));
1602 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001603 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001604
1605 if (ifs->bindPoints.empty()) {
1606 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1607 deleteStorage(*ifs);
1608 return;
1609 }
1610
1611 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1612 CHECK(ifs->dataLoaderStub);
1613
1614 mountedRootNames.insert(path::basename(ifs->root));
1615
1616 // not locking here at all: we're still in the constructor, no other calls can happen
1617 mMounts[ifs->mountId] = std::move(ifs);
1618 });
1619
1620 return mountedRootNames;
1621}
1622
1623void IncrementalService::mountExistingImages(
1624 const std::unordered_set<std::string_view>& mountedRootNames) {
1625 auto dir = openDir(mIncrementalDir);
1626 if (!dir) {
1627 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1628 return;
1629 }
1630 while (auto entry = ::readdir(dir.get())) {
1631 if (entry->d_type != DT_DIR) {
1632 continue;
1633 }
1634 std::string_view name = entry->d_name;
1635 if (!name.starts_with(constants().mountKeyPrefix)) {
1636 continue;
1637 }
1638 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001639 continue;
1640 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001641 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001642 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001643 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001644 }
1645 }
1646}
1647
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001648bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001649 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001650 const auto backing = path::join(root, constants().backing);
Songchun Fanf949c372021-04-27 11:26:25 -07001651 std::string mountKey(path::basename(path::dirname(mountTarget)));
Songchun Fan3c82a302019-11-29 14:23:45 -08001652
Songchun Fan3c82a302019-11-29 14:23:45 -08001653 IncrementalFileSystemControlParcel controlParcel;
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001654 auto metricsKey = makeUniqueName(mountKey);
1655 auto status = mVold->mountIncFs(backing, mountTarget, 0, metricsKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001656 if (!status.isOk()) {
1657 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1658 return false;
1659 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001660
1661 int cmd = controlParcel.cmd.release().release();
1662 int pendingReads = controlParcel.pendingReads.release().release();
1663 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001664 int blocksWritten =
1665 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1666 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001667
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001668 auto ifs = std::make_shared<IncFsMount>(std::string(root), std::move(metricsKey), -1,
1669 std::move(control), *this);
Songchun Fan3c82a302019-11-29 14:23:45 -08001670
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001671 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1672 path::join(mountTarget, constants().infoMdName));
1673 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001674 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1675 return false;
1676 }
1677
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001678 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001679 mNextId = std::max(mNextId, ifs->mountId + 1);
1680
Alex Buynytskyy04035452020-06-06 20:15:58 -07001681 // Check if marker file present.
1682 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001683 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001684 }
1685
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001686 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001687 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001688 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001689 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001690 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001691 dataLoaderParams.packageName = loader.package_name();
1692 dataLoaderParams.className = loader.class_name();
1693 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001694 }
1695
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001696 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001697 CHECK(ifs->dataLoaderStub);
1698
Songchun Fan3c82a302019-11-29 14:23:45 -08001699 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001700 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001701 while (auto e = ::readdir(d.get())) {
1702 if (e->d_type == DT_REG) {
1703 auto name = std::string_view(e->d_name);
1704 if (name.starts_with(constants().mountpointMdPrefix)) {
1705 bindPoints.emplace_back(name,
1706 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1707 ifs->control,
1708 path::join(mountTarget,
1709 name)));
1710 if (bindPoints.back().second.dest_path().empty() ||
1711 bindPoints.back().second.source_subdir().empty()) {
1712 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001713 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001714 }
1715 }
1716 } else if (e->d_type == DT_DIR) {
1717 if (e->d_name == "."sv || e->d_name == ".."sv) {
1718 continue;
1719 }
1720 auto name = std::string_view(e->d_name);
1721 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001722 int storageId;
1723 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1724 name.data() + name.size(), storageId);
1725 if (res.ec != std::errc{} || *res.ptr != '_') {
1726 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1727 << root;
1728 continue;
1729 }
1730 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001731 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001732 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001733 << " for mount " << root;
1734 continue;
1735 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001736 ifs->storages.insert_or_assign(storageId,
1737 IncFsMount::Storage{
1738 path::join(root, constants().mount, name)});
1739 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001740 }
1741 }
1742 }
1743
1744 if (ifs->storages.empty()) {
1745 LOG(WARNING) << "No valid storages in mount " << root;
1746 return false;
1747 }
1748
1749 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001750 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001751 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001752 for (auto&& bp : bindPoints) {
1753 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1754 std::move(*bp.second.mutable_source_subdir()),
1755 std::move(*bp.second.mutable_dest_path()),
1756 BindKind::Permanent, l);
1757 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001758 }
1759
1760 if (bindCount == 0) {
1761 LOG(WARNING) << "No valid bind points for mount " << root;
1762 deleteStorage(*ifs);
1763 return false;
1764 }
1765
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001766 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001767 mMounts[ifs->mountId] = std::move(ifs);
1768 return true;
1769}
1770
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001771void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001772 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001773 while (mRunning.load(std::memory_order_relaxed)) {
1774 mLooper->pollAll(kTimeoutMsecs);
1775 }
1776}
1777
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001778void IncrementalService::trimReservedSpaceV1(const IncFsMount& ifs) {
1779 mIncFs->forEachFile(ifs.control, [this](auto&& control, auto&& fileId) {
1780 if (mIncFs->isFileFullyLoaded(control, fileId) == incfs::LoadingState::Full) {
1781 mIncFs->reserveSpace(control, fileId, -1);
1782 }
1783 return true;
1784 });
1785}
1786
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001787void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001788 DataLoaderStatusListener&& statusListener,
1789 const StorageHealthCheckParams& healthCheckParams,
1790 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001791 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001792 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001793 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1794 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1795 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001796 if (ifs.control.blocksWritten() >= 0) {
1797 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1798 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001799 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001800
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001801 ifs.dataLoaderStub =
1802 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001803 std::move(statusListener), healthCheckParams,
1804 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001805
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001806 // pre-v2 IncFS doesn't do automatic reserved space trimming - need to run it manually
1807 if (!(mIncFs->features() & incfs::Features::v2)) {
1808 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1809 if (!state.fullyLoaded) {
1810 return true;
1811 }
1812
1813 const auto ifs = getIfs(storageId);
1814 if (!ifs) {
1815 return false;
1816 }
1817 trimReservedSpaceV1(*ifs);
1818 return false;
1819 });
1820 }
1821
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001822 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1823 if (!state.fullyLoaded || state.readLogsEnabled) {
1824 return true;
1825 }
1826
1827 DataLoaderStubPtr dataLoaderStub;
1828 {
1829 const auto ifs = getIfs(storageId);
1830 if (!ifs) {
1831 return false;
1832 }
1833
1834 std::unique_lock l(ifs->lock);
1835 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1836 }
1837
1838 if (dataLoaderStub) {
1839 dataLoaderStub->cleanupResources();
1840 }
1841
1842 return false;
1843 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001844}
1845
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001846template <class Duration>
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001847static constexpr auto castToMs(Duration d) {
1848 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1849}
1850
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001851// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001852// Lib files should be placed next to the APK file in the following matter:
1853// Example:
1854// /path/to/base.apk
1855// /path/to/lib/arm/first.so
1856// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001857bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1858 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001859 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001860 auto start = Clock::now();
1861
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001862 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001863 if (!ifs) {
1864 LOG(ERROR) << "Invalid storage " << storage;
1865 return false;
1866 }
1867
Songchun Fanc8975312020-07-13 12:14:37 -07001868 const auto targetLibPathRelativeToStorage =
1869 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1870 libDirRelativePath);
1871
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001872 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001873 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1874 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001875 << " errno: " << res;
1876 return false;
1877 }
1878
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001879 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001880 ZipArchiveHandle zipFileHandle;
1881 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001882 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1883 return false;
1884 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001885
1886 // Need a shared pointer: will be passing it into all unpacking jobs.
1887 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001888 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001889 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001890 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001891 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1892 return false;
1893 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001894 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001895 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1896
1897 auto openZipTs = Clock::now();
1898
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001899 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1900 incfs::FileId sourceId;
1901 if (mapFiles) {
1902 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1903 if (!incfs::isValidFileId(sourceId)) {
1904 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1905 << "', mapping disabled";
1906 mapFiles = false;
1907 }
1908 }
1909
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001910 std::vector<Job> jobQueue;
1911 ZipEntry entry;
1912 std::string_view fileName;
1913 while (!Next(cookie, &entry, &fileName)) {
1914 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001915 continue;
1916 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001917
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001918 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001919 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001920
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001921 if (!extractNativeLibs) {
1922 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001923 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001924 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1925 return false;
1926 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001927 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001928 LOG(WARNING) << "Library " << fileName
1929 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1930 << entry.offset;
1931 return false;
1932 }
1933 continue;
1934 }
1935
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001936 auto startFileTs = Clock::now();
1937
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001938 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001939 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001940 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001941 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001942 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001943 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001944 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1945 << "; skipping extraction, spent "
1946 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1947 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001948 continue;
1949 }
1950
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001951 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1952 incfs::NewMappedFileParams mappedFileParams = {
1953 .sourceId = sourceId,
1954 .sourceOffset = entry.offset,
1955 .size = entry.uncompressed_length,
1956 };
1957
1958 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1959 mappedFileParams);
1960 res == 0) {
1961 if (perfLoggingEnabled()) {
1962 auto doneTs = Clock::now();
1963 LOG(INFO) << "incfs: Mapped " << libName << ": "
1964 << elapsedMcs(startFileTs, doneTs) << "mcs";
1965 }
1966 continue;
1967 } else {
1968 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1969 << "; falling back to full extraction";
1970 }
1971 }
1972
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001973 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001974 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001975 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001976 .signature = {},
1977 // Metadata of the new lib file is its relative path
1978 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1979 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001980 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001981 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001982 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001983 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001984 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001985 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001986 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001987
1988 auto makeFileTs = Clock::now();
1989
Songchun Fanafaf6e92020-03-18 14:12:20 -07001990 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001991 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001992 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001993 LOG(INFO) << "incfs: Extracted " << libName
1994 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001995 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001996 continue;
1997 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001998
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001999 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
2000 libFileId, libPath = std::move(targetLibPath),
2001 makeFileTs]() mutable {
2002 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002003 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002004
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002005 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002006 auto prepareJobTs = Clock::now();
2007 LOG(INFO) << "incfs: Processed " << libName << ": "
2008 << elapsedMcs(startFileTs, prepareJobTs)
2009 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
2010 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002011 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002012 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002013
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002014 auto processedTs = Clock::now();
2015
2016 if (!jobQueue.empty()) {
2017 {
2018 std::lock_guard lock(mJobMutex);
2019 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002020 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002021 if (existingJobs.empty()) {
2022 existingJobs = std::move(jobQueue);
2023 } else {
2024 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
2025 std::move_iterator(jobQueue.end()));
2026 }
2027 }
2028 }
2029 mJobCondition.notify_all();
2030 }
2031
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002032 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002033 auto end = Clock::now();
2034 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
2035 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
2036 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002037 << " make files: " << elapsedMcs(openZipTs, processedTs)
2038 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002039 }
2040
2041 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002042}
2043
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002044void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
2045 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002046 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002047 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002048 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002049 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002050 return;
2051 }
2052
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002053 auto startedTs = Clock::now();
2054
2055 // Write extracted data to new file
2056 // NOTE: don't zero-initialize memory, it may take a while for nothing
2057 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
2058 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002059 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002060 return;
2061 }
2062
2063 auto extractFileTs = Clock::now();
2064
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002065 if (setFileContent(ifs, libFileId, debugLibPath,
2066 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002067 return;
2068 }
2069
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002070 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002071 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002072 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
2073 << entry.compressed_length << " -> " << entry.uncompressed_length
2074 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002075 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
2076 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002077 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002078 }
2079}
2080
2081bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002082 struct WaitPrinter {
2083 const Clock::time_point startTs = Clock::now();
2084 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002085 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002086 const auto endTs = Clock::now();
2087 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
2088 << elapsedMcs(startTs, endTs) << "mcs";
2089 }
2090 }
2091 } waitPrinter;
2092
2093 MountId mount;
2094 {
2095 auto ifs = getIfs(storage);
2096 if (!ifs) {
2097 return true;
2098 }
2099 mount = ifs->mountId;
2100 }
2101
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002102 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002103 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002104 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002105 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002106 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002107 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002108}
2109
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002110int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
2111 std::string_view debugFilePath,
2112 std::span<const uint8_t> data) const {
2113 auto startTs = Clock::now();
2114
2115 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2116 if (!writeFd.ok()) {
2117 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2118 << " errno: " << writeFd.get();
2119 return writeFd.get();
2120 }
2121
2122 const auto dataLength = data.size();
2123
2124 auto openFileTs = Clock::now();
2125 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2126 std::vector<IncFsDataBlock> instructions(numBlocks);
2127 for (int i = 0; i < numBlocks; i++) {
2128 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2129 instructions[i] = IncFsDataBlock{
2130 .fileFd = writeFd.get(),
2131 .pageIndex = static_cast<IncFsBlockIndex>(i),
2132 .compression = INCFS_COMPRESSION_KIND_NONE,
2133 .kind = INCFS_BLOCK_KIND_DATA,
2134 .dataSize = static_cast<uint32_t>(blockSize),
2135 .data = reinterpret_cast<const char*>(data.data()),
2136 };
2137 data = data.subspan(blockSize);
2138 }
2139 auto prepareInstsTs = Clock::now();
2140
2141 size_t res = mIncFs->writeBlocks(instructions);
2142 if (res != instructions.size()) {
2143 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2144 return res;
2145 }
2146
2147 if (perfLoggingEnabled()) {
2148 auto endTs = Clock::now();
2149 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2150 << " bytes): " << elapsedMcs(startTs, endTs)
2151 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2152 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2153 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2154 }
2155
2156 return 0;
2157}
2158
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002159incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2160 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002161 std::unique_lock l(mLock);
2162 const auto ifs = getIfsLocked(storage);
2163 if (!ifs) {
2164 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002165 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002166 }
2167 const auto storageInfo = ifs->storages.find(storage);
2168 if (storageInfo == ifs->storages.end()) {
2169 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002170 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002171 }
2172 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002173 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002174}
2175
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002176incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2177 const auto ifs = getIfs(storage);
2178 if (!ifs) {
2179 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2180 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002181 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002182 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002183}
2184
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002185IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002186 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002187 std::unique_lock l(mLock);
2188 const auto ifs = getIfsLocked(storage);
2189 if (!ifs) {
2190 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002191 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002192 }
2193 const auto storageInfo = ifs->storages.find(storage);
2194 if (storageInfo == ifs->storages.end()) {
2195 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002196 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002197 }
2198 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002199 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002200}
2201
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002202IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002203 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002204 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2205 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002206 const auto [filledBlocksCount, totalBlocksCount] =
2207 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002208 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2209 filledBlocksCount == -ENOENT) {
2210 // a kind of a file that's not really being loaded, e.g. a mapped range
2211 // an older IncFS used to return ENOENT in this case, so handle it the same way
2212 return true;
2213 }
Songchun Fan374f7652020-08-20 08:40:29 -07002214 if (filledBlocksCount < 0) {
2215 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002216 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002217 error = filledBlocksCount;
2218 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002219 }
2220 totalBlocks += totalBlocksCount;
2221 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002222 return true;
2223 });
Songchun Fan374f7652020-08-20 08:40:29 -07002224
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002225 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002226}
2227
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002228bool IncrementalService::updateLoadingProgress(StorageId storage,
2229 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002230 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002231 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002232 // Failed to get progress from incfs, abort.
2233 return false;
2234 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002235 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2236 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002237 // Stop updating progress once it is fully loaded
2238 return true;
2239 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002240 addTimedJob(*mProgressUpdateJobQueue, storage,
2241 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002242 [storage, progressListener = std::move(progressListener), this]() mutable {
2243 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002244 });
2245 return true;
2246}
2247
2248bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002249 StorageId storage, StorageLoadingProgressListener progressListener) {
2250 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002251}
2252
2253bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2254 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2255}
2256
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002257bool IncrementalService::perfLoggingEnabled() {
2258 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2259 return enabled;
2260}
2261
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002262void IncrementalService::runJobProcessing() {
2263 for (;;) {
2264 std::unique_lock lock(mJobMutex);
2265 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2266 if (!mRunning) {
2267 return;
2268 }
2269
2270 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002271 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002272 auto queue = std::move(it->second);
2273 mJobQueue.erase(it);
2274 lock.unlock();
2275
2276 for (auto&& job : queue) {
2277 job();
2278 }
2279
2280 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002281 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002282 lock.unlock();
2283 mJobCondition.notify_all();
2284 }
2285}
2286
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002287void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002288 sp<IAppOpsCallback> listener;
2289 {
2290 std::unique_lock lock{mCallbacksLock};
2291 auto& cb = mCallbackRegistered[packageName];
2292 if (cb) {
2293 return;
2294 }
2295 cb = new AppOpsListener(*this, packageName);
2296 listener = cb;
2297 }
2298
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002299 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2300 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002301}
2302
2303bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2304 sp<IAppOpsCallback> listener;
2305 {
2306 std::unique_lock lock{mCallbacksLock};
2307 auto found = mCallbackRegistered.find(packageName);
2308 if (found == mCallbackRegistered.end()) {
2309 return false;
2310 }
2311 listener = found->second;
2312 mCallbackRegistered.erase(found);
2313 }
2314
2315 mAppOpsManager->stopWatchingMode(listener);
2316 return true;
2317}
2318
2319void IncrementalService::onAppOpChanged(const std::string& packageName) {
2320 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002321 return;
2322 }
2323
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002324 std::vector<IfsMountPtr> affected;
2325 {
2326 std::lock_guard l(mLock);
2327 affected.reserve(mMounts.size());
2328 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002329 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002330 if (ifs->mountId == id && ifs->dataLoaderStub &&
2331 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002332 affected.push_back(ifs);
2333 }
2334 }
2335 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002336 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002337 std::unique_lock ll(ifs->lock);
2338 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002339 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002340}
2341
Songchun Fana7098592020-09-03 11:45:53 -07002342bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2343 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002344 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002345 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002346 }
Songchun Fana7098592020-09-03 11:45:53 -07002347 timedQueue.addJob(id, after, std::move(what));
2348 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002349}
2350
Songchun Fana7098592020-09-03 11:45:53 -07002351bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002352 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002353 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002354 }
Songchun Fana7098592020-09-03 11:45:53 -07002355 timedQueue.removeJobs(id);
2356 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002357}
2358
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002359void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2360 bool wasEmpty;
2361 {
2362 std::lock_guard l(mIfsStateCallbacksLock);
2363 wasEmpty = mIfsStateCallbacks.empty();
2364 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2365 }
2366 if (wasEmpty) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002367 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002368 [this]() { processIfsStateCallbacks(); });
2369 }
2370}
2371
2372void IncrementalService::processIfsStateCallbacks() {
2373 StorageId storageId = kInvalidStorageId;
2374 std::vector<IfsStateCallback> local;
2375 while (true) {
2376 {
2377 std::lock_guard l(mIfsStateCallbacksLock);
2378 if (mIfsStateCallbacks.empty()) {
2379 return;
2380 }
2381 IfsStateCallbacks::iterator it;
2382 if (storageId == kInvalidStorageId) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002383 // First entry, initialize the |it|.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002384 it = mIfsStateCallbacks.begin();
2385 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002386 // Subsequent entries, update the |storageId|, and shift to the new one (not that
2387 // it guarantees much about updated items, but at least the loop will finish).
2388 it = mIfsStateCallbacks.lower_bound(storageId);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002389 if (it == mIfsStateCallbacks.end()) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002390 // Nothing else left, too bad.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002391 break;
2392 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002393 if (it->first != storageId) {
2394 local.clear(); // Was removed during processing, forget the old callbacks.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002395 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002396 // Put the 'surviving' callbacks back into the map and advance the position.
2397 auto& callbacks = it->second;
2398 if (callbacks.empty()) {
2399 std::swap(callbacks, local);
2400 } else {
2401 callbacks.insert(callbacks.end(), std::move_iterator(local.begin()),
2402 std::move_iterator(local.end()));
2403 local.clear();
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002404 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002405 if (callbacks.empty()) {
2406 it = mIfsStateCallbacks.erase(it);
2407 if (mIfsStateCallbacks.empty()) {
2408 return;
2409 }
2410 } else {
2411 ++it;
2412 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002413 }
2414 }
2415
2416 if (it == mIfsStateCallbacks.end()) {
2417 break;
2418 }
2419
2420 storageId = it->first;
2421 auto& callbacks = it->second;
2422 if (callbacks.empty()) {
2423 // Invalid case, one extra lookup should be ok.
2424 continue;
2425 }
2426 std::swap(callbacks, local);
2427 }
2428
2429 processIfsStateCallbacks(storageId, local);
2430 }
2431
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002432 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002433 [this]() { processIfsStateCallbacks(); });
2434}
2435
2436void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2437 std::vector<IfsStateCallback>& callbacks) {
2438 const auto state = isMountFullyLoaded(storageId);
2439 IfsState storageState = {};
2440 storageState.error = int(state) < 0;
2441 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2442 if (storageState.fullyLoaded) {
2443 const auto ifs = getIfs(storageId);
2444 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2445 }
2446
2447 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2448 if ((*cur)(storageId, storageState)) {
2449 ++cur;
2450 } else {
2451 cur = callbacks.erase(cur);
2452 }
2453 }
2454}
2455
2456void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2457 std::lock_guard l(mIfsStateCallbacksLock);
2458 mIfsStateCallbacks.erase(storageId);
2459}
2460
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002461void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002462 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002463 if (!ifs) {
Songchun Fan9471be52021-04-21 17:49:27 -07002464 LOG(ERROR) << "getMetrics failed, invalid storageId: " << storageId;
2465 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002466 }
Songchun Fan0dc77722021-05-03 17:13:52 -07002467 const auto& kMetricsReadLogsEnabled =
Songchun Fan9471be52021-04-21 17:49:27 -07002468 os::incremental::BnIncrementalService::METRICS_READ_LOGS_ENABLED();
Songchun Fan0dc77722021-05-03 17:13:52 -07002469 result->putBoolean(String16(kMetricsReadLogsEnabled.c_str()), ifs->readLogsEnabled() != 0);
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07002470 const auto incfsMetrics = mIncFs->getMetrics(ifs->metricsKey);
Songchun Fan0dc77722021-05-03 17:13:52 -07002471 if (incfsMetrics) {
2472 const auto& kMetricsTotalDelayedReads =
2473 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS();
2474 const auto totalDelayedReads =
2475 incfsMetrics->readsDelayedMin + incfsMetrics->readsDelayedPending;
2476 result->putInt(String16(kMetricsTotalDelayedReads.c_str()), totalDelayedReads);
2477 const auto& kMetricsTotalFailedReads =
2478 os::incremental::BnIncrementalService::METRICS_TOTAL_FAILED_READS();
2479 const auto totalFailedReads = incfsMetrics->readsFailedTimedOut +
2480 incfsMetrics->readsFailedHashVerification + incfsMetrics->readsFailedOther;
2481 result->putInt(String16(kMetricsTotalFailedReads.c_str()), totalFailedReads);
2482 const auto& kMetricsTotalDelayedReadsMillis =
2483 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS_MILLIS();
2484 const int64_t totalDelayedReadsMillis =
2485 (incfsMetrics->readsDelayedMinUs + incfsMetrics->readsDelayedPendingUs) / 1000;
2486 result->putLong(String16(kMetricsTotalDelayedReadsMillis.c_str()), totalDelayedReadsMillis);
2487 }
2488 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
2489 if (lastReadError && lastReadError->timestampUs != 0) {
2490 const auto& kMetricsMillisSinceLastReadError =
2491 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_READ_ERROR();
2492 result->putLong(String16(kMetricsMillisSinceLastReadError.c_str()),
2493 (int64_t)elapsedUsSinceMonoTs(lastReadError->timestampUs) / 1000);
2494 const auto& kMetricsLastReadErrorNo =
2495 os::incremental::BnIncrementalService::METRICS_LAST_READ_ERROR_NUMBER();
2496 result->putInt(String16(kMetricsLastReadErrorNo.c_str()), lastReadError->errorNo);
2497 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002498 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002499 if (!ifs->dataLoaderStub) {
Songchun Fan9471be52021-04-21 17:49:27 -07002500 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002501 }
Songchun Fan9471be52021-04-21 17:49:27 -07002502 ifs->dataLoaderStub->getMetrics(result);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002503}
2504
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002505IncrementalService::DataLoaderStub::DataLoaderStub(
2506 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2507 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2508 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2509 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002510 : mService(service),
2511 mId(id),
2512 mParams(std::move(params)),
2513 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002514 mStatusListener(std::move(statusListener)),
2515 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002516 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002517 mHealthCheckParams(healthCheckParams) {
2518 if (mHealthListener && !isHealthParamsValid()) {
2519 mHealthListener = {};
2520 }
2521 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002522 // Disable advanced health check statuses.
2523 mHealthCheckParams.blockedTimeoutMs = -1;
2524 }
2525 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002526}
2527
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002528IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002529 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002530 cleanupResources();
2531 }
2532}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002533
2534void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002535 auto now = Clock::now();
2536 {
2537 std::unique_lock lock(mMutex);
2538 mHealthPath.clear();
2539 unregisterFromPendingReads();
2540 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002541 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002542 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002543 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002544
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002545 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002546
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002547 {
2548 std::unique_lock lock(mMutex);
2549 mParams = {};
2550 mControl = {};
2551 mHealthControl = {};
2552 mHealthListener = {};
2553 mStatusCondition.wait_until(lock, now + 60s, [this] {
2554 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2555 });
2556 mStatusListener = {};
2557 mId = kInvalidStorageId;
2558 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002559}
2560
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002561sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2562 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002563 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002564 if (!status.isOk()) {
2565 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2566 return {};
2567 }
2568 if (!dataloader) {
2569 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2570 return {};
2571 }
2572 return dataloader;
2573}
2574
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002575bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2576 return (params().packageName == Constants::systemPackage);
2577}
2578
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002579bool IncrementalService::DataLoaderStub::requestCreate() {
2580 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2581}
2582
2583bool IncrementalService::DataLoaderStub::requestStart() {
2584 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2585}
2586
2587bool IncrementalService::DataLoaderStub::requestDestroy() {
2588 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2589}
2590
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002591bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002592 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002593 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002594 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002595 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002596 return fsmStep();
2597}
2598
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002599void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002600 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002601 mTargetStatus = status;
2602 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002603 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002604 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002605}
2606
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002607std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002608 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002609
2610 const auto now = mService.mClock->now();
2611 const bool healthy = (mPreviousBindDelay == 0ms);
2612
2613 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2614 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2615 LOG(INFO) << "Binding still in progress. "
2616 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002617 : "Already unhealthy, don't do anything.")
2618 << " for storage " << mId;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002619 // Binding still in progress.
2620 if (!healthy) {
2621 // Already unhealthy, don't do anything.
2622 return {};
2623 }
2624 // The DL is healthy/freshly bound, ok to retry for a few times.
2625 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2626 // Still within grace period.
2627 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2628 // Retry interval passed, retrying.
2629 mCurrentStatusTs = now;
2630 mPreviousBindDelay = 0ms;
2631 return 0ms;
2632 }
2633 return {};
2634 }
2635 // fallthrough, mark as unhealthy, and retry with delay
2636 }
2637
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002638 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002639 mPreviousBindTs = now;
2640
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002641 const auto nonCrashingInterval =
2642 std::max(castToMs(now - previousBindTs - mPreviousBindDelay), 100ms);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002643 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2644 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2645 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002646 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002647 }
2648
2649 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2650 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2651
2652 const auto bindDelayMs =
2653 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2654 maxBindDelayMs)
2655 .count();
2656 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -07002657 // rand() is enough, not worth maintaining a full-blown <rand> object for delay jitter
2658 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - // NOLINT
2659 bindDelayJitterRangeMs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002660 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002661 return mPreviousBindDelay;
2662}
2663
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002664bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002665 const auto maybeBindDelay = needToBind();
2666 if (!maybeBindDelay) {
2667 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2668 return true;
2669 }
2670 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002671 if (bindDelay > 1s) {
2672 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002673 << bindDelay.count() / 1000 << "s"
2674 << " for storage " << mId;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002675 }
2676
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002677 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002678 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2679 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002680 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002681 const bool healthy = (bindDelay == 0ms);
2682 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2683 << (healthy ? ", retrying." : "");
2684
2685 // Internal error, retry for healthy/new DLs.
2686 // Let needToBind migrate it to unhealthy after too many retries.
2687 if (healthy) {
2688 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2689 [this]() { fsmStep(); })) {
2690 // Mark as binding so that we know it's not the DL's fault.
2691 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2692 return true;
2693 }
2694 }
2695
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002696 return false;
2697 }
2698 return true;
2699}
2700
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002701bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002702 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002703 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002704 return false;
2705 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002706 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002707 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002708 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002709 return false;
2710 }
2711 return true;
2712}
2713
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002714bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002715 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002716 if (!dataloader) {
2717 return false;
2718 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002719 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002720 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002721 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002722 return false;
2723 }
2724 return true;
2725}
2726
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002727bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002728 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002729}
2730
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002731bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002732 if (!isValid()) {
2733 return false;
2734 }
2735
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002736 int currentStatus;
2737 int targetStatus;
2738 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002739 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002740 currentStatus = mCurrentStatus;
2741 targetStatus = mTargetStatus;
2742 }
2743
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002744 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002745
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002746 if (currentStatus == targetStatus) {
2747 return true;
2748 }
2749
2750 switch (targetStatus) {
2751 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002752 switch (currentStatus) {
2753 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2754 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2755 return true;
2756 default:
2757 return destroy();
2758 }
2759 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002760 }
2761 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2762 switch (currentStatus) {
2763 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2764 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2765 return start();
2766 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002767 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002768 }
2769 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2770 switch (currentStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002771 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002772 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2773 // Before binding need to make sure we are unbound.
2774 // Otherwise we'll get stuck binding.
2775 return destroy();
2776 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002777 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002778 return bind();
2779 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002780 return create();
2781 }
2782 break;
2783 default:
2784 LOG(ERROR) << "Invalid target status: " << targetStatus
2785 << ", current status: " << currentStatus;
2786 break;
2787 }
2788 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002789}
2790
2791binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002792 if (!isValid()) {
2793 return binder::Status::
2794 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2795 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002796 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002797 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2798 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002799 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2800 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002801 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2802 newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002803 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2804 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2805 [this, newStatus]() { setCurrentStatus(newStatus); });
2806 return binder::Status::ok();
2807 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002808
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002809 setCurrentStatus(newStatus);
2810 return binder::Status::ok();
2811}
2812
2813void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002814 int oldStatus, oldTargetStatus, newTargetStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002815 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002816 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002817 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002818 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002819 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002820 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002821
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002822 oldStatus = mCurrentStatus;
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002823 oldTargetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002824 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002825
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002826 // Change the status.
2827 mCurrentStatus = newStatus;
2828 mCurrentStatusTs = mService.mClock->now();
2829
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002830 switch (mCurrentStatus) {
2831 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2832 // Unavailable, retry.
2833 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2834 break;
2835 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2836 // Unrecoverable, just unbind.
2837 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2838 break;
2839 default:
2840 break;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002841 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002842
2843 newTargetStatus = mTargetStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002844 }
2845
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002846 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002847 << newStatus << " (target " << oldTargetStatus << " -> " << newTargetStatus << ")";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002848
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002849 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002850 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002851 }
2852
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002853 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002854
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002855 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002856}
2857
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002858bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2859 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2860 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002861}
2862
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002863void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002864 int healthStatus) {
2865 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2866 if (healthListener) {
2867 healthListener->onHealthStatus(id(), healthStatus);
2868 }
Songchun Fan9471be52021-04-21 17:49:27 -07002869 mHealthStatus = healthStatus;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002870}
2871
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002872void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2873 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002874
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002875 int healthStatusToReport = -1;
2876 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002877
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002878 {
2879 std::unique_lock lock(mMutex);
2880 unregisterFromPendingReads();
2881
2882 healthListener = mHealthListener;
2883
2884 // Healthcheck depends on timestamp of the oldest pending read.
2885 // 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 -07002886 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2887 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002888 const auto now = Clock::now();
2889 const auto kernelTsUs = getOldestPendingReadTs();
2890 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002891 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2892 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002893 mHealthBase = {now, kernelTsUs};
2894 }
2895
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002896 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2897 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002898 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2899 registerForPendingReads();
2900 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2901 lock.unlock();
2902 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002903 return;
2904 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002905
2906 resetHealthControl();
2907
2908 // Always make sure the data loader is started.
2909 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2910
2911 // Skip any further processing if health check params are invalid.
2912 if (!isHealthParamsValid()) {
2913 LOG(DEBUG) << id()
2914 << ": Skip any further processing if health check params are invalid.";
2915 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2916 lock.unlock();
2917 onHealthStatus(healthListener, healthStatusToReport);
2918 // Triggering data loader start. This is a one-time action.
2919 fsmStep();
2920 return;
2921 }
2922
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002923 // Don't schedule timer job less than 500ms in advance.
2924 static constexpr auto kTolerance = 500ms;
2925
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002926 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2927 const auto unhealthyTimeout =
2928 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2929 const auto unhealthyMonitoring =
2930 std::max(1000ms,
2931 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2932
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002933 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002934
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002935 Milliseconds checkBackAfter;
2936 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002937 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002938 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002939 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002940 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002941 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002942 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002943 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2944 } else {
2945 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002946 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002947 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2948 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002949 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002950 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002951 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2952 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002953 }
2954
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002955 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002956 if (healthStatusToReport != -1) {
2957 onHealthStatus(healthListener, healthStatusToReport);
2958 }
2959
2960 fsmStep();
2961}
2962
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002963Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2964 BootClockTsUs kernelTsUs) {
2965 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2966 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2967 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2968}
2969
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002970const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2971 if (mHealthPath.empty()) {
2972 resetHealthControl();
2973 return mHealthControl;
2974 }
2975 if (mHealthControl.pendingReads() < 0) {
2976 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2977 }
2978 if (mHealthControl.pendingReads() < 0) {
2979 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2980 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2981 << mHealthControl.logs() << ")";
2982 }
2983 return mHealthControl;
2984}
2985
2986void IncrementalService::DataLoaderStub::resetHealthControl() {
2987 mHealthControl = {};
2988}
2989
2990BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2991 auto result = kMaxBootClockTsUs;
2992
2993 const auto& control = initializeHealthControl();
2994 if (control.pendingReads() < 0) {
2995 return result;
2996 }
2997
Songchun Fan6944f1e2020-11-06 15:24:24 -08002998 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002999 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08003000 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003001 // Clear previous pending reads
3002 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003003 return result;
3004 }
3005
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07003006 LOG(DEBUG) << id() << ": pendingReads: fd(" << control.pendingReads() << "), count("
3007 << mLastPendingReads.size() << "), block: " << mLastPendingReads.front().block
3008 << ", time: " << mLastPendingReads.front().bootClockTsUs
3009 << ", uid: " << mLastPendingReads.front().uid;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003010
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003011 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003012}
3013
3014void IncrementalService::DataLoaderStub::registerForPendingReads() {
3015 const auto pendingReadsFd = mHealthControl.pendingReads();
3016 if (pendingReadsFd < 0) {
3017 return;
3018 }
3019
3020 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
3021
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003022 mService.mLooper->addFd(
3023 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
3024 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07003025 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003026 self->updateHealthStatus(/*baseline=*/true);
3027 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003028 },
3029 this);
3030 mService.mLooper->wake();
3031}
3032
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003033BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
3034 auto result = kMaxBootClockTsUs;
3035 for (auto&& pendingRead : mLastPendingReads) {
3036 result = std::min(result, pendingRead.bootClockTsUs);
3037 }
3038 return result;
3039}
3040
Songchun Fan9471be52021-04-21 17:49:27 -07003041void IncrementalService::DataLoaderStub::getMetrics(android::os::PersistableBundle* result) {
3042 const auto duration = elapsedMsSinceOldestPendingRead();
3043 if (duration >= 0) {
Songchun Fan0dc77722021-05-03 17:13:52 -07003044 const auto& kMetricsMillisSinceOldestPendingRead =
Songchun Fan9471be52021-04-21 17:49:27 -07003045 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
Songchun Fan0dc77722021-05-03 17:13:52 -07003046 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.c_str()), duration);
Songchun Fan9471be52021-04-21 17:49:27 -07003047 }
Songchun Fan0dc77722021-05-03 17:13:52 -07003048 const auto& kMetricsStorageHealthStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003049 os::incremental::BnIncrementalService::METRICS_STORAGE_HEALTH_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003050 result->putInt(String16(kMetricsStorageHealthStatusCode.c_str()), mHealthStatus);
3051 const auto& kMetricsDataLoaderStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003052 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003053 result->putInt(String16(kMetricsDataLoaderStatusCode.c_str()), mCurrentStatus);
3054 const auto& kMetricsMillisSinceLastDataLoaderBind =
Songchun Fan9471be52021-04-21 17:49:27 -07003055 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_DATA_LOADER_BIND();
Songchun Fan0dc77722021-05-03 17:13:52 -07003056 result->putLong(String16(kMetricsMillisSinceLastDataLoaderBind.c_str()),
3057 elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000);
3058 const auto& kMetricsDataLoaderBindDelayMillis =
Songchun Fan9471be52021-04-21 17:49:27 -07003059 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_BIND_DELAY_MILLIS();
Songchun Fan0dc77722021-05-03 17:13:52 -07003060 result->putLong(String16(kMetricsDataLoaderBindDelayMillis.c_str()),
3061 mPreviousBindDelay.count());
Songchun Fan9471be52021-04-21 17:49:27 -07003062}
3063
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003064long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
3065 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
3066 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
3067 return 0;
3068 }
3069 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
3070}
3071
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07003072void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003073 const auto pendingReadsFd = mHealthControl.pendingReads();
3074 if (pendingReadsFd < 0) {
3075 return;
3076 }
3077
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003078 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
3079
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003080 mService.mLooper->removeFd(pendingReadsFd);
3081 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003082}
3083
Songchun Fan2570ec02020-10-08 17:22:33 -07003084void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003085 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07003086 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003087 mHealthCheckParams = healthCheckParams;
3088 mHealthListener = std::move(healthListener);
3089 if (!mHealthListener) {
3090 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07003091 }
3092}
3093
Songchun Fan6944f1e2020-11-06 15:24:24 -08003094static std::string toHexString(const RawMetadata& metadata) {
3095 int n = metadata.size();
3096 std::string res(n * 2, '\0');
3097 // Same as incfs::toString(fileId)
3098 static constexpr char kHexChar[] = "0123456789abcdef";
3099 for (int i = 0; i < n; ++i) {
3100 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
3101 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
3102 }
3103 return res;
3104}
3105
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003106void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003107 dprintf(fd, " dataLoader: {\n");
3108 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08003109 dprintf(fd, " currentStatusTs: %lldmcs\n",
3110 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003111 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
3112 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003113 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003114 dprintf(fd, " health: {\n");
3115 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3116 dprintf(fd, " base: %lldmcs (%lld)\n",
3117 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3118 (long long)mHealthBase.kernelTsUs);
3119 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3120 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3121 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3122 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003123 dprintf(fd, " lastPendingReads: \n");
3124 const auto control = mService.mIncFs->openMount(mHealthPath);
3125 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003126 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003127 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3128 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3129 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3130 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3131 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003132 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
Songchun Fan9471be52021-04-21 17:49:27 -07003133 (long long)(elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000000),
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003134 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003135 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003136 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003137 dprintf(fd, " dataLoaderParams: {\n");
3138 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3139 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3140 dprintf(fd, " className: %s\n", params.className.c_str());
3141 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3142 dprintf(fd, " }\n");
3143 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003144}
3145
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003146void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3147 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003148}
3149
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003150binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3151 bool enableReadLogs, int32_t* _aidl_return) {
3152 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3153 return binder::Status::ok();
3154}
3155
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003156FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3157 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3158}
3159
Songchun Fan3c82a302019-11-29 14:23:45 -08003160} // namespace android::incremental