blob: 42c6a8f062de92ff255da7af0811d1d1c2eb976f [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
209std::string makeBindMdName() {
210 static constexpr auto uuidStringSize = 36;
211
212 uuid_t guid;
213 uuid_generate(guid);
214
215 std::string name;
216 const auto prefixSize = constants().mountpointMdPrefix.size();
217 name.reserve(prefixSize + uuidStringSize);
218
219 name = constants().mountpointMdPrefix;
220 name.resize(prefixSize + uuidStringSize);
221 uuid_unparse(guid, name.data() + prefixSize);
222
223 return name;
224}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700225
226static bool checkReadLogsDisabledMarker(std::string_view root) {
227 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
228 struct stat st;
229 return (::stat(markerPath, &st) == 0);
230}
231
Songchun Fan3c82a302019-11-29 14:23:45 -0800232} // namespace
233
234IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700235 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700236 dataLoaderStub->cleanupResources();
237 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700238 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700239 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800240 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
241 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700242 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800243 incrementalService.mVold->unmountIncFs(target);
244 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700245 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800246 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
247 cleanupFilesystem(root);
248}
249
250auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800251 std::string name;
252 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
253 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
254 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800255 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
256 constants().storagePrefix.data(), id, no);
257 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800258 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800259 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800260 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
261 } else if (err != EEXIST) {
262 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
263 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800264 }
265 }
266 nextStorageDirNo = 0;
267 return storages.end();
268}
269
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700270template <class Func>
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700271static auto makeCleanup(Func&& f) requires(!std::is_lvalue_reference_v<Func>) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700272 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700273 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700274 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
275}
276
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700277static auto openDir(const char* dir) {
278 struct DirCloser {
279 void operator()(DIR* d) const noexcept { ::closedir(d); }
280 };
281 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700282}
283
284static auto openDir(std::string_view dir) {
285 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800286}
287
288static int rmDirContent(const char* path) {
289 auto dir = openDir(path);
290 if (!dir) {
291 return -EINVAL;
292 }
293 while (auto entry = ::readdir(dir.get())) {
294 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
295 continue;
296 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700297 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800298 if (entry->d_type == DT_DIR) {
299 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
300 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
301 return err;
302 }
303 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
304 PLOG(WARNING) << "Failed to rmdir " << fullPath;
305 return err;
306 }
307 } else {
308 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
309 PLOG(WARNING) << "Failed to delete " << fullPath;
310 return err;
311 }
312 }
313 }
314 return 0;
315}
316
Songchun Fan3c82a302019-11-29 14:23:45 -0800317void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800318 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800319 ::rmdir(path::join(root, constants().backing).c_str());
320 ::rmdir(path::join(root, constants().mount).c_str());
321 ::rmdir(path::c_str(root));
322}
323
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700324void IncrementalService::IncFsMount::setFlag(StorageFlags flag, bool value) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700325 if (value) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700326 flags |= flag;
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700327 } else {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700328 flags &= ~flag;
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700329 }
330}
331
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800332IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800333 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800334 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800335 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700336 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700337 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700338 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700339 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700340 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700341 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800342 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800343 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700344 CHECK(mVold) << "Vold service is unavailable";
345 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
346 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
347 CHECK(mJni) << "JNI is unavailable";
348 CHECK(mLooper) << "Looper is unavailable";
349 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700350 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700351 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800352 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700353
354 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700355 mJobProcessor = std::thread([this]() {
356 mJni->initializeForCurrentThread();
357 runJobProcessing();
358 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700359 mCmdLooperThread = std::thread([this]() {
360 mJni->initializeForCurrentThread();
361 runCmdLooper();
362 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700363
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700364 const auto mountedRootNames = adoptMountedInstances();
365 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800366}
367
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700368IncrementalService::~IncrementalService() {
369 {
370 std::lock_guard lock(mJobMutex);
371 mRunning = false;
372 }
373 mJobCondition.notify_all();
374 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700375 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700376 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700377 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700378 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700379 // Ensure that mounts are destroyed while the service is still valid.
380 mBindsByPath.clear();
381 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700382}
Songchun Fan3c82a302019-11-29 14:23:45 -0800383
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700384static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800385 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800386 case IncrementalService::BindKind::Temporary:
387 return "Temporary";
388 case IncrementalService::BindKind::Permanent:
389 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800390 }
391}
392
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700393template <class Duration>
Songchun Fan0dc77722021-05-03 17:13:52 -0700394static int64_t elapsedMcs(Duration start, Duration end) {
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700395 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
396}
397
Songchun Fan0dc77722021-05-03 17:13:52 -0700398int64_t IncrementalService::elapsedUsSinceMonoTs(uint64_t monoTsUs) {
399 const auto now = mClock->now();
400 const auto nowUs = static_cast<uint64_t>(
401 duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count());
Songchun Fand48a25e2021-04-30 09:50:58 -0700402 return nowUs - monoTsUs;
403}
404
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800405void IncrementalService::onDump(int fd) {
406 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
407 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
408
409 std::unique_lock l(mLock);
410
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700411 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800412 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700413 std::unique_lock ll(ifs->lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700414 const IncFsMount& mnt = *ifs;
415 dprintf(fd, " [%d]: {\n", id);
416 if (id != mnt.mountId) {
417 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
418 } else {
419 dprintf(fd, " mountId: %d\n", mnt.mountId);
420 dprintf(fd, " root: %s\n", mnt.root.c_str());
Songchun Fanf949c372021-04-27 11:26:25 -0700421 const auto metricsInstanceName = path::basename(ifs->root);
422 dprintf(fd, " metrics instance name: %s\n", path::c_str(metricsInstanceName).get());
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700423 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700424 dprintf(fd, " flags: %d\n", int(mnt.flags));
425 if (mnt.startLoadingTs.time_since_epoch() == Clock::duration::zero()) {
426 dprintf(fd, " not loading\n");
427 } else {
428 dprintf(fd, " startLoading: %llds\n",
429 (long long)(elapsedMcs(mnt.startLoadingTs, Clock::now()) / 1000000));
430 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700431 if (mnt.dataLoaderStub) {
432 mnt.dataLoaderStub->onDump(fd);
433 } else {
434 dprintf(fd, " dataLoader: null\n");
435 }
436 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
437 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700438 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700439 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800440 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700441 }
442 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800443
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700444 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
445 for (auto&& [target, bind] : mnt.bindPoints) {
446 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
447 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
448 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
449 dprintf(fd, " kind: %s\n", toString(bind.kind));
450 }
451 dprintf(fd, " }\n");
Songchun Fanf949c372021-04-27 11:26:25 -0700452
453 dprintf(fd, " incfsMetrics: {\n");
454 const auto incfsMetrics = mIncFs->getMetrics(metricsInstanceName);
455 if (incfsMetrics) {
456 dprintf(fd, " readsDelayedMin: %d\n", incfsMetrics.value().readsDelayedMin);
457 dprintf(fd, " readsDelayedMinUs: %lld\n",
458 (long long)incfsMetrics.value().readsDelayedMinUs);
459 dprintf(fd, " readsDelayedPending: %d\n",
460 incfsMetrics.value().readsDelayedPending);
461 dprintf(fd, " readsDelayedPendingUs: %lld\n",
462 (long long)incfsMetrics.value().readsDelayedPendingUs);
463 dprintf(fd, " readsFailedHashVerification: %d\n",
464 incfsMetrics.value().readsFailedHashVerification);
465 dprintf(fd, " readsFailedOther: %d\n", incfsMetrics.value().readsFailedOther);
466 dprintf(fd, " readsFailedTimedOut: %d\n",
467 incfsMetrics.value().readsFailedTimedOut);
468 } else {
469 dprintf(fd, " Metrics not available. Errno: %d\n", errno);
470 }
471 dprintf(fd, " }\n");
Songchun Fand48a25e2021-04-30 09:50:58 -0700472
473 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
474 const auto errorNo = errno;
475 dprintf(fd, " lastReadError: {\n");
476 if (lastReadError) {
477 if (lastReadError->timestampUs == 0) {
478 dprintf(fd, " No read errors.\n");
479 } else {
480 dprintf(fd, " fileId: %s\n",
481 IncFsWrapper::toString(lastReadError->id).c_str());
482 dprintf(fd, " time: %llu microseconds ago\n",
483 (unsigned long long)elapsedUsSinceMonoTs(lastReadError->timestampUs));
484 dprintf(fd, " blockIndex: %d\n", lastReadError->block);
485 dprintf(fd, " errno: %d\n", lastReadError->errorNo);
486 }
487 } else {
488 dprintf(fd, " Info not available. Errno: %d\n", errorNo);
489 }
490 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800491 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700492 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800493 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700494 dprintf(fd, "}\n");
495 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800496 for (auto&& [target, mountPairIt] : mBindsByPath) {
497 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700498 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
499 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
500 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
501 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800502 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700503 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800504}
505
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800506bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700507 if (!ifs.dataLoaderStub) {
508 return false;
509 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700510 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800511 return true;
512 }
513
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700514 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800515}
516
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700517void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800518 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700519 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800520 }
521
522 std::vector<IfsMountPtr> mounts;
523 {
524 std::lock_guard l(mLock);
525 mounts.reserve(mMounts.size());
526 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700527 std::unique_lock ll(ifs->lock);
528
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800529 if (ifs->mountId != id) {
530 continue;
531 }
532
533 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800534 mounts.push_back(ifs);
535 }
536 }
537 }
538
Alex Buynytskyy69941662020-04-11 21:40:37 -0700539 if (mounts.empty()) {
540 return;
541 }
542
Songchun Fan3c82a302019-11-29 14:23:45 -0800543 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700544 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800545 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700546 std::unique_lock l(ifs->lock);
547 if (ifs->dataLoaderStub) {
548 ifs->dataLoaderStub->requestStart();
549 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800550 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800551 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800552}
553
554auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
555 for (;;) {
556 if (mNextId == kMaxStorageId) {
557 mNextId = 0;
558 }
559 auto id = ++mNextId;
560 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
561 if (inserted) {
562 return it;
563 }
564 }
565}
566
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700567StorageId IncrementalService::createStorage(std::string_view mountPoint,
568 content::pm::DataLoaderParamsParcel dataLoaderParams,
569 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800570 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
571 if (!path::isAbsolute(mountPoint)) {
572 LOG(ERROR) << "path is not absolute: " << mountPoint;
573 return kInvalidStorageId;
574 }
575
576 auto mountNorm = path::normalize(mountPoint);
577 {
578 const auto id = findStorageId(mountNorm);
579 if (id != kInvalidStorageId) {
580 if (options & CreateOptions::OpenExisting) {
581 LOG(INFO) << "Opened existing storage " << id;
582 return id;
583 }
584 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
585 return kInvalidStorageId;
586 }
587 }
588
589 if (!(options & CreateOptions::CreateNew)) {
590 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
591 return kInvalidStorageId;
592 }
593
594 if (!path::isEmptyDir(mountNorm)) {
595 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
596 return kInvalidStorageId;
597 }
598 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
599 if (mountRoot.empty()) {
600 LOG(ERROR) << "Bad mount point";
601 return kInvalidStorageId;
602 }
603 // Make sure the code removes all crap it may create while still failing.
604 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
605 auto firstCleanupOnFailure =
606 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
607
608 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800609 const auto backing = path::join(mountRoot, constants().backing);
610 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800611 return kInvalidStorageId;
612 }
613
Songchun Fan3c82a302019-11-29 14:23:45 -0800614 IncFsMount::Control control;
615 {
616 std::lock_guard l(mMountOperationLock);
617 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800618
619 if (auto err = rmDirContent(backing.c_str())) {
620 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
621 return kInvalidStorageId;
622 }
623 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
624 return kInvalidStorageId;
625 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800626 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
627 return kInvalidStorageId;
628 }
Songchun Fanf949c372021-04-27 11:26:25 -0700629 auto status = mVold->mountIncFs(backing, mountTarget, 0, mountKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800630 if (!status.isOk()) {
631 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
632 return kInvalidStorageId;
633 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800634 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
635 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800636 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
637 return kInvalidStorageId;
638 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800639 int cmd = controlParcel.cmd.release().release();
640 int pendingReads = controlParcel.pendingReads.release().release();
641 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800642 int blocksWritten =
643 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
644 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800645 }
646
647 std::unique_lock l(mLock);
648 const auto mountIt = getStorageSlotLocked();
649 const auto mountId = mountIt->first;
650 l.unlock();
651
652 auto ifs =
653 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
654 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
655 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700656 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800657
658 auto secondCleanup = [this, &l](auto itPtr) {
659 if (!l.owns_lock()) {
660 l.lock();
661 }
662 mMounts.erase(*itPtr);
663 };
664 auto secondCleanupOnFailure =
665 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
666
667 const auto storageIt = ifs->makeStorage(ifs->mountId);
668 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800669 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800670 return kInvalidStorageId;
671 }
672
673 {
674 metadata::Mount m;
675 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700676 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700677 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
678 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
679 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800680 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800681 if (auto err =
682 mIncFs->makeFile(ifs->control,
683 path::join(ifs->root, constants().mount,
684 constants().infoMdName),
685 0777, idFromMetadata(metadata),
686 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800687 LOG(ERROR) << "Saving mount metadata failed: " << -err;
688 return kInvalidStorageId;
689 }
690 }
691
692 const auto bk =
693 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800694 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
695 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800696 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800697 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800698 return kInvalidStorageId;
699 }
700
701 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700702 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800703
Songchun Fan3c82a302019-11-29 14:23:45 -0800704 mountIt->second = std::move(ifs);
705 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700706
Songchun Fan3c82a302019-11-29 14:23:45 -0800707 LOG(INFO) << "created storage " << mountId;
708 return mountId;
709}
710
711StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
712 StorageId linkedStorage,
713 IncrementalService::CreateOptions options) {
714 if (!isValidMountTarget(mountPoint)) {
715 LOG(ERROR) << "Mount point is invalid or missing";
716 return kInvalidStorageId;
717 }
718
719 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700720 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800721 if (!ifs) {
722 LOG(ERROR) << "Ifs unavailable";
723 return kInvalidStorageId;
724 }
725
726 const auto mountIt = getStorageSlotLocked();
727 const auto storageId = mountIt->first;
728 const auto storageIt = ifs->makeStorage(storageId);
729 if (storageIt == ifs->storages.end()) {
730 LOG(ERROR) << "Can't create a new storage";
731 mMounts.erase(mountIt);
732 return kInvalidStorageId;
733 }
734
735 l.unlock();
736
737 const auto bk =
738 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800739 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
740 std::string(storageIt->second.name), path::normalize(mountPoint),
741 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800742 err < 0) {
743 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700744 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
745 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800746 return kInvalidStorageId;
747 }
748
749 mountIt->second = ifs;
750 return storageId;
751}
752
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700753bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700754 content::pm::DataLoaderParamsParcel dataLoaderParams,
755 DataLoaderStatusListener statusListener,
756 const StorageHealthCheckParams& healthCheckParams,
757 StorageHealthListener healthListener,
758 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800759 // Per Uid timeouts.
760 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700761 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800762 }
763
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700764 IfsMountPtr ifs;
765 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800766
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700767 // Re-initialize DataLoader.
768 {
769 ifs = getIfs(storageId);
770 if (!ifs) {
771 return false;
772 }
773
774 std::unique_lock l(ifs->lock);
775 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
776 }
777
778 if (dataLoaderStub) {
779 dataLoaderStub->cleanupResources();
780 dataLoaderStub = {};
781 }
782
783 {
784 std::unique_lock l(ifs->lock);
785 if (ifs->dataLoaderStub) {
786 LOG(INFO) << "Skipped data loader stub creation because it already exists";
787 return false;
788 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700789
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700790 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
791 healthCheckParams, std::move(healthListener));
792 CHECK(ifs->dataLoaderStub);
793 dataLoaderStub = ifs->dataLoaderStub;
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700794
795 // Disable long read timeouts for non-system dataloaders.
796 // To be re-enabled after installation is complete.
797 ifs->setReadTimeoutsRequested(dataLoaderStub->isSystemDataLoader() &&
798 getAlwaysEnableReadTimeoutsForSystemDataLoaders());
799 applyStorageParamsLocked(*ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700800 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800801
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700802 if (dataLoaderStub->isSystemDataLoader() &&
803 !getEnforceReadLogsMaxIntervalForSystemDataLoaders()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700804 // Readlogs from system dataloader (adb) can always be collected.
805 ifs->startLoadingTs = TimePoint::max();
806 } else {
807 // Assign time when installation wants the DL to start streaming.
808 const auto startLoadingTs = mClock->now();
809 ifs->startLoadingTs = startLoadingTs;
810 // Setup a callback to disable the readlogs after max interval.
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700811 addTimedJob(*mTimedQueue, storageId, getReadLogsMaxInterval(),
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700812 [this, storageId, startLoadingTs]() {
813 const auto ifs = getIfs(storageId);
814 if (!ifs) {
815 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
816 << storageId;
817 return;
818 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700819 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700820 if (ifs->startLoadingTs != startLoadingTs) {
821 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
822 "installation?): "
823 << storageId;
824 return;
825 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700826 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700827 });
828 }
829
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800830 return dataLoaderStub->requestStart();
831}
832
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700833void IncrementalService::onInstallationComplete(StorageId storage) {
834 IfsMountPtr ifs = getIfs(storage);
835 if (!ifs) {
836 return;
837 }
838
839 // Always enable long read timeouts after installation is complete.
840 std::unique_lock l(ifs->lock);
841 ifs->setReadTimeoutsRequested(true);
842 applyStorageParamsLocked(*ifs);
843}
844
Songchun Fan3c82a302019-11-29 14:23:45 -0800845IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
846 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700847 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800848}
849
850StorageId IncrementalService::findStorageId(std::string_view path) const {
851 std::lock_guard l(mLock);
852 auto it = findStorageLocked(path);
853 if (it == mBindsByPath.end()) {
854 return kInvalidStorageId;
855 }
856 return it->second->second.storage;
857}
858
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800859void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700860 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700861 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800862 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700863 return;
864 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700865
866 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800867 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700868 return;
869 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800870 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700871
872 const auto metadata = constants().readLogsDisabledMarkerName;
873 if (auto err = mIncFs->makeFile(ifs->control,
874 path::join(ifs->root, constants().mount,
875 constants().readLogsDisabledMarkerName),
876 0777, idFromMetadata(metadata), {})) {
877 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
878 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
879 return;
880 }
881
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700882 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700883}
884
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700885int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
886 const auto ifs = getIfs(storageId);
887 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700888 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700889 return -EINVAL;
890 }
891
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700892 std::string packageName;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700893
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700894 {
895 std::unique_lock l(ifs->lock);
896 if (!enableReadLogs) {
897 return disableReadLogsLocked(*ifs);
898 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700899
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700900 if (!ifs->readLogsAllowed()) {
901 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
902 return -EPERM;
903 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700904
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700905 if (!ifs->dataLoaderStub) {
906 // This should never happen - only DL can call enableReadLogs.
907 LOG(ERROR) << "enableReadLogs failed: invalid state";
908 return -EPERM;
909 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700910
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700911 // Check installation time.
912 const auto now = mClock->now();
913 const auto startLoadingTs = ifs->startLoadingTs;
914 if (startLoadingTs <= now && now - startLoadingTs > getReadLogsMaxInterval()) {
915 LOG(ERROR)
916 << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
917 << storageId;
918 return -EPERM;
919 }
920
921 packageName = ifs->dataLoaderStub->params().packageName;
922 ifs->setReadLogsRequested(true);
923 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700924
925 // Check loader usage stats permission and apop.
926 if (auto status =
927 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
928 !status.isOk()) {
929 LOG(ERROR) << " Permission: " << kLoaderUsageStats
930 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700931 return fromBinderStatus(status);
932 }
933
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700934 // Check multiuser permission.
935 if (auto status =
936 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
937 !status.isOk()) {
938 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
939 << " check failed: " << status.toString8();
940 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700941 }
942
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700943 {
944 std::unique_lock l(ifs->lock);
945 if (!ifs->readLogsRequested()) {
946 return 0;
947 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700948 if (auto status = applyStorageParamsLocked(*ifs); status != 0) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700949 return status;
950 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700951 }
952
953 registerAppOpsCallback(packageName);
954
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700955 return 0;
956}
957
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700958int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700959 ifs.setReadLogsRequested(false);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700960 return applyStorageParamsLocked(ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700961}
962
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700963int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700964 os::incremental::IncrementalFileSystemControlParcel control;
965 control.cmd.reset(dup(ifs.control.cmd()));
966 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700967 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700968 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700969 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700970 }
971
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700972 bool enableReadLogs = ifs.readLogsRequested();
973 bool enableReadTimeouts = ifs.readTimeoutsRequested();
974
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700975 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700976 auto status = mVold->setIncFsMountOptions(control, enableReadLogs, enableReadTimeouts);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800977 if (status.isOk()) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700978 // Store states.
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800979 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700980 ifs.setReadTimeoutsEnabled(enableReadTimeouts);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700981 } else {
982 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800983 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700984 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700985}
986
Songchun Fan3c82a302019-11-29 14:23:45 -0800987void IncrementalService::deleteStorage(StorageId storageId) {
988 const auto ifs = getIfs(storageId);
989 if (!ifs) {
990 return;
991 }
992 deleteStorage(*ifs);
993}
994
995void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
996 std::unique_lock l(ifs.lock);
997 deleteStorageLocked(ifs, std::move(l));
998}
999
1000void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
1001 std::unique_lock<std::mutex>&& ifsLock) {
1002 const auto storages = std::move(ifs.storages);
1003 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
1004 const auto bindPoints = ifs.bindPoints;
1005 ifsLock.unlock();
1006
1007 std::lock_guard l(mLock);
1008 for (auto&& [id, _] : storages) {
1009 if (id != ifs.mountId) {
1010 mMounts.erase(id);
1011 }
1012 }
1013 for (auto&& [path, _] : bindPoints) {
1014 mBindsByPath.erase(path);
1015 }
1016 mMounts.erase(ifs.mountId);
1017}
1018
1019StorageId IncrementalService::openStorage(std::string_view pathInMount) {
1020 if (!path::isAbsolute(pathInMount)) {
1021 return kInvalidStorageId;
1022 }
1023
1024 return findStorageId(path::normalize(pathInMount));
1025}
1026
Songchun Fan3c82a302019-11-29 14:23:45 -08001027IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
1028 std::lock_guard l(mLock);
1029 return getIfsLocked(storage);
1030}
1031
1032const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
1033 auto it = mMounts.find(storage);
1034 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001035 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -07001036 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -08001037 }
1038 return it->second;
1039}
1040
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001041int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
1042 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001043 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001044 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001045 return -EINVAL;
1046 }
1047
1048 const auto ifs = getIfs(storage);
1049 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001050 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001051 return -EINVAL;
1052 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001053
Songchun Fan3c82a302019-11-29 14:23:45 -08001054 std::unique_lock l(ifs->lock);
1055 const auto storageInfo = ifs->storages.find(storage);
1056 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001057 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -08001058 return -EINVAL;
1059 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001060 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001061 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001062 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001063 return -EINVAL;
1064 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001065 l.unlock();
1066 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001067 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
1068 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -08001069}
1070
1071int IncrementalService::unbind(StorageId storage, std::string_view target) {
1072 if (!path::isAbsolute(target)) {
1073 return -EINVAL;
1074 }
1075
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001076 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001077
1078 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
1079 // otherwise there's a chance to unmount something completely unrelated
1080 const auto norm = path::normalize(target);
1081 std::unique_lock l(mLock);
1082 const auto storageIt = mBindsByPath.find(norm);
1083 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
1084 return -EINVAL;
1085 }
1086 const auto bindIt = storageIt->second;
1087 const auto storageId = bindIt->second.storage;
1088 const auto ifs = getIfsLocked(storageId);
1089 if (!ifs) {
1090 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
1091 << " is missing";
1092 return -EFAULT;
1093 }
1094 mBindsByPath.erase(storageIt);
1095 l.unlock();
1096
1097 mVold->unmountIncFs(bindIt->first);
1098 std::unique_lock l2(ifs->lock);
1099 if (ifs->bindPoints.size() <= 1) {
1100 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -07001101 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001102 } else {
1103 const std::string savedFile = std::move(bindIt->second.savedFilename);
1104 ifs->bindPoints.erase(bindIt);
1105 l2.unlock();
1106 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001107 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001108 }
1109 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001110
Songchun Fan3c82a302019-11-29 14:23:45 -08001111 return 0;
1112}
1113
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001114std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001115 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001116 std::string_view path) const {
1117 if (!path::isAbsolute(path)) {
1118 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001119 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001120 auto normPath = path::normalize(path);
1121 if (path::startsWith(normPath, storageIt->second.name)) {
1122 return normPath;
1123 }
1124 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001125 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1126 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001127 return {};
1128 }
1129 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001130}
1131
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001132std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001133 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001134 std::unique_lock l(ifs.lock);
1135 const auto storageInfo = ifs.storages.find(storage);
1136 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001137 return {};
1138 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001139 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001140}
1141
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001142int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001143 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001144 const auto ifs = getIfs(storage);
1145 if (!ifs) {
1146 return -EINVAL;
1147 }
1148 if (data.size() > params.size) {
1149 LOG(ERROR) << "Bad data size - bigger than file size";
1150 return -EINVAL;
1151 }
1152 if (!data.empty() && data.size() != params.size) {
1153 // Writing a page is an irreversible operation, and it can't be updated with additional
1154 // data later. Check that the last written page is complete, or we may break the file.
1155 if (!isPageAligned(data.size())) {
1156 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001157 return -EINVAL;
1158 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001159 }
1160 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1161 if (normPath.empty()) {
1162 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1163 return -EINVAL;
1164 }
1165 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1166 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1167 return err;
1168 }
1169 if (params.size > 0) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001170 if (auto err = mIncFs->reserveSpace(ifs->control, id, params.size)) {
1171 if (err != -EOPNOTSUPP) {
1172 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1173 (void)mIncFs->unlink(ifs->control, normPath);
1174 return err;
1175 } else {
1176 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1177 "may run out of disk later";
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001178 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001179 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001180 if (!data.empty()) {
1181 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001182 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001183 return err;
1184 }
1185 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001186 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001187 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001188}
1189
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001190int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001191 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001192 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001193 if (normPath.empty()) {
1194 return -EINVAL;
1195 }
1196 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001197 }
1198 return -EINVAL;
1199}
1200
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001201int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001202 const auto ifs = getIfs(storageId);
1203 if (!ifs) {
1204 return -EINVAL;
1205 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001206 return makeDirs(*ifs, storageId, path, mode);
1207}
1208
1209int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1210 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001211 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1212 if (normPath.empty()) {
1213 return -EINVAL;
1214 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001215 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001216}
1217
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001218int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1219 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001220 std::unique_lock l(mLock);
1221 auto ifsSrc = getIfsLocked(sourceStorageId);
1222 if (!ifsSrc) {
1223 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001224 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001225 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1226 return -EINVAL;
1227 }
1228 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001229 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1230 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001231 if (normOldPath.empty() || normNewPath.empty()) {
1232 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1233 return -EINVAL;
1234 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001235 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1236 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1237 << " to " << newPath << "[" << normNewPath << "]";
1238 return err;
1239 }
1240 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001241}
1242
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001243int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001244 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001245 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001246 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001247 }
1248 return -EINVAL;
1249}
1250
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001251int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1252 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001253 std::string&& target, BindKind kind,
1254 std::unique_lock<std::mutex>& mainLock) {
1255 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001256 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001257 return -EINVAL;
1258 }
1259
1260 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001261 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001262 if (kind != BindKind::Temporary) {
1263 metadata::BindPoint bp;
1264 bp.set_storage_id(storage);
1265 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001266 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001267 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001268 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001269 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001270 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001271 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1272 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1273 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001274 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001275 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001276 return int(node);
1277 }
1278 }
1279
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001280 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1281 std::move(target), kind, mainLock);
1282 if (res) {
1283 mIncFs->unlink(ifs.control, metadataFullPath);
1284 }
1285 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001286}
1287
1288int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001289 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001290 std::string&& target, BindKind kind,
1291 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001292 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001293 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001294 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001295 if (!status.isOk()) {
1296 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1297 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1298 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1299 : status.serviceSpecificErrorCode() == 0
1300 ? -EFAULT
1301 : status.serviceSpecificErrorCode()
1302 : -EIO;
1303 }
1304 }
1305
1306 if (!mainLock.owns_lock()) {
1307 mainLock.lock();
1308 }
1309 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001310 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1311 std::move(target), kind);
1312 return 0;
1313}
1314
1315void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1316 std::string&& metadataName, std::string&& source,
1317 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001318 const auto [it, _] =
1319 ifs.bindPoints.insert_or_assign(target,
1320 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001321 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001322 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001323}
1324
1325RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1326 const auto ifs = getIfs(storage);
1327 if (!ifs) {
1328 return {};
1329 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001330 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001331 if (normPath.empty()) {
1332 return {};
1333 }
1334 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001335}
1336
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001337RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001338 const auto ifs = getIfs(storage);
1339 if (!ifs) {
1340 return {};
1341 }
1342 return mIncFs->getMetadata(ifs->control, node);
1343}
1344
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001345void IncrementalService::setUidReadTimeouts(StorageId storage,
1346 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001347 using microseconds = std::chrono::microseconds;
1348 using milliseconds = std::chrono::milliseconds;
1349
1350 auto maxPendingTimeUs = microseconds(0);
1351 for (const auto& timeouts : perUidReadTimeouts) {
1352 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1353 }
1354 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07001355 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001356 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1357 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001358 return;
1359 }
1360
1361 const auto ifs = getIfs(storage);
1362 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001363 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001364 return;
1365 }
1366
1367 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1368 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1369 return;
1370 }
1371
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001372 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1373 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1374 if (checkUidReadTimeouts(storageId, state, timeout)) {
1375 return true;
1376 }
1377 clearUidReadTimeouts(storageId);
1378 return false;
1379 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001380}
1381
1382void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1383 const auto ifs = getIfs(storage);
1384 if (!ifs) {
1385 return;
1386 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001387 mIncFs->setUidReadTimeouts(ifs->control, {});
1388}
1389
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001390bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1391 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001392 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001393 // Reached maximum timeout.
1394 return false;
1395 }
1396 if (state.error) {
1397 // Something is wrong, abort.
1398 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001399 }
1400
1401 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001402 if (state.fullyLoaded && !state.readLogsEnabled) {
1403 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001404 }
1405
1406 const auto timeLeft = timeLimit - Clock::now();
1407 if (timeLeft < Constants::progressUpdateInterval) {
1408 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001409 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001410 }
1411
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001412 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001413}
1414
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001415std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1416 std::unordered_set<std::string_view> mountedRootNames;
1417 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1418 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1419 for (auto [source, target] : binds) {
1420 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1421 LOG(INFO) << " " << path::join(root, source);
1422 }
1423
1424 // Ensure it's a kind of a mount that's managed by IncrementalService
1425 if (path::basename(root) != constants().mount ||
1426 path::basename(backingDir) != constants().backing) {
1427 return;
1428 }
1429 const auto expectedRoot = path::dirname(root);
1430 if (path::dirname(backingDir) != expectedRoot) {
1431 return;
1432 }
1433 if (path::dirname(expectedRoot) != mIncrementalDir) {
1434 return;
1435 }
1436 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1437 return;
1438 }
1439
1440 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1441
1442 // make sure we clean up the mount if it happens to be a bad one.
1443 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1444 auto cleanupFiles = makeCleanup([&]() {
1445 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1446 IncFsMount::cleanupFilesystem(expectedRoot);
1447 });
1448 auto cleanupMounts = makeCleanup([&]() {
1449 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1450 for (auto&& [_, target] : binds) {
1451 mVold->unmountIncFs(std::string(target));
1452 }
1453 mVold->unmountIncFs(std::string(root));
1454 });
1455
1456 auto control = mIncFs->openMount(root);
1457 if (!control) {
1458 LOG(INFO) << "failed to open mount " << root;
1459 return;
1460 }
1461
1462 auto mountRecord =
1463 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1464 path::join(root, constants().infoMdName));
1465 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1466 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1467 return;
1468 }
1469
1470 auto mountId = mountRecord.storage().id();
1471 mNextId = std::max(mNextId, mountId + 1);
1472
1473 DataLoaderParamsParcel dataLoaderParams;
1474 {
1475 const auto& loader = mountRecord.loader();
1476 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1477 dataLoaderParams.packageName = loader.package_name();
1478 dataLoaderParams.className = loader.class_name();
1479 dataLoaderParams.arguments = loader.arguments();
1480 }
1481
1482 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1483 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001484 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001485
Alex Buynytskyy04035452020-06-06 20:15:58 -07001486 // Check if marker file present.
1487 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001488 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001489 }
1490
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001491 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1492 auto d = openDir(root);
1493 while (auto e = ::readdir(d.get())) {
1494 if (e->d_type == DT_REG) {
1495 auto name = std::string_view(e->d_name);
1496 if (name.starts_with(constants().mountpointMdPrefix)) {
1497 permanentBindPoints
1498 .emplace_back(name,
1499 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1500 ifs->control,
1501 path::join(root,
1502 name)));
1503 if (permanentBindPoints.back().second.dest_path().empty() ||
1504 permanentBindPoints.back().second.source_subdir().empty()) {
1505 permanentBindPoints.pop_back();
1506 mIncFs->unlink(ifs->control, path::join(root, name));
1507 } else {
1508 LOG(INFO) << "Permanent bind record: '"
1509 << permanentBindPoints.back().second.source_subdir() << "'->'"
1510 << permanentBindPoints.back().second.dest_path() << "'";
1511 }
1512 }
1513 } else if (e->d_type == DT_DIR) {
1514 if (e->d_name == "."sv || e->d_name == ".."sv) {
1515 continue;
1516 }
1517 auto name = std::string_view(e->d_name);
1518 if (name.starts_with(constants().storagePrefix)) {
1519 int storageId;
1520 const auto res =
1521 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1522 name.data() + name.size(), storageId);
1523 if (res.ec != std::errc{} || *res.ptr != '_') {
1524 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1525 << "' for mount " << expectedRoot;
1526 continue;
1527 }
1528 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1529 if (!inserted) {
1530 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1531 << " for mount " << expectedRoot;
1532 continue;
1533 }
1534 ifs->storages.insert_or_assign(storageId,
1535 IncFsMount::Storage{path::join(root, name)});
1536 mNextId = std::max(mNextId, storageId + 1);
1537 }
1538 }
1539 }
1540
1541 if (ifs->storages.empty()) {
1542 LOG(WARNING) << "No valid storages in mount " << root;
1543 return;
1544 }
1545
1546 // now match the mounted directories with what we expect to have in the metadata
1547 {
1548 std::unique_lock l(mLock, std::defer_lock);
1549 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1550 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1551 [&, bindRecord = bindRecord](auto&& bind) {
1552 return bind.second == bindRecord.dest_path() &&
1553 path::join(root, bind.first) ==
1554 bindRecord.source_subdir();
1555 });
1556 if (mountedIt != binds.end()) {
1557 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1558 << " to mount " << mountedIt->first;
1559 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1560 std::move(*bindRecord.mutable_source_subdir()),
1561 std::move(*bindRecord.mutable_dest_path()),
1562 BindKind::Permanent);
1563 if (mountedIt != binds.end() - 1) {
1564 std::iter_swap(mountedIt, binds.end() - 1);
1565 }
1566 binds = binds.first(binds.size() - 1);
1567 } else {
1568 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1569 << ", mounting";
1570 // doesn't exist - try mounting back
1571 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1572 std::move(*bindRecord.mutable_source_subdir()),
1573 std::move(*bindRecord.mutable_dest_path()),
1574 BindKind::Permanent, l)) {
1575 mIncFs->unlink(ifs->control, metadataFile);
1576 }
1577 }
1578 }
1579 }
1580
1581 // if anything stays in |binds| those are probably temporary binds; system restarted since
1582 // they were mounted - so let's unmount them all.
1583 for (auto&& [source, target] : binds) {
1584 if (source.empty()) {
1585 continue;
1586 }
1587 mVold->unmountIncFs(std::string(target));
1588 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001589 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001590
1591 if (ifs->bindPoints.empty()) {
1592 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1593 deleteStorage(*ifs);
1594 return;
1595 }
1596
1597 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1598 CHECK(ifs->dataLoaderStub);
1599
1600 mountedRootNames.insert(path::basename(ifs->root));
1601
1602 // not locking here at all: we're still in the constructor, no other calls can happen
1603 mMounts[ifs->mountId] = std::move(ifs);
1604 });
1605
1606 return mountedRootNames;
1607}
1608
1609void IncrementalService::mountExistingImages(
1610 const std::unordered_set<std::string_view>& mountedRootNames) {
1611 auto dir = openDir(mIncrementalDir);
1612 if (!dir) {
1613 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1614 return;
1615 }
1616 while (auto entry = ::readdir(dir.get())) {
1617 if (entry->d_type != DT_DIR) {
1618 continue;
1619 }
1620 std::string_view name = entry->d_name;
1621 if (!name.starts_with(constants().mountKeyPrefix)) {
1622 continue;
1623 }
1624 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001625 continue;
1626 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001627 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001628 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001629 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001630 }
1631 }
1632}
1633
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001634bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001635 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001636 const auto backing = path::join(root, constants().backing);
Songchun Fanf949c372021-04-27 11:26:25 -07001637 std::string mountKey(path::basename(path::dirname(mountTarget)));
Songchun Fan3c82a302019-11-29 14:23:45 -08001638
Songchun Fan3c82a302019-11-29 14:23:45 -08001639 IncrementalFileSystemControlParcel controlParcel;
Songchun Fanf949c372021-04-27 11:26:25 -07001640 auto status = mVold->mountIncFs(backing, mountTarget, 0, mountKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001641 if (!status.isOk()) {
1642 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1643 return false;
1644 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001645
1646 int cmd = controlParcel.cmd.release().release();
1647 int pendingReads = controlParcel.pendingReads.release().release();
1648 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001649 int blocksWritten =
1650 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1651 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001652
1653 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1654
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001655 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1656 path::join(mountTarget, constants().infoMdName));
1657 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001658 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1659 return false;
1660 }
1661
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001662 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001663 mNextId = std::max(mNextId, ifs->mountId + 1);
1664
Alex Buynytskyy04035452020-06-06 20:15:58 -07001665 // Check if marker file present.
1666 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001667 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001668 }
1669
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001670 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001671 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001672 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001673 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001674 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001675 dataLoaderParams.packageName = loader.package_name();
1676 dataLoaderParams.className = loader.class_name();
1677 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001678 }
1679
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001680 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001681 CHECK(ifs->dataLoaderStub);
1682
Songchun Fan3c82a302019-11-29 14:23:45 -08001683 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001684 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001685 while (auto e = ::readdir(d.get())) {
1686 if (e->d_type == DT_REG) {
1687 auto name = std::string_view(e->d_name);
1688 if (name.starts_with(constants().mountpointMdPrefix)) {
1689 bindPoints.emplace_back(name,
1690 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1691 ifs->control,
1692 path::join(mountTarget,
1693 name)));
1694 if (bindPoints.back().second.dest_path().empty() ||
1695 bindPoints.back().second.source_subdir().empty()) {
1696 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001697 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001698 }
1699 }
1700 } else if (e->d_type == DT_DIR) {
1701 if (e->d_name == "."sv || e->d_name == ".."sv) {
1702 continue;
1703 }
1704 auto name = std::string_view(e->d_name);
1705 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001706 int storageId;
1707 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1708 name.data() + name.size(), storageId);
1709 if (res.ec != std::errc{} || *res.ptr != '_') {
1710 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1711 << root;
1712 continue;
1713 }
1714 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001715 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001716 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001717 << " for mount " << root;
1718 continue;
1719 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001720 ifs->storages.insert_or_assign(storageId,
1721 IncFsMount::Storage{
1722 path::join(root, constants().mount, name)});
1723 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001724 }
1725 }
1726 }
1727
1728 if (ifs->storages.empty()) {
1729 LOG(WARNING) << "No valid storages in mount " << root;
1730 return false;
1731 }
1732
1733 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001734 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001735 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001736 for (auto&& bp : bindPoints) {
1737 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1738 std::move(*bp.second.mutable_source_subdir()),
1739 std::move(*bp.second.mutable_dest_path()),
1740 BindKind::Permanent, l);
1741 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001742 }
1743
1744 if (bindCount == 0) {
1745 LOG(WARNING) << "No valid bind points for mount " << root;
1746 deleteStorage(*ifs);
1747 return false;
1748 }
1749
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001750 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001751 mMounts[ifs->mountId] = std::move(ifs);
1752 return true;
1753}
1754
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001755void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001756 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001757 while (mRunning.load(std::memory_order_relaxed)) {
1758 mLooper->pollAll(kTimeoutMsecs);
1759 }
1760}
1761
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001762void IncrementalService::trimReservedSpaceV1(const IncFsMount& ifs) {
1763 mIncFs->forEachFile(ifs.control, [this](auto&& control, auto&& fileId) {
1764 if (mIncFs->isFileFullyLoaded(control, fileId) == incfs::LoadingState::Full) {
1765 mIncFs->reserveSpace(control, fileId, -1);
1766 }
1767 return true;
1768 });
1769}
1770
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001771void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001772 DataLoaderStatusListener&& statusListener,
1773 const StorageHealthCheckParams& healthCheckParams,
1774 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001775 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001776 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001777 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1778 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1779 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001780 if (ifs.control.blocksWritten() >= 0) {
1781 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1782 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001783 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001784
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001785 ifs.dataLoaderStub =
1786 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001787 std::move(statusListener), healthCheckParams,
1788 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001789
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001790 // pre-v2 IncFS doesn't do automatic reserved space trimming - need to run it manually
1791 if (!(mIncFs->features() & incfs::Features::v2)) {
1792 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1793 if (!state.fullyLoaded) {
1794 return true;
1795 }
1796
1797 const auto ifs = getIfs(storageId);
1798 if (!ifs) {
1799 return false;
1800 }
1801 trimReservedSpaceV1(*ifs);
1802 return false;
1803 });
1804 }
1805
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001806 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1807 if (!state.fullyLoaded || state.readLogsEnabled) {
1808 return true;
1809 }
1810
1811 DataLoaderStubPtr dataLoaderStub;
1812 {
1813 const auto ifs = getIfs(storageId);
1814 if (!ifs) {
1815 return false;
1816 }
1817
1818 std::unique_lock l(ifs->lock);
1819 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1820 }
1821
1822 if (dataLoaderStub) {
1823 dataLoaderStub->cleanupResources();
1824 }
1825
1826 return false;
1827 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001828}
1829
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001830template <class Duration>
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001831static constexpr auto castToMs(Duration d) {
1832 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1833}
1834
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001835// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001836// Lib files should be placed next to the APK file in the following matter:
1837// Example:
1838// /path/to/base.apk
1839// /path/to/lib/arm/first.so
1840// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001841bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1842 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001843 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001844 auto start = Clock::now();
1845
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001846 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001847 if (!ifs) {
1848 LOG(ERROR) << "Invalid storage " << storage;
1849 return false;
1850 }
1851
Songchun Fanc8975312020-07-13 12:14:37 -07001852 const auto targetLibPathRelativeToStorage =
1853 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1854 libDirRelativePath);
1855
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001856 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001857 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1858 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001859 << " errno: " << res;
1860 return false;
1861 }
1862
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001863 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001864 ZipArchiveHandle zipFileHandle;
1865 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001866 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1867 return false;
1868 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001869
1870 // Need a shared pointer: will be passing it into all unpacking jobs.
1871 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001872 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001873 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001874 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001875 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1876 return false;
1877 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001878 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001879 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1880
1881 auto openZipTs = Clock::now();
1882
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001883 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1884 incfs::FileId sourceId;
1885 if (mapFiles) {
1886 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1887 if (!incfs::isValidFileId(sourceId)) {
1888 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1889 << "', mapping disabled";
1890 mapFiles = false;
1891 }
1892 }
1893
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001894 std::vector<Job> jobQueue;
1895 ZipEntry entry;
1896 std::string_view fileName;
1897 while (!Next(cookie, &entry, &fileName)) {
1898 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001899 continue;
1900 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001901
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001902 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001903 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001904
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001905 if (!extractNativeLibs) {
1906 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001907 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001908 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1909 return false;
1910 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001911 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001912 LOG(WARNING) << "Library " << fileName
1913 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1914 << entry.offset;
1915 return false;
1916 }
1917 continue;
1918 }
1919
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001920 auto startFileTs = Clock::now();
1921
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001922 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001923 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001924 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001925 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001926 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001927 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001928 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1929 << "; skipping extraction, spent "
1930 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1931 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001932 continue;
1933 }
1934
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001935 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1936 incfs::NewMappedFileParams mappedFileParams = {
1937 .sourceId = sourceId,
1938 .sourceOffset = entry.offset,
1939 .size = entry.uncompressed_length,
1940 };
1941
1942 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1943 mappedFileParams);
1944 res == 0) {
1945 if (perfLoggingEnabled()) {
1946 auto doneTs = Clock::now();
1947 LOG(INFO) << "incfs: Mapped " << libName << ": "
1948 << elapsedMcs(startFileTs, doneTs) << "mcs";
1949 }
1950 continue;
1951 } else {
1952 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1953 << "; falling back to full extraction";
1954 }
1955 }
1956
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001957 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001958 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001959 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001960 .signature = {},
1961 // Metadata of the new lib file is its relative path
1962 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1963 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001964 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001965 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001966 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001967 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001968 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001969 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001970 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001971
1972 auto makeFileTs = Clock::now();
1973
Songchun Fanafaf6e92020-03-18 14:12:20 -07001974 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001975 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001976 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001977 LOG(INFO) << "incfs: Extracted " << libName
1978 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001979 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001980 continue;
1981 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001982
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001983 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1984 libFileId, libPath = std::move(targetLibPath),
1985 makeFileTs]() mutable {
1986 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001987 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001988
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001989 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001990 auto prepareJobTs = Clock::now();
1991 LOG(INFO) << "incfs: Processed " << libName << ": "
1992 << elapsedMcs(startFileTs, prepareJobTs)
1993 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1994 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001995 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001996 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001997
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001998 auto processedTs = Clock::now();
1999
2000 if (!jobQueue.empty()) {
2001 {
2002 std::lock_guard lock(mJobMutex);
2003 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002004 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002005 if (existingJobs.empty()) {
2006 existingJobs = std::move(jobQueue);
2007 } else {
2008 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
2009 std::move_iterator(jobQueue.end()));
2010 }
2011 }
2012 }
2013 mJobCondition.notify_all();
2014 }
2015
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002016 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002017 auto end = Clock::now();
2018 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
2019 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
2020 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002021 << " make files: " << elapsedMcs(openZipTs, processedTs)
2022 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002023 }
2024
2025 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002026}
2027
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002028void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
2029 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002030 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002031 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002032 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002033 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002034 return;
2035 }
2036
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002037 auto startedTs = Clock::now();
2038
2039 // Write extracted data to new file
2040 // NOTE: don't zero-initialize memory, it may take a while for nothing
2041 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
2042 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002043 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002044 return;
2045 }
2046
2047 auto extractFileTs = Clock::now();
2048
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002049 if (setFileContent(ifs, libFileId, debugLibPath,
2050 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002051 return;
2052 }
2053
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002054 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002055 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002056 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
2057 << entry.compressed_length << " -> " << entry.uncompressed_length
2058 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002059 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
2060 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002061 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002062 }
2063}
2064
2065bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002066 struct WaitPrinter {
2067 const Clock::time_point startTs = Clock::now();
2068 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002069 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002070 const auto endTs = Clock::now();
2071 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
2072 << elapsedMcs(startTs, endTs) << "mcs";
2073 }
2074 }
2075 } waitPrinter;
2076
2077 MountId mount;
2078 {
2079 auto ifs = getIfs(storage);
2080 if (!ifs) {
2081 return true;
2082 }
2083 mount = ifs->mountId;
2084 }
2085
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002086 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002087 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002088 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002089 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002090 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002091 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002092}
2093
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002094int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
2095 std::string_view debugFilePath,
2096 std::span<const uint8_t> data) const {
2097 auto startTs = Clock::now();
2098
2099 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2100 if (!writeFd.ok()) {
2101 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2102 << " errno: " << writeFd.get();
2103 return writeFd.get();
2104 }
2105
2106 const auto dataLength = data.size();
2107
2108 auto openFileTs = Clock::now();
2109 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2110 std::vector<IncFsDataBlock> instructions(numBlocks);
2111 for (int i = 0; i < numBlocks; i++) {
2112 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2113 instructions[i] = IncFsDataBlock{
2114 .fileFd = writeFd.get(),
2115 .pageIndex = static_cast<IncFsBlockIndex>(i),
2116 .compression = INCFS_COMPRESSION_KIND_NONE,
2117 .kind = INCFS_BLOCK_KIND_DATA,
2118 .dataSize = static_cast<uint32_t>(blockSize),
2119 .data = reinterpret_cast<const char*>(data.data()),
2120 };
2121 data = data.subspan(blockSize);
2122 }
2123 auto prepareInstsTs = Clock::now();
2124
2125 size_t res = mIncFs->writeBlocks(instructions);
2126 if (res != instructions.size()) {
2127 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2128 return res;
2129 }
2130
2131 if (perfLoggingEnabled()) {
2132 auto endTs = Clock::now();
2133 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2134 << " bytes): " << elapsedMcs(startTs, endTs)
2135 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2136 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2137 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2138 }
2139
2140 return 0;
2141}
2142
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002143incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2144 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002145 std::unique_lock l(mLock);
2146 const auto ifs = getIfsLocked(storage);
2147 if (!ifs) {
2148 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002149 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002150 }
2151 const auto storageInfo = ifs->storages.find(storage);
2152 if (storageInfo == ifs->storages.end()) {
2153 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002154 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002155 }
2156 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002157 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002158}
2159
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002160incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2161 const auto ifs = getIfs(storage);
2162 if (!ifs) {
2163 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2164 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002165 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002166 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002167}
2168
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002169IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002170 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002171 std::unique_lock l(mLock);
2172 const auto ifs = getIfsLocked(storage);
2173 if (!ifs) {
2174 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002175 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002176 }
2177 const auto storageInfo = ifs->storages.find(storage);
2178 if (storageInfo == ifs->storages.end()) {
2179 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002180 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002181 }
2182 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002183 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002184}
2185
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002186IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002187 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002188 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2189 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002190 const auto [filledBlocksCount, totalBlocksCount] =
2191 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002192 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2193 filledBlocksCount == -ENOENT) {
2194 // a kind of a file that's not really being loaded, e.g. a mapped range
2195 // an older IncFS used to return ENOENT in this case, so handle it the same way
2196 return true;
2197 }
Songchun Fan374f7652020-08-20 08:40:29 -07002198 if (filledBlocksCount < 0) {
2199 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002200 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002201 error = filledBlocksCount;
2202 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002203 }
2204 totalBlocks += totalBlocksCount;
2205 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002206 return true;
2207 });
Songchun Fan374f7652020-08-20 08:40:29 -07002208
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002209 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002210}
2211
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002212bool IncrementalService::updateLoadingProgress(StorageId storage,
2213 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002214 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002215 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002216 // Failed to get progress from incfs, abort.
2217 return false;
2218 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002219 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2220 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002221 // Stop updating progress once it is fully loaded
2222 return true;
2223 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002224 addTimedJob(*mProgressUpdateJobQueue, storage,
2225 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002226 [storage, progressListener = std::move(progressListener), this]() mutable {
2227 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002228 });
2229 return true;
2230}
2231
2232bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002233 StorageId storage, StorageLoadingProgressListener progressListener) {
2234 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002235}
2236
2237bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2238 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2239}
2240
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002241bool IncrementalService::perfLoggingEnabled() {
2242 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2243 return enabled;
2244}
2245
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002246void IncrementalService::runJobProcessing() {
2247 for (;;) {
2248 std::unique_lock lock(mJobMutex);
2249 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2250 if (!mRunning) {
2251 return;
2252 }
2253
2254 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002255 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002256 auto queue = std::move(it->second);
2257 mJobQueue.erase(it);
2258 lock.unlock();
2259
2260 for (auto&& job : queue) {
2261 job();
2262 }
2263
2264 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002265 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002266 lock.unlock();
2267 mJobCondition.notify_all();
2268 }
2269}
2270
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002271void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002272 sp<IAppOpsCallback> listener;
2273 {
2274 std::unique_lock lock{mCallbacksLock};
2275 auto& cb = mCallbackRegistered[packageName];
2276 if (cb) {
2277 return;
2278 }
2279 cb = new AppOpsListener(*this, packageName);
2280 listener = cb;
2281 }
2282
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002283 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2284 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002285}
2286
2287bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2288 sp<IAppOpsCallback> listener;
2289 {
2290 std::unique_lock lock{mCallbacksLock};
2291 auto found = mCallbackRegistered.find(packageName);
2292 if (found == mCallbackRegistered.end()) {
2293 return false;
2294 }
2295 listener = found->second;
2296 mCallbackRegistered.erase(found);
2297 }
2298
2299 mAppOpsManager->stopWatchingMode(listener);
2300 return true;
2301}
2302
2303void IncrementalService::onAppOpChanged(const std::string& packageName) {
2304 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002305 return;
2306 }
2307
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002308 std::vector<IfsMountPtr> affected;
2309 {
2310 std::lock_guard l(mLock);
2311 affected.reserve(mMounts.size());
2312 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002313 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002314 if (ifs->mountId == id && ifs->dataLoaderStub &&
2315 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002316 affected.push_back(ifs);
2317 }
2318 }
2319 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002320 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002321 std::unique_lock ll(ifs->lock);
2322 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002323 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002324}
2325
Songchun Fana7098592020-09-03 11:45:53 -07002326bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2327 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002328 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002329 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002330 }
Songchun Fana7098592020-09-03 11:45:53 -07002331 timedQueue.addJob(id, after, std::move(what));
2332 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002333}
2334
Songchun Fana7098592020-09-03 11:45:53 -07002335bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002336 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002337 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002338 }
Songchun Fana7098592020-09-03 11:45:53 -07002339 timedQueue.removeJobs(id);
2340 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002341}
2342
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002343void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2344 bool wasEmpty;
2345 {
2346 std::lock_guard l(mIfsStateCallbacksLock);
2347 wasEmpty = mIfsStateCallbacks.empty();
2348 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2349 }
2350 if (wasEmpty) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002351 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002352 [this]() { processIfsStateCallbacks(); });
2353 }
2354}
2355
2356void IncrementalService::processIfsStateCallbacks() {
2357 StorageId storageId = kInvalidStorageId;
2358 std::vector<IfsStateCallback> local;
2359 while (true) {
2360 {
2361 std::lock_guard l(mIfsStateCallbacksLock);
2362 if (mIfsStateCallbacks.empty()) {
2363 return;
2364 }
2365 IfsStateCallbacks::iterator it;
2366 if (storageId == kInvalidStorageId) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002367 // First entry, initialize the |it|.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002368 it = mIfsStateCallbacks.begin();
2369 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002370 // Subsequent entries, update the |storageId|, and shift to the new one (not that
2371 // it guarantees much about updated items, but at least the loop will finish).
2372 it = mIfsStateCallbacks.lower_bound(storageId);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002373 if (it == mIfsStateCallbacks.end()) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002374 // Nothing else left, too bad.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002375 break;
2376 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002377 if (it->first != storageId) {
2378 local.clear(); // Was removed during processing, forget the old callbacks.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002379 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002380 // Put the 'surviving' callbacks back into the map and advance the position.
2381 auto& callbacks = it->second;
2382 if (callbacks.empty()) {
2383 std::swap(callbacks, local);
2384 } else {
2385 callbacks.insert(callbacks.end(), std::move_iterator(local.begin()),
2386 std::move_iterator(local.end()));
2387 local.clear();
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002388 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002389 if (callbacks.empty()) {
2390 it = mIfsStateCallbacks.erase(it);
2391 if (mIfsStateCallbacks.empty()) {
2392 return;
2393 }
2394 } else {
2395 ++it;
2396 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002397 }
2398 }
2399
2400 if (it == mIfsStateCallbacks.end()) {
2401 break;
2402 }
2403
2404 storageId = it->first;
2405 auto& callbacks = it->second;
2406 if (callbacks.empty()) {
2407 // Invalid case, one extra lookup should be ok.
2408 continue;
2409 }
2410 std::swap(callbacks, local);
2411 }
2412
2413 processIfsStateCallbacks(storageId, local);
2414 }
2415
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002416 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002417 [this]() { processIfsStateCallbacks(); });
2418}
2419
2420void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2421 std::vector<IfsStateCallback>& callbacks) {
2422 const auto state = isMountFullyLoaded(storageId);
2423 IfsState storageState = {};
2424 storageState.error = int(state) < 0;
2425 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2426 if (storageState.fullyLoaded) {
2427 const auto ifs = getIfs(storageId);
2428 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2429 }
2430
2431 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2432 if ((*cur)(storageId, storageState)) {
2433 ++cur;
2434 } else {
2435 cur = callbacks.erase(cur);
2436 }
2437 }
2438}
2439
2440void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2441 std::lock_guard l(mIfsStateCallbacksLock);
2442 mIfsStateCallbacks.erase(storageId);
2443}
2444
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002445void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002446 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002447 if (!ifs) {
Songchun Fan9471be52021-04-21 17:49:27 -07002448 LOG(ERROR) << "getMetrics failed, invalid storageId: " << storageId;
2449 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002450 }
Songchun Fan0dc77722021-05-03 17:13:52 -07002451 const auto& kMetricsReadLogsEnabled =
Songchun Fan9471be52021-04-21 17:49:27 -07002452 os::incremental::BnIncrementalService::METRICS_READ_LOGS_ENABLED();
Songchun Fan0dc77722021-05-03 17:13:52 -07002453 result->putBoolean(String16(kMetricsReadLogsEnabled.c_str()), ifs->readLogsEnabled() != 0);
2454 const auto incfsMetrics = mIncFs->getMetrics(path::basename(ifs->root));
2455 if (incfsMetrics) {
2456 const auto& kMetricsTotalDelayedReads =
2457 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS();
2458 const auto totalDelayedReads =
2459 incfsMetrics->readsDelayedMin + incfsMetrics->readsDelayedPending;
2460 result->putInt(String16(kMetricsTotalDelayedReads.c_str()), totalDelayedReads);
2461 const auto& kMetricsTotalFailedReads =
2462 os::incremental::BnIncrementalService::METRICS_TOTAL_FAILED_READS();
2463 const auto totalFailedReads = incfsMetrics->readsFailedTimedOut +
2464 incfsMetrics->readsFailedHashVerification + incfsMetrics->readsFailedOther;
2465 result->putInt(String16(kMetricsTotalFailedReads.c_str()), totalFailedReads);
2466 const auto& kMetricsTotalDelayedReadsMillis =
2467 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS_MILLIS();
2468 const int64_t totalDelayedReadsMillis =
2469 (incfsMetrics->readsDelayedMinUs + incfsMetrics->readsDelayedPendingUs) / 1000;
2470 result->putLong(String16(kMetricsTotalDelayedReadsMillis.c_str()), totalDelayedReadsMillis);
2471 }
2472 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
2473 if (lastReadError && lastReadError->timestampUs != 0) {
2474 const auto& kMetricsMillisSinceLastReadError =
2475 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_READ_ERROR();
2476 result->putLong(String16(kMetricsMillisSinceLastReadError.c_str()),
2477 (int64_t)elapsedUsSinceMonoTs(lastReadError->timestampUs) / 1000);
2478 const auto& kMetricsLastReadErrorNo =
2479 os::incremental::BnIncrementalService::METRICS_LAST_READ_ERROR_NUMBER();
2480 result->putInt(String16(kMetricsLastReadErrorNo.c_str()), lastReadError->errorNo);
2481 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002482 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002483 if (!ifs->dataLoaderStub) {
Songchun Fan9471be52021-04-21 17:49:27 -07002484 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002485 }
Songchun Fan9471be52021-04-21 17:49:27 -07002486 ifs->dataLoaderStub->getMetrics(result);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002487}
2488
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002489IncrementalService::DataLoaderStub::DataLoaderStub(
2490 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2491 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2492 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2493 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002494 : mService(service),
2495 mId(id),
2496 mParams(std::move(params)),
2497 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002498 mStatusListener(std::move(statusListener)),
2499 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002500 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002501 mHealthCheckParams(healthCheckParams) {
2502 if (mHealthListener && !isHealthParamsValid()) {
2503 mHealthListener = {};
2504 }
2505 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002506 // Disable advanced health check statuses.
2507 mHealthCheckParams.blockedTimeoutMs = -1;
2508 }
2509 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002510}
2511
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002512IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002513 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002514 cleanupResources();
2515 }
2516}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002517
2518void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002519 auto now = Clock::now();
2520 {
2521 std::unique_lock lock(mMutex);
2522 mHealthPath.clear();
2523 unregisterFromPendingReads();
2524 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002525 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002526 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002527 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002528
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002529 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002530
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002531 {
2532 std::unique_lock lock(mMutex);
2533 mParams = {};
2534 mControl = {};
2535 mHealthControl = {};
2536 mHealthListener = {};
2537 mStatusCondition.wait_until(lock, now + 60s, [this] {
2538 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2539 });
2540 mStatusListener = {};
2541 mId = kInvalidStorageId;
2542 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002543}
2544
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002545sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2546 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002547 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002548 if (!status.isOk()) {
2549 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2550 return {};
2551 }
2552 if (!dataloader) {
2553 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2554 return {};
2555 }
2556 return dataloader;
2557}
2558
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002559bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2560 return (params().packageName == Constants::systemPackage);
2561}
2562
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002563bool IncrementalService::DataLoaderStub::requestCreate() {
2564 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2565}
2566
2567bool IncrementalService::DataLoaderStub::requestStart() {
2568 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2569}
2570
2571bool IncrementalService::DataLoaderStub::requestDestroy() {
2572 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2573}
2574
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002575bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002576 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002577 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002578 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002579 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002580 return fsmStep();
2581}
2582
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002583void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002584 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002585 mTargetStatus = status;
2586 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002587 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002588 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002589}
2590
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002591std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002592 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002593
2594 const auto now = mService.mClock->now();
2595 const bool healthy = (mPreviousBindDelay == 0ms);
2596
2597 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2598 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2599 LOG(INFO) << "Binding still in progress. "
2600 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002601 : "Already unhealthy, don't do anything.")
2602 << " for storage " << mId;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002603 // Binding still in progress.
2604 if (!healthy) {
2605 // Already unhealthy, don't do anything.
2606 return {};
2607 }
2608 // The DL is healthy/freshly bound, ok to retry for a few times.
2609 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2610 // Still within grace period.
2611 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2612 // Retry interval passed, retrying.
2613 mCurrentStatusTs = now;
2614 mPreviousBindDelay = 0ms;
2615 return 0ms;
2616 }
2617 return {};
2618 }
2619 // fallthrough, mark as unhealthy, and retry with delay
2620 }
2621
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002622 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002623 mPreviousBindTs = now;
2624
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002625 const auto nonCrashingInterval =
2626 std::max(castToMs(now - previousBindTs - mPreviousBindDelay), 100ms);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002627 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2628 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2629 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002630 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002631 }
2632
2633 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2634 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2635
2636 const auto bindDelayMs =
2637 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2638 maxBindDelayMs)
2639 .count();
2640 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2641 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2642 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002643 return mPreviousBindDelay;
2644}
2645
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002646bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002647 const auto maybeBindDelay = needToBind();
2648 if (!maybeBindDelay) {
2649 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2650 return true;
2651 }
2652 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002653 if (bindDelay > 1s) {
2654 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002655 << bindDelay.count() / 1000 << "s"
2656 << " for storage " << mId;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002657 }
2658
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002659 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002660 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2661 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002662 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002663 const bool healthy = (bindDelay == 0ms);
2664 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2665 << (healthy ? ", retrying." : "");
2666
2667 // Internal error, retry for healthy/new DLs.
2668 // Let needToBind migrate it to unhealthy after too many retries.
2669 if (healthy) {
2670 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2671 [this]() { fsmStep(); })) {
2672 // Mark as binding so that we know it's not the DL's fault.
2673 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2674 return true;
2675 }
2676 }
2677
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002678 return false;
2679 }
2680 return true;
2681}
2682
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002683bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002684 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002685 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002686 return false;
2687 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002688 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002689 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002690 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002691 return false;
2692 }
2693 return true;
2694}
2695
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002696bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002697 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002698 if (!dataloader) {
2699 return false;
2700 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002701 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002702 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002703 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002704 return false;
2705 }
2706 return true;
2707}
2708
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002709bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002710 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002711}
2712
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002713bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002714 if (!isValid()) {
2715 return false;
2716 }
2717
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002718 int currentStatus;
2719 int targetStatus;
2720 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002721 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002722 currentStatus = mCurrentStatus;
2723 targetStatus = mTargetStatus;
2724 }
2725
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002726 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002727
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002728 if (currentStatus == targetStatus) {
2729 return true;
2730 }
2731
2732 switch (targetStatus) {
2733 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002734 switch (currentStatus) {
2735 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2736 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2737 return true;
2738 default:
2739 return destroy();
2740 }
2741 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002742 }
2743 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2744 switch (currentStatus) {
2745 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2746 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2747 return start();
2748 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002749 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002750 }
2751 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2752 switch (currentStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002753 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002754 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2755 // Before binding need to make sure we are unbound.
2756 // Otherwise we'll get stuck binding.
2757 return destroy();
2758 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002759 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002760 return bind();
2761 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002762 return create();
2763 }
2764 break;
2765 default:
2766 LOG(ERROR) << "Invalid target status: " << targetStatus
2767 << ", current status: " << currentStatus;
2768 break;
2769 }
2770 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002771}
2772
2773binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002774 if (!isValid()) {
2775 return binder::Status::
2776 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2777 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002778 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002779 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2780 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002781 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2782 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002783 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2784 newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002785 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2786 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2787 [this, newStatus]() { setCurrentStatus(newStatus); });
2788 return binder::Status::ok();
2789 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002790
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002791 setCurrentStatus(newStatus);
2792 return binder::Status::ok();
2793}
2794
2795void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002796 int oldStatus, oldTargetStatus, newTargetStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002797 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002798 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002799 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002800 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002801 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002802 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002803
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002804 oldStatus = mCurrentStatus;
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002805 oldTargetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002806 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002807
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002808 // Change the status.
2809 mCurrentStatus = newStatus;
2810 mCurrentStatusTs = mService.mClock->now();
2811
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002812 switch (mCurrentStatus) {
2813 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2814 // Unavailable, retry.
2815 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2816 break;
2817 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2818 // Unrecoverable, just unbind.
2819 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2820 break;
2821 default:
2822 break;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002823 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002824
2825 newTargetStatus = mTargetStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002826 }
2827
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002828 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002829 << newStatus << " (target " << oldTargetStatus << " -> " << newTargetStatus << ")";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002830
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002831 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002832 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002833 }
2834
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002835 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002836
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002837 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002838}
2839
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002840bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2841 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2842 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002843}
2844
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002845void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002846 int healthStatus) {
2847 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2848 if (healthListener) {
2849 healthListener->onHealthStatus(id(), healthStatus);
2850 }
Songchun Fan9471be52021-04-21 17:49:27 -07002851 mHealthStatus = healthStatus;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002852}
2853
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002854void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2855 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002856
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002857 int healthStatusToReport = -1;
2858 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002859
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002860 {
2861 std::unique_lock lock(mMutex);
2862 unregisterFromPendingReads();
2863
2864 healthListener = mHealthListener;
2865
2866 // Healthcheck depends on timestamp of the oldest pending read.
2867 // 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 -07002868 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2869 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002870 const auto now = Clock::now();
2871 const auto kernelTsUs = getOldestPendingReadTs();
2872 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002873 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2874 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002875 mHealthBase = {now, kernelTsUs};
2876 }
2877
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002878 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2879 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002880 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2881 registerForPendingReads();
2882 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2883 lock.unlock();
2884 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002885 return;
2886 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002887
2888 resetHealthControl();
2889
2890 // Always make sure the data loader is started.
2891 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2892
2893 // Skip any further processing if health check params are invalid.
2894 if (!isHealthParamsValid()) {
2895 LOG(DEBUG) << id()
2896 << ": Skip any further processing if health check params are invalid.";
2897 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2898 lock.unlock();
2899 onHealthStatus(healthListener, healthStatusToReport);
2900 // Triggering data loader start. This is a one-time action.
2901 fsmStep();
2902 return;
2903 }
2904
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002905 // Don't schedule timer job less than 500ms in advance.
2906 static constexpr auto kTolerance = 500ms;
2907
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002908 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2909 const auto unhealthyTimeout =
2910 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2911 const auto unhealthyMonitoring =
2912 std::max(1000ms,
2913 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2914
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002915 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002916
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002917 Milliseconds checkBackAfter;
2918 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002919 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002920 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002921 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002922 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002923 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002924 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002925 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2926 } else {
2927 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002928 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002929 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2930 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002931 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002932 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002933 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2934 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002935 }
2936
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002937 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002938 if (healthStatusToReport != -1) {
2939 onHealthStatus(healthListener, healthStatusToReport);
2940 }
2941
2942 fsmStep();
2943}
2944
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002945Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2946 BootClockTsUs kernelTsUs) {
2947 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2948 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2949 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2950}
2951
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002952const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2953 if (mHealthPath.empty()) {
2954 resetHealthControl();
2955 return mHealthControl;
2956 }
2957 if (mHealthControl.pendingReads() < 0) {
2958 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2959 }
2960 if (mHealthControl.pendingReads() < 0) {
2961 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2962 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2963 << mHealthControl.logs() << ")";
2964 }
2965 return mHealthControl;
2966}
2967
2968void IncrementalService::DataLoaderStub::resetHealthControl() {
2969 mHealthControl = {};
2970}
2971
2972BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2973 auto result = kMaxBootClockTsUs;
2974
2975 const auto& control = initializeHealthControl();
2976 if (control.pendingReads() < 0) {
2977 return result;
2978 }
2979
Songchun Fan6944f1e2020-11-06 15:24:24 -08002980 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002981 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002982 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002983 // Clear previous pending reads
2984 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002985 return result;
2986 }
2987
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07002988 LOG(DEBUG) << id() << ": pendingReads: fd(" << control.pendingReads() << "), count("
2989 << mLastPendingReads.size() << "), block: " << mLastPendingReads.front().block
2990 << ", time: " << mLastPendingReads.front().bootClockTsUs
2991 << ", uid: " << mLastPendingReads.front().uid;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002992
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002993 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002994}
2995
2996void IncrementalService::DataLoaderStub::registerForPendingReads() {
2997 const auto pendingReadsFd = mHealthControl.pendingReads();
2998 if (pendingReadsFd < 0) {
2999 return;
3000 }
3001
3002 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
3003
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003004 mService.mLooper->addFd(
3005 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
3006 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07003007 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003008 self->updateHealthStatus(/*baseline=*/true);
3009 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003010 },
3011 this);
3012 mService.mLooper->wake();
3013}
3014
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003015BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
3016 auto result = kMaxBootClockTsUs;
3017 for (auto&& pendingRead : mLastPendingReads) {
3018 result = std::min(result, pendingRead.bootClockTsUs);
3019 }
3020 return result;
3021}
3022
Songchun Fan9471be52021-04-21 17:49:27 -07003023void IncrementalService::DataLoaderStub::getMetrics(android::os::PersistableBundle* result) {
3024 const auto duration = elapsedMsSinceOldestPendingRead();
3025 if (duration >= 0) {
Songchun Fan0dc77722021-05-03 17:13:52 -07003026 const auto& kMetricsMillisSinceOldestPendingRead =
Songchun Fan9471be52021-04-21 17:49:27 -07003027 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
Songchun Fan0dc77722021-05-03 17:13:52 -07003028 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.c_str()), duration);
Songchun Fan9471be52021-04-21 17:49:27 -07003029 }
Songchun Fan0dc77722021-05-03 17:13:52 -07003030 const auto& kMetricsStorageHealthStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003031 os::incremental::BnIncrementalService::METRICS_STORAGE_HEALTH_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003032 result->putInt(String16(kMetricsStorageHealthStatusCode.c_str()), mHealthStatus);
3033 const auto& kMetricsDataLoaderStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003034 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003035 result->putInt(String16(kMetricsDataLoaderStatusCode.c_str()), mCurrentStatus);
3036 const auto& kMetricsMillisSinceLastDataLoaderBind =
Songchun Fan9471be52021-04-21 17:49:27 -07003037 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_DATA_LOADER_BIND();
Songchun Fan0dc77722021-05-03 17:13:52 -07003038 result->putLong(String16(kMetricsMillisSinceLastDataLoaderBind.c_str()),
3039 elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000);
3040 const auto& kMetricsDataLoaderBindDelayMillis =
Songchun Fan9471be52021-04-21 17:49:27 -07003041 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_BIND_DELAY_MILLIS();
Songchun Fan0dc77722021-05-03 17:13:52 -07003042 result->putLong(String16(kMetricsDataLoaderBindDelayMillis.c_str()),
3043 mPreviousBindDelay.count());
Songchun Fan9471be52021-04-21 17:49:27 -07003044}
3045
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003046long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
3047 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
3048 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
3049 return 0;
3050 }
3051 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
3052}
3053
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07003054void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003055 const auto pendingReadsFd = mHealthControl.pendingReads();
3056 if (pendingReadsFd < 0) {
3057 return;
3058 }
3059
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003060 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
3061
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003062 mService.mLooper->removeFd(pendingReadsFd);
3063 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003064}
3065
Songchun Fan2570ec02020-10-08 17:22:33 -07003066void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003067 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07003068 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003069 mHealthCheckParams = healthCheckParams;
3070 mHealthListener = std::move(healthListener);
3071 if (!mHealthListener) {
3072 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07003073 }
3074}
3075
Songchun Fan6944f1e2020-11-06 15:24:24 -08003076static std::string toHexString(const RawMetadata& metadata) {
3077 int n = metadata.size();
3078 std::string res(n * 2, '\0');
3079 // Same as incfs::toString(fileId)
3080 static constexpr char kHexChar[] = "0123456789abcdef";
3081 for (int i = 0; i < n; ++i) {
3082 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
3083 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
3084 }
3085 return res;
3086}
3087
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003088void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003089 dprintf(fd, " dataLoader: {\n");
3090 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08003091 dprintf(fd, " currentStatusTs: %lldmcs\n",
3092 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003093 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
3094 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003095 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003096 dprintf(fd, " health: {\n");
3097 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3098 dprintf(fd, " base: %lldmcs (%lld)\n",
3099 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3100 (long long)mHealthBase.kernelTsUs);
3101 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3102 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3103 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3104 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003105 dprintf(fd, " lastPendingReads: \n");
3106 const auto control = mService.mIncFs->openMount(mHealthPath);
3107 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003108 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003109 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3110 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3111 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3112 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3113 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003114 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
Songchun Fan9471be52021-04-21 17:49:27 -07003115 (long long)(elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000000),
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003116 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003117 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003118 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003119 dprintf(fd, " dataLoaderParams: {\n");
3120 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3121 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3122 dprintf(fd, " className: %s\n", params.className.c_str());
3123 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3124 dprintf(fd, " }\n");
3125 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003126}
3127
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003128void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3129 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003130}
3131
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003132binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3133 bool enableReadLogs, int32_t* _aidl_return) {
3134 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3135 return binder::Status::ok();
3136}
3137
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003138FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3139 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3140}
3141
Songchun Fan3c82a302019-11-29 14:23:45 -08003142} // namespace android::incremental