blob: 26efbc95eedd3be3344974278bd6a289d68b933d [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 Zubrytskyi878714a2021-04-30 15:41:37 -0700272 // ok to move a 'forwarding' reference here as lvalues are disabled anyway
273 auto deleter = [f = std::move(f)](auto) { // NOLINT
274 f();
275 };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700276 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700277 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
278}
279
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700280static auto openDir(const char* dir) {
281 struct DirCloser {
282 void operator()(DIR* d) const noexcept { ::closedir(d); }
283 };
284 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700285}
286
287static auto openDir(std::string_view dir) {
288 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800289}
290
291static int rmDirContent(const char* path) {
292 auto dir = openDir(path);
293 if (!dir) {
294 return -EINVAL;
295 }
296 while (auto entry = ::readdir(dir.get())) {
297 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
298 continue;
299 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700300 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800301 if (entry->d_type == DT_DIR) {
302 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
303 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
304 return err;
305 }
306 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
307 PLOG(WARNING) << "Failed to rmdir " << fullPath;
308 return err;
309 }
310 } else {
311 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
312 PLOG(WARNING) << "Failed to delete " << fullPath;
313 return err;
314 }
315 }
316 }
317 return 0;
318}
319
Songchun Fan3c82a302019-11-29 14:23:45 -0800320void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800321 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800322 ::rmdir(path::join(root, constants().backing).c_str());
323 ::rmdir(path::join(root, constants().mount).c_str());
324 ::rmdir(path::c_str(root));
325}
326
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700327void IncrementalService::IncFsMount::setFlag(StorageFlags flag, bool value) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700328 if (value) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700329 flags |= flag;
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700330 } else {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700331 flags &= ~flag;
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700332 }
333}
334
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800335IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800336 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800337 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800338 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700339 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700340 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700341 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700342 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700343 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700344 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800345 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800346 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700347 CHECK(mVold) << "Vold service is unavailable";
348 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
349 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
350 CHECK(mJni) << "JNI is unavailable";
351 CHECK(mLooper) << "Looper is unavailable";
352 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700353 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700354 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800355 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700356
357 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700358 mJobProcessor = std::thread([this]() {
359 mJni->initializeForCurrentThread();
360 runJobProcessing();
361 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700362 mCmdLooperThread = std::thread([this]() {
363 mJni->initializeForCurrentThread();
364 runCmdLooper();
365 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700366
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700367 const auto mountedRootNames = adoptMountedInstances();
368 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800369}
370
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700371IncrementalService::~IncrementalService() {
372 {
373 std::lock_guard lock(mJobMutex);
374 mRunning = false;
375 }
376 mJobCondition.notify_all();
377 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700378 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700379 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700380 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700381 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700382 // Ensure that mounts are destroyed while the service is still valid.
383 mBindsByPath.clear();
384 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700385}
Songchun Fan3c82a302019-11-29 14:23:45 -0800386
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700387static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800388 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800389 case IncrementalService::BindKind::Temporary:
390 return "Temporary";
391 case IncrementalService::BindKind::Permanent:
392 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800393 }
394}
395
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700396template <class Duration>
Songchun Fan0dc77722021-05-03 17:13:52 -0700397static int64_t elapsedMcs(Duration start, Duration end) {
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700398 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
399}
400
Songchun Fan0dc77722021-05-03 17:13:52 -0700401int64_t IncrementalService::elapsedUsSinceMonoTs(uint64_t monoTsUs) {
402 const auto now = mClock->now();
403 const auto nowUs = static_cast<uint64_t>(
404 duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count());
Songchun Fand48a25e2021-04-30 09:50:58 -0700405 return nowUs - monoTsUs;
406}
407
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800408void IncrementalService::onDump(int fd) {
409 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -0700410 dprintf(fd, "IncFs features: 0x%x\n", int(mIncFs->features()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800411 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
412
413 std::unique_lock l(mLock);
414
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700415 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800416 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700417 std::unique_lock ll(ifs->lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700418 const IncFsMount& mnt = *ifs;
419 dprintf(fd, " [%d]: {\n", id);
420 if (id != mnt.mountId) {
421 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
422 } else {
423 dprintf(fd, " mountId: %d\n", mnt.mountId);
424 dprintf(fd, " root: %s\n", mnt.root.c_str());
Songchun Fanf949c372021-04-27 11:26:25 -0700425 const auto metricsInstanceName = path::basename(ifs->root);
426 dprintf(fd, " metrics instance name: %s\n", path::c_str(metricsInstanceName).get());
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700427 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700428 dprintf(fd, " flags: %d\n", int(mnt.flags));
429 if (mnt.startLoadingTs.time_since_epoch() == Clock::duration::zero()) {
430 dprintf(fd, " not loading\n");
431 } else {
432 dprintf(fd, " startLoading: %llds\n",
433 (long long)(elapsedMcs(mnt.startLoadingTs, Clock::now()) / 1000000));
434 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700435 if (mnt.dataLoaderStub) {
436 mnt.dataLoaderStub->onDump(fd);
437 } else {
438 dprintf(fd, " dataLoader: null\n");
439 }
440 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
441 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700442 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700443 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800444 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700445 }
446 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800447
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700448 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
449 for (auto&& [target, bind] : mnt.bindPoints) {
450 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
451 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
452 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
453 dprintf(fd, " kind: %s\n", toString(bind.kind));
454 }
455 dprintf(fd, " }\n");
Songchun Fanf949c372021-04-27 11:26:25 -0700456
457 dprintf(fd, " incfsMetrics: {\n");
458 const auto incfsMetrics = mIncFs->getMetrics(metricsInstanceName);
459 if (incfsMetrics) {
460 dprintf(fd, " readsDelayedMin: %d\n", incfsMetrics.value().readsDelayedMin);
461 dprintf(fd, " readsDelayedMinUs: %lld\n",
462 (long long)incfsMetrics.value().readsDelayedMinUs);
463 dprintf(fd, " readsDelayedPending: %d\n",
464 incfsMetrics.value().readsDelayedPending);
465 dprintf(fd, " readsDelayedPendingUs: %lld\n",
466 (long long)incfsMetrics.value().readsDelayedPendingUs);
467 dprintf(fd, " readsFailedHashVerification: %d\n",
468 incfsMetrics.value().readsFailedHashVerification);
469 dprintf(fd, " readsFailedOther: %d\n", incfsMetrics.value().readsFailedOther);
470 dprintf(fd, " readsFailedTimedOut: %d\n",
471 incfsMetrics.value().readsFailedTimedOut);
472 } else {
473 dprintf(fd, " Metrics not available. Errno: %d\n", errno);
474 }
475 dprintf(fd, " }\n");
Songchun Fand48a25e2021-04-30 09:50:58 -0700476
477 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
478 const auto errorNo = errno;
479 dprintf(fd, " lastReadError: {\n");
480 if (lastReadError) {
481 if (lastReadError->timestampUs == 0) {
482 dprintf(fd, " No read errors.\n");
483 } else {
484 dprintf(fd, " fileId: %s\n",
485 IncFsWrapper::toString(lastReadError->id).c_str());
486 dprintf(fd, " time: %llu microseconds ago\n",
487 (unsigned long long)elapsedUsSinceMonoTs(lastReadError->timestampUs));
488 dprintf(fd, " blockIndex: %d\n", lastReadError->block);
489 dprintf(fd, " errno: %d\n", lastReadError->errorNo);
490 }
491 } else {
492 dprintf(fd, " Info not available. Errno: %d\n", errorNo);
493 }
494 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800495 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700496 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800497 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700498 dprintf(fd, "}\n");
499 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800500 for (auto&& [target, mountPairIt] : mBindsByPath) {
501 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700502 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
503 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
504 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
505 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800506 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700507 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800508}
509
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800510bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700511 if (!ifs.dataLoaderStub) {
512 return false;
513 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700514 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800515 return true;
516 }
517
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700518 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800519}
520
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700521void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800522 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700523 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800524 }
525
526 std::vector<IfsMountPtr> mounts;
527 {
528 std::lock_guard l(mLock);
529 mounts.reserve(mMounts.size());
530 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700531 std::unique_lock ll(ifs->lock);
532
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800533 if (ifs->mountId != id) {
534 continue;
535 }
536
537 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800538 mounts.push_back(ifs);
539 }
540 }
541 }
542
Alex Buynytskyy69941662020-04-11 21:40:37 -0700543 if (mounts.empty()) {
544 return;
545 }
546
Songchun Fan3c82a302019-11-29 14:23:45 -0800547 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700548 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800549 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700550 std::unique_lock l(ifs->lock);
551 if (ifs->dataLoaderStub) {
552 ifs->dataLoaderStub->requestStart();
553 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800554 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800555 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800556}
557
558auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
559 for (;;) {
560 if (mNextId == kMaxStorageId) {
561 mNextId = 0;
562 }
563 auto id = ++mNextId;
564 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
565 if (inserted) {
566 return it;
567 }
568 }
569}
570
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700571StorageId IncrementalService::createStorage(std::string_view mountPoint,
572 content::pm::DataLoaderParamsParcel dataLoaderParams,
573 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800574 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
575 if (!path::isAbsolute(mountPoint)) {
576 LOG(ERROR) << "path is not absolute: " << mountPoint;
577 return kInvalidStorageId;
578 }
579
580 auto mountNorm = path::normalize(mountPoint);
581 {
582 const auto id = findStorageId(mountNorm);
583 if (id != kInvalidStorageId) {
584 if (options & CreateOptions::OpenExisting) {
585 LOG(INFO) << "Opened existing storage " << id;
586 return id;
587 }
588 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
589 return kInvalidStorageId;
590 }
591 }
592
593 if (!(options & CreateOptions::CreateNew)) {
594 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
595 return kInvalidStorageId;
596 }
597
598 if (!path::isEmptyDir(mountNorm)) {
599 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
600 return kInvalidStorageId;
601 }
602 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
603 if (mountRoot.empty()) {
604 LOG(ERROR) << "Bad mount point";
605 return kInvalidStorageId;
606 }
607 // Make sure the code removes all crap it may create while still failing.
608 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
609 auto firstCleanupOnFailure =
610 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
611
612 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800613 const auto backing = path::join(mountRoot, constants().backing);
614 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800615 return kInvalidStorageId;
616 }
617
Songchun Fan3c82a302019-11-29 14:23:45 -0800618 IncFsMount::Control control;
619 {
620 std::lock_guard l(mMountOperationLock);
621 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800622
623 if (auto err = rmDirContent(backing.c_str())) {
624 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
625 return kInvalidStorageId;
626 }
627 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
628 return kInvalidStorageId;
629 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800630 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
631 return kInvalidStorageId;
632 }
Songchun Fanf949c372021-04-27 11:26:25 -0700633 auto status = mVold->mountIncFs(backing, mountTarget, 0, mountKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800634 if (!status.isOk()) {
635 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
636 return kInvalidStorageId;
637 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800638 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
639 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800640 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
641 return kInvalidStorageId;
642 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800643 int cmd = controlParcel.cmd.release().release();
644 int pendingReads = controlParcel.pendingReads.release().release();
645 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800646 int blocksWritten =
647 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
648 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800649 }
650
651 std::unique_lock l(mLock);
652 const auto mountIt = getStorageSlotLocked();
653 const auto mountId = mountIt->first;
654 l.unlock();
655
656 auto ifs =
657 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
658 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
659 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700660 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800661
662 auto secondCleanup = [this, &l](auto itPtr) {
663 if (!l.owns_lock()) {
664 l.lock();
665 }
666 mMounts.erase(*itPtr);
667 };
668 auto secondCleanupOnFailure =
669 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
670
671 const auto storageIt = ifs->makeStorage(ifs->mountId);
672 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800673 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800674 return kInvalidStorageId;
675 }
676
677 {
678 metadata::Mount m;
679 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700680 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700681 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
682 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
683 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800684 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800685 if (auto err =
686 mIncFs->makeFile(ifs->control,
687 path::join(ifs->root, constants().mount,
688 constants().infoMdName),
689 0777, idFromMetadata(metadata),
690 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800691 LOG(ERROR) << "Saving mount metadata failed: " << -err;
692 return kInvalidStorageId;
693 }
694 }
695
696 const auto bk =
697 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800698 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
699 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800700 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800701 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800702 return kInvalidStorageId;
703 }
704
705 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700706 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800707
Songchun Fan3c82a302019-11-29 14:23:45 -0800708 mountIt->second = std::move(ifs);
709 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700710
Songchun Fan3c82a302019-11-29 14:23:45 -0800711 LOG(INFO) << "created storage " << mountId;
712 return mountId;
713}
714
715StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
716 StorageId linkedStorage,
717 IncrementalService::CreateOptions options) {
718 if (!isValidMountTarget(mountPoint)) {
719 LOG(ERROR) << "Mount point is invalid or missing";
720 return kInvalidStorageId;
721 }
722
723 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700724 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800725 if (!ifs) {
726 LOG(ERROR) << "Ifs unavailable";
727 return kInvalidStorageId;
728 }
729
730 const auto mountIt = getStorageSlotLocked();
731 const auto storageId = mountIt->first;
732 const auto storageIt = ifs->makeStorage(storageId);
733 if (storageIt == ifs->storages.end()) {
734 LOG(ERROR) << "Can't create a new storage";
735 mMounts.erase(mountIt);
736 return kInvalidStorageId;
737 }
738
739 l.unlock();
740
741 const auto bk =
742 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800743 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
744 std::string(storageIt->second.name), path::normalize(mountPoint),
745 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800746 err < 0) {
747 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700748 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
749 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800750 return kInvalidStorageId;
751 }
752
753 mountIt->second = ifs;
754 return storageId;
755}
756
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700757bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700758 content::pm::DataLoaderParamsParcel dataLoaderParams,
759 DataLoaderStatusListener statusListener,
760 const StorageHealthCheckParams& healthCheckParams,
761 StorageHealthListener healthListener,
762 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800763 // Per Uid timeouts.
764 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700765 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800766 }
767
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700768 IfsMountPtr ifs;
769 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800770
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700771 // Re-initialize DataLoader.
772 {
773 ifs = getIfs(storageId);
774 if (!ifs) {
775 return false;
776 }
777
778 std::unique_lock l(ifs->lock);
779 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
780 }
781
782 if (dataLoaderStub) {
783 dataLoaderStub->cleanupResources();
784 dataLoaderStub = {};
785 }
786
787 {
788 std::unique_lock l(ifs->lock);
789 if (ifs->dataLoaderStub) {
790 LOG(INFO) << "Skipped data loader stub creation because it already exists";
791 return false;
792 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700793
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700794 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
795 healthCheckParams, std::move(healthListener));
796 CHECK(ifs->dataLoaderStub);
797 dataLoaderStub = ifs->dataLoaderStub;
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700798
799 // Disable long read timeouts for non-system dataloaders.
800 // To be re-enabled after installation is complete.
801 ifs->setReadTimeoutsRequested(dataLoaderStub->isSystemDataLoader() &&
802 getAlwaysEnableReadTimeoutsForSystemDataLoaders());
803 applyStorageParamsLocked(*ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700804 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800805
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700806 if (dataLoaderStub->isSystemDataLoader() &&
807 !getEnforceReadLogsMaxIntervalForSystemDataLoaders()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700808 // Readlogs from system dataloader (adb) can always be collected.
809 ifs->startLoadingTs = TimePoint::max();
810 } else {
811 // Assign time when installation wants the DL to start streaming.
812 const auto startLoadingTs = mClock->now();
813 ifs->startLoadingTs = startLoadingTs;
814 // Setup a callback to disable the readlogs after max interval.
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700815 addTimedJob(*mTimedQueue, storageId, getReadLogsMaxInterval(),
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700816 [this, storageId, startLoadingTs]() {
817 const auto ifs = getIfs(storageId);
818 if (!ifs) {
819 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
820 << storageId;
821 return;
822 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700823 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700824 if (ifs->startLoadingTs != startLoadingTs) {
825 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
826 "installation?): "
827 << storageId;
828 return;
829 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700830 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700831 });
832 }
833
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800834 return dataLoaderStub->requestStart();
835}
836
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700837void IncrementalService::onInstallationComplete(StorageId storage) {
838 IfsMountPtr ifs = getIfs(storage);
839 if (!ifs) {
840 return;
841 }
842
843 // Always enable long read timeouts after installation is complete.
844 std::unique_lock l(ifs->lock);
845 ifs->setReadTimeoutsRequested(true);
846 applyStorageParamsLocked(*ifs);
847}
848
Songchun Fan3c82a302019-11-29 14:23:45 -0800849IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
850 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700851 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800852}
853
854StorageId IncrementalService::findStorageId(std::string_view path) const {
855 std::lock_guard l(mLock);
856 auto it = findStorageLocked(path);
857 if (it == mBindsByPath.end()) {
858 return kInvalidStorageId;
859 }
860 return it->second->second.storage;
861}
862
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800863void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700864 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700865 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800866 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700867 return;
868 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700869
870 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800871 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700872 return;
873 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800874 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700875
876 const auto metadata = constants().readLogsDisabledMarkerName;
877 if (auto err = mIncFs->makeFile(ifs->control,
878 path::join(ifs->root, constants().mount,
879 constants().readLogsDisabledMarkerName),
880 0777, idFromMetadata(metadata), {})) {
881 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
882 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
883 return;
884 }
885
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700886 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700887}
888
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700889int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
890 const auto ifs = getIfs(storageId);
891 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700892 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700893 return -EINVAL;
894 }
895
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700896 std::string packageName;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700897
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700898 {
899 std::unique_lock l(ifs->lock);
900 if (!enableReadLogs) {
901 return disableReadLogsLocked(*ifs);
902 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700903
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700904 if (!ifs->readLogsAllowed()) {
905 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
906 return -EPERM;
907 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700908
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700909 if (!ifs->dataLoaderStub) {
910 // This should never happen - only DL can call enableReadLogs.
911 LOG(ERROR) << "enableReadLogs failed: invalid state";
912 return -EPERM;
913 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700914
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700915 // Check installation time.
916 const auto now = mClock->now();
917 const auto startLoadingTs = ifs->startLoadingTs;
918 if (startLoadingTs <= now && now - startLoadingTs > getReadLogsMaxInterval()) {
919 LOG(ERROR)
920 << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
921 << storageId;
922 return -EPERM;
923 }
924
925 packageName = ifs->dataLoaderStub->params().packageName;
926 ifs->setReadLogsRequested(true);
927 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700928
929 // Check loader usage stats permission and apop.
930 if (auto status =
931 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
932 !status.isOk()) {
933 LOG(ERROR) << " Permission: " << kLoaderUsageStats
934 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700935 return fromBinderStatus(status);
936 }
937
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700938 // Check multiuser permission.
939 if (auto status =
940 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
941 !status.isOk()) {
942 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
943 << " check failed: " << status.toString8();
944 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700945 }
946
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700947 {
948 std::unique_lock l(ifs->lock);
949 if (!ifs->readLogsRequested()) {
950 return 0;
951 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700952 if (auto status = applyStorageParamsLocked(*ifs); status != 0) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700953 return status;
954 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700955 }
956
957 registerAppOpsCallback(packageName);
958
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700959 return 0;
960}
961
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700962int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700963 ifs.setReadLogsRequested(false);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700964 return applyStorageParamsLocked(ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700965}
966
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700967int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700968 os::incremental::IncrementalFileSystemControlParcel control;
969 control.cmd.reset(dup(ifs.control.cmd()));
970 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700971 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700972 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700973 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700974 }
975
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700976 bool enableReadLogs = ifs.readLogsRequested();
977 bool enableReadTimeouts = ifs.readTimeoutsRequested();
978
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700979 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700980 auto status = mVold->setIncFsMountOptions(control, enableReadLogs, enableReadTimeouts);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800981 if (status.isOk()) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700982 // Store states.
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800983 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700984 ifs.setReadTimeoutsEnabled(enableReadTimeouts);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700985 } else {
986 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800987 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700988 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700989}
990
Songchun Fan3c82a302019-11-29 14:23:45 -0800991void IncrementalService::deleteStorage(StorageId storageId) {
992 const auto ifs = getIfs(storageId);
993 if (!ifs) {
994 return;
995 }
996 deleteStorage(*ifs);
997}
998
999void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
1000 std::unique_lock l(ifs.lock);
1001 deleteStorageLocked(ifs, std::move(l));
1002}
1003
1004void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
1005 std::unique_lock<std::mutex>&& ifsLock) {
1006 const auto storages = std::move(ifs.storages);
1007 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
1008 const auto bindPoints = ifs.bindPoints;
1009 ifsLock.unlock();
1010
1011 std::lock_guard l(mLock);
1012 for (auto&& [id, _] : storages) {
1013 if (id != ifs.mountId) {
1014 mMounts.erase(id);
1015 }
1016 }
1017 for (auto&& [path, _] : bindPoints) {
1018 mBindsByPath.erase(path);
1019 }
1020 mMounts.erase(ifs.mountId);
1021}
1022
1023StorageId IncrementalService::openStorage(std::string_view pathInMount) {
1024 if (!path::isAbsolute(pathInMount)) {
1025 return kInvalidStorageId;
1026 }
1027
1028 return findStorageId(path::normalize(pathInMount));
1029}
1030
Songchun Fan3c82a302019-11-29 14:23:45 -08001031IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
1032 std::lock_guard l(mLock);
1033 return getIfsLocked(storage);
1034}
1035
1036const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
1037 auto it = mMounts.find(storage);
1038 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001039 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -07001040 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -08001041 }
1042 return it->second;
1043}
1044
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001045int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
1046 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001047 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001048 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001049 return -EINVAL;
1050 }
1051
1052 const auto ifs = getIfs(storage);
1053 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001054 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001055 return -EINVAL;
1056 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001057
Songchun Fan3c82a302019-11-29 14:23:45 -08001058 std::unique_lock l(ifs->lock);
1059 const auto storageInfo = ifs->storages.find(storage);
1060 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001061 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -08001062 return -EINVAL;
1063 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001064 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001065 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001066 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001067 return -EINVAL;
1068 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001069 l.unlock();
1070 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001071 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
1072 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -08001073}
1074
1075int IncrementalService::unbind(StorageId storage, std::string_view target) {
1076 if (!path::isAbsolute(target)) {
1077 return -EINVAL;
1078 }
1079
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001080 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001081
1082 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
1083 // otherwise there's a chance to unmount something completely unrelated
1084 const auto norm = path::normalize(target);
1085 std::unique_lock l(mLock);
1086 const auto storageIt = mBindsByPath.find(norm);
1087 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
1088 return -EINVAL;
1089 }
1090 const auto bindIt = storageIt->second;
1091 const auto storageId = bindIt->second.storage;
1092 const auto ifs = getIfsLocked(storageId);
1093 if (!ifs) {
1094 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
1095 << " is missing";
1096 return -EFAULT;
1097 }
1098 mBindsByPath.erase(storageIt);
1099 l.unlock();
1100
1101 mVold->unmountIncFs(bindIt->first);
1102 std::unique_lock l2(ifs->lock);
1103 if (ifs->bindPoints.size() <= 1) {
1104 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -07001105 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001106 } else {
1107 const std::string savedFile = std::move(bindIt->second.savedFilename);
1108 ifs->bindPoints.erase(bindIt);
1109 l2.unlock();
1110 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001111 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001112 }
1113 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001114
Songchun Fan3c82a302019-11-29 14:23:45 -08001115 return 0;
1116}
1117
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001118std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001119 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001120 std::string_view path) const {
1121 if (!path::isAbsolute(path)) {
1122 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001123 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001124 auto normPath = path::normalize(path);
1125 if (path::startsWith(normPath, storageIt->second.name)) {
1126 return normPath;
1127 }
1128 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001129 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1130 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001131 return {};
1132 }
1133 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001134}
1135
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001136std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001137 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001138 std::unique_lock l(ifs.lock);
1139 const auto storageInfo = ifs.storages.find(storage);
1140 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001141 return {};
1142 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001143 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001144}
1145
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001146int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001147 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001148 const auto ifs = getIfs(storage);
1149 if (!ifs) {
1150 return -EINVAL;
1151 }
1152 if (data.size() > params.size) {
1153 LOG(ERROR) << "Bad data size - bigger than file size";
1154 return -EINVAL;
1155 }
1156 if (!data.empty() && data.size() != params.size) {
1157 // Writing a page is an irreversible operation, and it can't be updated with additional
1158 // data later. Check that the last written page is complete, or we may break the file.
1159 if (!isPageAligned(data.size())) {
1160 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001161 return -EINVAL;
1162 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001163 }
1164 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1165 if (normPath.empty()) {
1166 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1167 return -EINVAL;
1168 }
1169 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1170 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1171 return err;
1172 }
1173 if (params.size > 0) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001174 if (auto err = mIncFs->reserveSpace(ifs->control, id, params.size)) {
1175 if (err != -EOPNOTSUPP) {
1176 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1177 (void)mIncFs->unlink(ifs->control, normPath);
1178 return err;
1179 } else {
1180 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1181 "may run out of disk later";
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001182 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001183 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001184 if (!data.empty()) {
1185 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001186 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001187 return err;
1188 }
1189 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001190 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001191 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001192}
1193
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001194int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001195 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001196 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001197 if (normPath.empty()) {
1198 return -EINVAL;
1199 }
1200 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001201 }
1202 return -EINVAL;
1203}
1204
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001205int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001206 const auto ifs = getIfs(storageId);
1207 if (!ifs) {
1208 return -EINVAL;
1209 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001210 return makeDirs(*ifs, storageId, path, mode);
1211}
1212
1213int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1214 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001215 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1216 if (normPath.empty()) {
1217 return -EINVAL;
1218 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001219 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001220}
1221
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001222int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1223 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001224 std::unique_lock l(mLock);
1225 auto ifsSrc = getIfsLocked(sourceStorageId);
1226 if (!ifsSrc) {
1227 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001228 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001229 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1230 return -EINVAL;
1231 }
1232 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001233 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1234 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001235 if (normOldPath.empty() || normNewPath.empty()) {
1236 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1237 return -EINVAL;
1238 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001239 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1240 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1241 << " to " << newPath << "[" << normNewPath << "]";
1242 return err;
1243 }
1244 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001245}
1246
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001247int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001248 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001249 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001250 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001251 }
1252 return -EINVAL;
1253}
1254
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001255int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1256 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001257 std::string&& target, BindKind kind,
1258 std::unique_lock<std::mutex>& mainLock) {
1259 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001260 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001261 return -EINVAL;
1262 }
1263
1264 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001265 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001266 if (kind != BindKind::Temporary) {
1267 metadata::BindPoint bp;
1268 bp.set_storage_id(storage);
1269 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001270 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001271 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001272 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001273 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001274 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001275 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1276 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1277 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001278 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001279 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001280 return int(node);
1281 }
1282 }
1283
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001284 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1285 std::move(target), kind, mainLock);
1286 if (res) {
1287 mIncFs->unlink(ifs.control, metadataFullPath);
1288 }
1289 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001290}
1291
1292int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001293 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001294 std::string&& target, BindKind kind,
1295 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001296 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001297 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001298 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001299 if (!status.isOk()) {
1300 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1301 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1302 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1303 : status.serviceSpecificErrorCode() == 0
1304 ? -EFAULT
1305 : status.serviceSpecificErrorCode()
1306 : -EIO;
1307 }
1308 }
1309
1310 if (!mainLock.owns_lock()) {
1311 mainLock.lock();
1312 }
1313 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001314 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1315 std::move(target), kind);
1316 return 0;
1317}
1318
1319void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1320 std::string&& metadataName, std::string&& source,
1321 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001322 const auto [it, _] =
1323 ifs.bindPoints.insert_or_assign(target,
1324 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001325 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001326 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001327}
1328
1329RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1330 const auto ifs = getIfs(storage);
1331 if (!ifs) {
1332 return {};
1333 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001334 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001335 if (normPath.empty()) {
1336 return {};
1337 }
1338 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001339}
1340
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001341RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001342 const auto ifs = getIfs(storage);
1343 if (!ifs) {
1344 return {};
1345 }
1346 return mIncFs->getMetadata(ifs->control, node);
1347}
1348
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001349void IncrementalService::setUidReadTimeouts(StorageId storage,
1350 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001351 using microseconds = std::chrono::microseconds;
1352 using milliseconds = std::chrono::milliseconds;
1353
1354 auto maxPendingTimeUs = microseconds(0);
1355 for (const auto& timeouts : perUidReadTimeouts) {
1356 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1357 }
1358 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07001359 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001360 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1361 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001362 return;
1363 }
1364
1365 const auto ifs = getIfs(storage);
1366 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001367 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001368 return;
1369 }
1370
1371 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1372 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1373 return;
1374 }
1375
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001376 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1377 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1378 if (checkUidReadTimeouts(storageId, state, timeout)) {
1379 return true;
1380 }
1381 clearUidReadTimeouts(storageId);
1382 return false;
1383 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001384}
1385
1386void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1387 const auto ifs = getIfs(storage);
1388 if (!ifs) {
1389 return;
1390 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001391 mIncFs->setUidReadTimeouts(ifs->control, {});
1392}
1393
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001394bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1395 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001396 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001397 // Reached maximum timeout.
1398 return false;
1399 }
1400 if (state.error) {
1401 // Something is wrong, abort.
1402 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001403 }
1404
1405 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001406 if (state.fullyLoaded && !state.readLogsEnabled) {
1407 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001408 }
1409
1410 const auto timeLeft = timeLimit - Clock::now();
1411 if (timeLeft < Constants::progressUpdateInterval) {
1412 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001413 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001414 }
1415
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001416 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001417}
1418
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001419std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1420 std::unordered_set<std::string_view> mountedRootNames;
1421 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1422 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1423 for (auto [source, target] : binds) {
1424 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1425 LOG(INFO) << " " << path::join(root, source);
1426 }
1427
1428 // Ensure it's a kind of a mount that's managed by IncrementalService
1429 if (path::basename(root) != constants().mount ||
1430 path::basename(backingDir) != constants().backing) {
1431 return;
1432 }
1433 const auto expectedRoot = path::dirname(root);
1434 if (path::dirname(backingDir) != expectedRoot) {
1435 return;
1436 }
1437 if (path::dirname(expectedRoot) != mIncrementalDir) {
1438 return;
1439 }
1440 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1441 return;
1442 }
1443
1444 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1445
1446 // make sure we clean up the mount if it happens to be a bad one.
1447 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1448 auto cleanupFiles = makeCleanup([&]() {
1449 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1450 IncFsMount::cleanupFilesystem(expectedRoot);
1451 });
1452 auto cleanupMounts = makeCleanup([&]() {
1453 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1454 for (auto&& [_, target] : binds) {
1455 mVold->unmountIncFs(std::string(target));
1456 }
1457 mVold->unmountIncFs(std::string(root));
1458 });
1459
1460 auto control = mIncFs->openMount(root);
1461 if (!control) {
1462 LOG(INFO) << "failed to open mount " << root;
1463 return;
1464 }
1465
1466 auto mountRecord =
1467 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1468 path::join(root, constants().infoMdName));
1469 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1470 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1471 return;
1472 }
1473
1474 auto mountId = mountRecord.storage().id();
1475 mNextId = std::max(mNextId, mountId + 1);
1476
1477 DataLoaderParamsParcel dataLoaderParams;
1478 {
1479 const auto& loader = mountRecord.loader();
1480 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1481 dataLoaderParams.packageName = loader.package_name();
1482 dataLoaderParams.className = loader.class_name();
1483 dataLoaderParams.arguments = loader.arguments();
1484 }
1485
1486 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1487 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001488 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001489
Alex Buynytskyy04035452020-06-06 20:15:58 -07001490 // Check if marker file present.
1491 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001492 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001493 }
1494
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001495 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1496 auto d = openDir(root);
1497 while (auto e = ::readdir(d.get())) {
1498 if (e->d_type == DT_REG) {
1499 auto name = std::string_view(e->d_name);
1500 if (name.starts_with(constants().mountpointMdPrefix)) {
1501 permanentBindPoints
1502 .emplace_back(name,
1503 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1504 ifs->control,
1505 path::join(root,
1506 name)));
1507 if (permanentBindPoints.back().second.dest_path().empty() ||
1508 permanentBindPoints.back().second.source_subdir().empty()) {
1509 permanentBindPoints.pop_back();
1510 mIncFs->unlink(ifs->control, path::join(root, name));
1511 } else {
1512 LOG(INFO) << "Permanent bind record: '"
1513 << permanentBindPoints.back().second.source_subdir() << "'->'"
1514 << permanentBindPoints.back().second.dest_path() << "'";
1515 }
1516 }
1517 } else if (e->d_type == DT_DIR) {
1518 if (e->d_name == "."sv || e->d_name == ".."sv) {
1519 continue;
1520 }
1521 auto name = std::string_view(e->d_name);
1522 if (name.starts_with(constants().storagePrefix)) {
1523 int storageId;
1524 const auto res =
1525 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1526 name.data() + name.size(), storageId);
1527 if (res.ec != std::errc{} || *res.ptr != '_') {
1528 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1529 << "' for mount " << expectedRoot;
1530 continue;
1531 }
1532 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1533 if (!inserted) {
1534 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1535 << " for mount " << expectedRoot;
1536 continue;
1537 }
1538 ifs->storages.insert_or_assign(storageId,
1539 IncFsMount::Storage{path::join(root, name)});
1540 mNextId = std::max(mNextId, storageId + 1);
1541 }
1542 }
1543 }
1544
1545 if (ifs->storages.empty()) {
1546 LOG(WARNING) << "No valid storages in mount " << root;
1547 return;
1548 }
1549
1550 // now match the mounted directories with what we expect to have in the metadata
1551 {
1552 std::unique_lock l(mLock, std::defer_lock);
1553 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1554 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1555 [&, bindRecord = bindRecord](auto&& bind) {
1556 return bind.second == bindRecord.dest_path() &&
1557 path::join(root, bind.first) ==
1558 bindRecord.source_subdir();
1559 });
1560 if (mountedIt != binds.end()) {
1561 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1562 << " to mount " << mountedIt->first;
1563 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1564 std::move(*bindRecord.mutable_source_subdir()),
1565 std::move(*bindRecord.mutable_dest_path()),
1566 BindKind::Permanent);
1567 if (mountedIt != binds.end() - 1) {
1568 std::iter_swap(mountedIt, binds.end() - 1);
1569 }
1570 binds = binds.first(binds.size() - 1);
1571 } else {
1572 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1573 << ", mounting";
1574 // doesn't exist - try mounting back
1575 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1576 std::move(*bindRecord.mutable_source_subdir()),
1577 std::move(*bindRecord.mutable_dest_path()),
1578 BindKind::Permanent, l)) {
1579 mIncFs->unlink(ifs->control, metadataFile);
1580 }
1581 }
1582 }
1583 }
1584
1585 // if anything stays in |binds| those are probably temporary binds; system restarted since
1586 // they were mounted - so let's unmount them all.
1587 for (auto&& [source, target] : binds) {
1588 if (source.empty()) {
1589 continue;
1590 }
1591 mVold->unmountIncFs(std::string(target));
1592 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001593 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001594
1595 if (ifs->bindPoints.empty()) {
1596 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1597 deleteStorage(*ifs);
1598 return;
1599 }
1600
1601 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1602 CHECK(ifs->dataLoaderStub);
1603
1604 mountedRootNames.insert(path::basename(ifs->root));
1605
1606 // not locking here at all: we're still in the constructor, no other calls can happen
1607 mMounts[ifs->mountId] = std::move(ifs);
1608 });
1609
1610 return mountedRootNames;
1611}
1612
1613void IncrementalService::mountExistingImages(
1614 const std::unordered_set<std::string_view>& mountedRootNames) {
1615 auto dir = openDir(mIncrementalDir);
1616 if (!dir) {
1617 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1618 return;
1619 }
1620 while (auto entry = ::readdir(dir.get())) {
1621 if (entry->d_type != DT_DIR) {
1622 continue;
1623 }
1624 std::string_view name = entry->d_name;
1625 if (!name.starts_with(constants().mountKeyPrefix)) {
1626 continue;
1627 }
1628 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001629 continue;
1630 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001631 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001632 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001633 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001634 }
1635 }
1636}
1637
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001638bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001639 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001640 const auto backing = path::join(root, constants().backing);
Songchun Fanf949c372021-04-27 11:26:25 -07001641 std::string mountKey(path::basename(path::dirname(mountTarget)));
Songchun Fan3c82a302019-11-29 14:23:45 -08001642
Songchun Fan3c82a302019-11-29 14:23:45 -08001643 IncrementalFileSystemControlParcel controlParcel;
Songchun Fanf949c372021-04-27 11:26:25 -07001644 auto status = mVold->mountIncFs(backing, mountTarget, 0, mountKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001645 if (!status.isOk()) {
1646 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1647 return false;
1648 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001649
1650 int cmd = controlParcel.cmd.release().release();
1651 int pendingReads = controlParcel.pendingReads.release().release();
1652 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001653 int blocksWritten =
1654 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1655 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001656
1657 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1658
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001659 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1660 path::join(mountTarget, constants().infoMdName));
1661 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001662 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1663 return false;
1664 }
1665
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001666 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001667 mNextId = std::max(mNextId, ifs->mountId + 1);
1668
Alex Buynytskyy04035452020-06-06 20:15:58 -07001669 // Check if marker file present.
1670 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001671 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001672 }
1673
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001674 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001675 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001676 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001677 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001678 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001679 dataLoaderParams.packageName = loader.package_name();
1680 dataLoaderParams.className = loader.class_name();
1681 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001682 }
1683
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001684 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001685 CHECK(ifs->dataLoaderStub);
1686
Songchun Fan3c82a302019-11-29 14:23:45 -08001687 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001688 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001689 while (auto e = ::readdir(d.get())) {
1690 if (e->d_type == DT_REG) {
1691 auto name = std::string_view(e->d_name);
1692 if (name.starts_with(constants().mountpointMdPrefix)) {
1693 bindPoints.emplace_back(name,
1694 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1695 ifs->control,
1696 path::join(mountTarget,
1697 name)));
1698 if (bindPoints.back().second.dest_path().empty() ||
1699 bindPoints.back().second.source_subdir().empty()) {
1700 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001701 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001702 }
1703 }
1704 } else if (e->d_type == DT_DIR) {
1705 if (e->d_name == "."sv || e->d_name == ".."sv) {
1706 continue;
1707 }
1708 auto name = std::string_view(e->d_name);
1709 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001710 int storageId;
1711 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1712 name.data() + name.size(), storageId);
1713 if (res.ec != std::errc{} || *res.ptr != '_') {
1714 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1715 << root;
1716 continue;
1717 }
1718 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001719 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001720 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001721 << " for mount " << root;
1722 continue;
1723 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001724 ifs->storages.insert_or_assign(storageId,
1725 IncFsMount::Storage{
1726 path::join(root, constants().mount, name)});
1727 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001728 }
1729 }
1730 }
1731
1732 if (ifs->storages.empty()) {
1733 LOG(WARNING) << "No valid storages in mount " << root;
1734 return false;
1735 }
1736
1737 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001738 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001739 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001740 for (auto&& bp : bindPoints) {
1741 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1742 std::move(*bp.second.mutable_source_subdir()),
1743 std::move(*bp.second.mutable_dest_path()),
1744 BindKind::Permanent, l);
1745 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001746 }
1747
1748 if (bindCount == 0) {
1749 LOG(WARNING) << "No valid bind points for mount " << root;
1750 deleteStorage(*ifs);
1751 return false;
1752 }
1753
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001754 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001755 mMounts[ifs->mountId] = std::move(ifs);
1756 return true;
1757}
1758
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001759void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001760 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001761 while (mRunning.load(std::memory_order_relaxed)) {
1762 mLooper->pollAll(kTimeoutMsecs);
1763 }
1764}
1765
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001766void IncrementalService::trimReservedSpaceV1(const IncFsMount& ifs) {
1767 mIncFs->forEachFile(ifs.control, [this](auto&& control, auto&& fileId) {
1768 if (mIncFs->isFileFullyLoaded(control, fileId) == incfs::LoadingState::Full) {
1769 mIncFs->reserveSpace(control, fileId, -1);
1770 }
1771 return true;
1772 });
1773}
1774
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001775void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001776 DataLoaderStatusListener&& statusListener,
1777 const StorageHealthCheckParams& healthCheckParams,
1778 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001779 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001780 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001781 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1782 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1783 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001784 if (ifs.control.blocksWritten() >= 0) {
1785 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1786 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001787 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001788
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001789 ifs.dataLoaderStub =
1790 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001791 std::move(statusListener), healthCheckParams,
1792 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001793
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001794 // pre-v2 IncFS doesn't do automatic reserved space trimming - need to run it manually
1795 if (!(mIncFs->features() & incfs::Features::v2)) {
1796 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1797 if (!state.fullyLoaded) {
1798 return true;
1799 }
1800
1801 const auto ifs = getIfs(storageId);
1802 if (!ifs) {
1803 return false;
1804 }
1805 trimReservedSpaceV1(*ifs);
1806 return false;
1807 });
1808 }
1809
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001810 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1811 if (!state.fullyLoaded || state.readLogsEnabled) {
1812 return true;
1813 }
1814
1815 DataLoaderStubPtr dataLoaderStub;
1816 {
1817 const auto ifs = getIfs(storageId);
1818 if (!ifs) {
1819 return false;
1820 }
1821
1822 std::unique_lock l(ifs->lock);
1823 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1824 }
1825
1826 if (dataLoaderStub) {
1827 dataLoaderStub->cleanupResources();
1828 }
1829
1830 return false;
1831 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001832}
1833
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001834template <class Duration>
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001835static constexpr auto castToMs(Duration d) {
1836 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1837}
1838
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001839// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001840// Lib files should be placed next to the APK file in the following matter:
1841// Example:
1842// /path/to/base.apk
1843// /path/to/lib/arm/first.so
1844// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001845bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1846 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001847 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001848 auto start = Clock::now();
1849
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001850 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001851 if (!ifs) {
1852 LOG(ERROR) << "Invalid storage " << storage;
1853 return false;
1854 }
1855
Songchun Fanc8975312020-07-13 12:14:37 -07001856 const auto targetLibPathRelativeToStorage =
1857 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1858 libDirRelativePath);
1859
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001860 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001861 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1862 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001863 << " errno: " << res;
1864 return false;
1865 }
1866
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001867 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001868 ZipArchiveHandle zipFileHandle;
1869 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001870 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1871 return false;
1872 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001873
1874 // Need a shared pointer: will be passing it into all unpacking jobs.
1875 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001876 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001877 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001878 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001879 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1880 return false;
1881 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001882 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001883 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1884
1885 auto openZipTs = Clock::now();
1886
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001887 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1888 incfs::FileId sourceId;
1889 if (mapFiles) {
1890 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1891 if (!incfs::isValidFileId(sourceId)) {
1892 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1893 << "', mapping disabled";
1894 mapFiles = false;
1895 }
1896 }
1897
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001898 std::vector<Job> jobQueue;
1899 ZipEntry entry;
1900 std::string_view fileName;
1901 while (!Next(cookie, &entry, &fileName)) {
1902 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001903 continue;
1904 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001905
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001906 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001907 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001908
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001909 if (!extractNativeLibs) {
1910 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001911 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001912 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1913 return false;
1914 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001915 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001916 LOG(WARNING) << "Library " << fileName
1917 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1918 << entry.offset;
1919 return false;
1920 }
1921 continue;
1922 }
1923
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001924 auto startFileTs = Clock::now();
1925
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001926 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001927 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001928 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001929 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001930 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001931 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001932 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1933 << "; skipping extraction, spent "
1934 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1935 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001936 continue;
1937 }
1938
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001939 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1940 incfs::NewMappedFileParams mappedFileParams = {
1941 .sourceId = sourceId,
1942 .sourceOffset = entry.offset,
1943 .size = entry.uncompressed_length,
1944 };
1945
1946 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1947 mappedFileParams);
1948 res == 0) {
1949 if (perfLoggingEnabled()) {
1950 auto doneTs = Clock::now();
1951 LOG(INFO) << "incfs: Mapped " << libName << ": "
1952 << elapsedMcs(startFileTs, doneTs) << "mcs";
1953 }
1954 continue;
1955 } else {
1956 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1957 << "; falling back to full extraction";
1958 }
1959 }
1960
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001961 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001962 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001963 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001964 .signature = {},
1965 // Metadata of the new lib file is its relative path
1966 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1967 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001968 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001969 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001970 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001971 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001972 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001973 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001974 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001975
1976 auto makeFileTs = Clock::now();
1977
Songchun Fanafaf6e92020-03-18 14:12:20 -07001978 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001979 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001980 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001981 LOG(INFO) << "incfs: Extracted " << libName
1982 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001983 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001984 continue;
1985 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001986
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001987 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1988 libFileId, libPath = std::move(targetLibPath),
1989 makeFileTs]() mutable {
1990 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001991 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001992
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001993 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001994 auto prepareJobTs = Clock::now();
1995 LOG(INFO) << "incfs: Processed " << libName << ": "
1996 << elapsedMcs(startFileTs, prepareJobTs)
1997 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1998 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001999 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002000 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002001
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002002 auto processedTs = Clock::now();
2003
2004 if (!jobQueue.empty()) {
2005 {
2006 std::lock_guard lock(mJobMutex);
2007 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002008 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002009 if (existingJobs.empty()) {
2010 existingJobs = std::move(jobQueue);
2011 } else {
2012 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
2013 std::move_iterator(jobQueue.end()));
2014 }
2015 }
2016 }
2017 mJobCondition.notify_all();
2018 }
2019
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002020 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002021 auto end = Clock::now();
2022 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
2023 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
2024 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002025 << " make files: " << elapsedMcs(openZipTs, processedTs)
2026 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002027 }
2028
2029 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002030}
2031
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002032void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
2033 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002034 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002035 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002036 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002037 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002038 return;
2039 }
2040
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002041 auto startedTs = Clock::now();
2042
2043 // Write extracted data to new file
2044 // NOTE: don't zero-initialize memory, it may take a while for nothing
2045 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
2046 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002047 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002048 return;
2049 }
2050
2051 auto extractFileTs = Clock::now();
2052
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002053 if (setFileContent(ifs, libFileId, debugLibPath,
2054 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002055 return;
2056 }
2057
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002058 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002059 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002060 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
2061 << entry.compressed_length << " -> " << entry.uncompressed_length
2062 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002063 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
2064 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002065 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002066 }
2067}
2068
2069bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002070 struct WaitPrinter {
2071 const Clock::time_point startTs = Clock::now();
2072 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002073 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002074 const auto endTs = Clock::now();
2075 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
2076 << elapsedMcs(startTs, endTs) << "mcs";
2077 }
2078 }
2079 } waitPrinter;
2080
2081 MountId mount;
2082 {
2083 auto ifs = getIfs(storage);
2084 if (!ifs) {
2085 return true;
2086 }
2087 mount = ifs->mountId;
2088 }
2089
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002090 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002091 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002092 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002093 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002094 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002095 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002096}
2097
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002098int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
2099 std::string_view debugFilePath,
2100 std::span<const uint8_t> data) const {
2101 auto startTs = Clock::now();
2102
2103 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2104 if (!writeFd.ok()) {
2105 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2106 << " errno: " << writeFd.get();
2107 return writeFd.get();
2108 }
2109
2110 const auto dataLength = data.size();
2111
2112 auto openFileTs = Clock::now();
2113 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2114 std::vector<IncFsDataBlock> instructions(numBlocks);
2115 for (int i = 0; i < numBlocks; i++) {
2116 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2117 instructions[i] = IncFsDataBlock{
2118 .fileFd = writeFd.get(),
2119 .pageIndex = static_cast<IncFsBlockIndex>(i),
2120 .compression = INCFS_COMPRESSION_KIND_NONE,
2121 .kind = INCFS_BLOCK_KIND_DATA,
2122 .dataSize = static_cast<uint32_t>(blockSize),
2123 .data = reinterpret_cast<const char*>(data.data()),
2124 };
2125 data = data.subspan(blockSize);
2126 }
2127 auto prepareInstsTs = Clock::now();
2128
2129 size_t res = mIncFs->writeBlocks(instructions);
2130 if (res != instructions.size()) {
2131 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2132 return res;
2133 }
2134
2135 if (perfLoggingEnabled()) {
2136 auto endTs = Clock::now();
2137 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2138 << " bytes): " << elapsedMcs(startTs, endTs)
2139 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2140 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2141 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2142 }
2143
2144 return 0;
2145}
2146
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002147incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2148 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002149 std::unique_lock l(mLock);
2150 const auto ifs = getIfsLocked(storage);
2151 if (!ifs) {
2152 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002153 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002154 }
2155 const auto storageInfo = ifs->storages.find(storage);
2156 if (storageInfo == ifs->storages.end()) {
2157 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002158 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002159 }
2160 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002161 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002162}
2163
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002164incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2165 const auto ifs = getIfs(storage);
2166 if (!ifs) {
2167 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2168 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002169 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002170 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002171}
2172
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002173IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002174 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002175 std::unique_lock l(mLock);
2176 const auto ifs = getIfsLocked(storage);
2177 if (!ifs) {
2178 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002179 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002180 }
2181 const auto storageInfo = ifs->storages.find(storage);
2182 if (storageInfo == ifs->storages.end()) {
2183 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002184 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002185 }
2186 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002187 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002188}
2189
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002190IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002191 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002192 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2193 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002194 const auto [filledBlocksCount, totalBlocksCount] =
2195 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002196 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2197 filledBlocksCount == -ENOENT) {
2198 // a kind of a file that's not really being loaded, e.g. a mapped range
2199 // an older IncFS used to return ENOENT in this case, so handle it the same way
2200 return true;
2201 }
Songchun Fan374f7652020-08-20 08:40:29 -07002202 if (filledBlocksCount < 0) {
2203 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002204 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002205 error = filledBlocksCount;
2206 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002207 }
2208 totalBlocks += totalBlocksCount;
2209 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002210 return true;
2211 });
Songchun Fan374f7652020-08-20 08:40:29 -07002212
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002213 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002214}
2215
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002216bool IncrementalService::updateLoadingProgress(StorageId storage,
2217 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002218 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002219 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002220 // Failed to get progress from incfs, abort.
2221 return false;
2222 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002223 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2224 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002225 // Stop updating progress once it is fully loaded
2226 return true;
2227 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002228 addTimedJob(*mProgressUpdateJobQueue, storage,
2229 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002230 [storage, progressListener = std::move(progressListener), this]() mutable {
2231 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002232 });
2233 return true;
2234}
2235
2236bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002237 StorageId storage, StorageLoadingProgressListener progressListener) {
2238 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002239}
2240
2241bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2242 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2243}
2244
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002245bool IncrementalService::perfLoggingEnabled() {
2246 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2247 return enabled;
2248}
2249
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002250void IncrementalService::runJobProcessing() {
2251 for (;;) {
2252 std::unique_lock lock(mJobMutex);
2253 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2254 if (!mRunning) {
2255 return;
2256 }
2257
2258 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002259 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002260 auto queue = std::move(it->second);
2261 mJobQueue.erase(it);
2262 lock.unlock();
2263
2264 for (auto&& job : queue) {
2265 job();
2266 }
2267
2268 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002269 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002270 lock.unlock();
2271 mJobCondition.notify_all();
2272 }
2273}
2274
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002275void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002276 sp<IAppOpsCallback> listener;
2277 {
2278 std::unique_lock lock{mCallbacksLock};
2279 auto& cb = mCallbackRegistered[packageName];
2280 if (cb) {
2281 return;
2282 }
2283 cb = new AppOpsListener(*this, packageName);
2284 listener = cb;
2285 }
2286
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002287 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2288 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002289}
2290
2291bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2292 sp<IAppOpsCallback> listener;
2293 {
2294 std::unique_lock lock{mCallbacksLock};
2295 auto found = mCallbackRegistered.find(packageName);
2296 if (found == mCallbackRegistered.end()) {
2297 return false;
2298 }
2299 listener = found->second;
2300 mCallbackRegistered.erase(found);
2301 }
2302
2303 mAppOpsManager->stopWatchingMode(listener);
2304 return true;
2305}
2306
2307void IncrementalService::onAppOpChanged(const std::string& packageName) {
2308 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002309 return;
2310 }
2311
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002312 std::vector<IfsMountPtr> affected;
2313 {
2314 std::lock_guard l(mLock);
2315 affected.reserve(mMounts.size());
2316 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002317 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002318 if (ifs->mountId == id && ifs->dataLoaderStub &&
2319 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002320 affected.push_back(ifs);
2321 }
2322 }
2323 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002324 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002325 std::unique_lock ll(ifs->lock);
2326 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002327 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002328}
2329
Songchun Fana7098592020-09-03 11:45:53 -07002330bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2331 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002332 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002333 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002334 }
Songchun Fana7098592020-09-03 11:45:53 -07002335 timedQueue.addJob(id, after, std::move(what));
2336 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002337}
2338
Songchun Fana7098592020-09-03 11:45:53 -07002339bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002340 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002341 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002342 }
Songchun Fana7098592020-09-03 11:45:53 -07002343 timedQueue.removeJobs(id);
2344 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002345}
2346
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002347void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2348 bool wasEmpty;
2349 {
2350 std::lock_guard l(mIfsStateCallbacksLock);
2351 wasEmpty = mIfsStateCallbacks.empty();
2352 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2353 }
2354 if (wasEmpty) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002355 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002356 [this]() { processIfsStateCallbacks(); });
2357 }
2358}
2359
2360void IncrementalService::processIfsStateCallbacks() {
2361 StorageId storageId = kInvalidStorageId;
2362 std::vector<IfsStateCallback> local;
2363 while (true) {
2364 {
2365 std::lock_guard l(mIfsStateCallbacksLock);
2366 if (mIfsStateCallbacks.empty()) {
2367 return;
2368 }
2369 IfsStateCallbacks::iterator it;
2370 if (storageId == kInvalidStorageId) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002371 // First entry, initialize the |it|.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002372 it = mIfsStateCallbacks.begin();
2373 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002374 // Subsequent entries, update the |storageId|, and shift to the new one (not that
2375 // it guarantees much about updated items, but at least the loop will finish).
2376 it = mIfsStateCallbacks.lower_bound(storageId);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002377 if (it == mIfsStateCallbacks.end()) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002378 // Nothing else left, too bad.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002379 break;
2380 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002381 if (it->first != storageId) {
2382 local.clear(); // Was removed during processing, forget the old callbacks.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002383 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002384 // Put the 'surviving' callbacks back into the map and advance the position.
2385 auto& callbacks = it->second;
2386 if (callbacks.empty()) {
2387 std::swap(callbacks, local);
2388 } else {
2389 callbacks.insert(callbacks.end(), std::move_iterator(local.begin()),
2390 std::move_iterator(local.end()));
2391 local.clear();
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002392 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002393 if (callbacks.empty()) {
2394 it = mIfsStateCallbacks.erase(it);
2395 if (mIfsStateCallbacks.empty()) {
2396 return;
2397 }
2398 } else {
2399 ++it;
2400 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002401 }
2402 }
2403
2404 if (it == mIfsStateCallbacks.end()) {
2405 break;
2406 }
2407
2408 storageId = it->first;
2409 auto& callbacks = it->second;
2410 if (callbacks.empty()) {
2411 // Invalid case, one extra lookup should be ok.
2412 continue;
2413 }
2414 std::swap(callbacks, local);
2415 }
2416
2417 processIfsStateCallbacks(storageId, local);
2418 }
2419
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002420 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002421 [this]() { processIfsStateCallbacks(); });
2422}
2423
2424void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2425 std::vector<IfsStateCallback>& callbacks) {
2426 const auto state = isMountFullyLoaded(storageId);
2427 IfsState storageState = {};
2428 storageState.error = int(state) < 0;
2429 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2430 if (storageState.fullyLoaded) {
2431 const auto ifs = getIfs(storageId);
2432 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2433 }
2434
2435 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2436 if ((*cur)(storageId, storageState)) {
2437 ++cur;
2438 } else {
2439 cur = callbacks.erase(cur);
2440 }
2441 }
2442}
2443
2444void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2445 std::lock_guard l(mIfsStateCallbacksLock);
2446 mIfsStateCallbacks.erase(storageId);
2447}
2448
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002449void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002450 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002451 if (!ifs) {
Songchun Fan9471be52021-04-21 17:49:27 -07002452 LOG(ERROR) << "getMetrics failed, invalid storageId: " << storageId;
2453 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002454 }
Songchun Fan0dc77722021-05-03 17:13:52 -07002455 const auto& kMetricsReadLogsEnabled =
Songchun Fan9471be52021-04-21 17:49:27 -07002456 os::incremental::BnIncrementalService::METRICS_READ_LOGS_ENABLED();
Songchun Fan0dc77722021-05-03 17:13:52 -07002457 result->putBoolean(String16(kMetricsReadLogsEnabled.c_str()), ifs->readLogsEnabled() != 0);
2458 const auto incfsMetrics = mIncFs->getMetrics(path::basename(ifs->root));
2459 if (incfsMetrics) {
2460 const auto& kMetricsTotalDelayedReads =
2461 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS();
2462 const auto totalDelayedReads =
2463 incfsMetrics->readsDelayedMin + incfsMetrics->readsDelayedPending;
2464 result->putInt(String16(kMetricsTotalDelayedReads.c_str()), totalDelayedReads);
2465 const auto& kMetricsTotalFailedReads =
2466 os::incremental::BnIncrementalService::METRICS_TOTAL_FAILED_READS();
2467 const auto totalFailedReads = incfsMetrics->readsFailedTimedOut +
2468 incfsMetrics->readsFailedHashVerification + incfsMetrics->readsFailedOther;
2469 result->putInt(String16(kMetricsTotalFailedReads.c_str()), totalFailedReads);
2470 const auto& kMetricsTotalDelayedReadsMillis =
2471 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS_MILLIS();
2472 const int64_t totalDelayedReadsMillis =
2473 (incfsMetrics->readsDelayedMinUs + incfsMetrics->readsDelayedPendingUs) / 1000;
2474 result->putLong(String16(kMetricsTotalDelayedReadsMillis.c_str()), totalDelayedReadsMillis);
2475 }
2476 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
2477 if (lastReadError && lastReadError->timestampUs != 0) {
2478 const auto& kMetricsMillisSinceLastReadError =
2479 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_READ_ERROR();
2480 result->putLong(String16(kMetricsMillisSinceLastReadError.c_str()),
2481 (int64_t)elapsedUsSinceMonoTs(lastReadError->timestampUs) / 1000);
2482 const auto& kMetricsLastReadErrorNo =
2483 os::incremental::BnIncrementalService::METRICS_LAST_READ_ERROR_NUMBER();
2484 result->putInt(String16(kMetricsLastReadErrorNo.c_str()), lastReadError->errorNo);
2485 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002486 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002487 if (!ifs->dataLoaderStub) {
Songchun Fan9471be52021-04-21 17:49:27 -07002488 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002489 }
Songchun Fan9471be52021-04-21 17:49:27 -07002490 ifs->dataLoaderStub->getMetrics(result);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002491}
2492
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002493IncrementalService::DataLoaderStub::DataLoaderStub(
2494 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2495 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2496 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2497 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002498 : mService(service),
2499 mId(id),
2500 mParams(std::move(params)),
2501 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002502 mStatusListener(std::move(statusListener)),
2503 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002504 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002505 mHealthCheckParams(healthCheckParams) {
2506 if (mHealthListener && !isHealthParamsValid()) {
2507 mHealthListener = {};
2508 }
2509 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002510 // Disable advanced health check statuses.
2511 mHealthCheckParams.blockedTimeoutMs = -1;
2512 }
2513 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002514}
2515
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002516IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002517 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002518 cleanupResources();
2519 }
2520}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002521
2522void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002523 auto now = Clock::now();
2524 {
2525 std::unique_lock lock(mMutex);
2526 mHealthPath.clear();
2527 unregisterFromPendingReads();
2528 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002529 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002530 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002531 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002532
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002533 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002534
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002535 {
2536 std::unique_lock lock(mMutex);
2537 mParams = {};
2538 mControl = {};
2539 mHealthControl = {};
2540 mHealthListener = {};
2541 mStatusCondition.wait_until(lock, now + 60s, [this] {
2542 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2543 });
2544 mStatusListener = {};
2545 mId = kInvalidStorageId;
2546 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002547}
2548
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002549sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2550 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002551 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002552 if (!status.isOk()) {
2553 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2554 return {};
2555 }
2556 if (!dataloader) {
2557 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2558 return {};
2559 }
2560 return dataloader;
2561}
2562
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002563bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2564 return (params().packageName == Constants::systemPackage);
2565}
2566
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002567bool IncrementalService::DataLoaderStub::requestCreate() {
2568 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2569}
2570
2571bool IncrementalService::DataLoaderStub::requestStart() {
2572 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2573}
2574
2575bool IncrementalService::DataLoaderStub::requestDestroy() {
2576 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2577}
2578
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002579bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002580 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002581 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002582 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002583 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002584 return fsmStep();
2585}
2586
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002587void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002588 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002589 mTargetStatus = status;
2590 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002591 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002592 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002593}
2594
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002595std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002596 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002597
2598 const auto now = mService.mClock->now();
2599 const bool healthy = (mPreviousBindDelay == 0ms);
2600
2601 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2602 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2603 LOG(INFO) << "Binding still in progress. "
2604 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002605 : "Already unhealthy, don't do anything.")
2606 << " for storage " << mId;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002607 // Binding still in progress.
2608 if (!healthy) {
2609 // Already unhealthy, don't do anything.
2610 return {};
2611 }
2612 // The DL is healthy/freshly bound, ok to retry for a few times.
2613 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2614 // Still within grace period.
2615 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2616 // Retry interval passed, retrying.
2617 mCurrentStatusTs = now;
2618 mPreviousBindDelay = 0ms;
2619 return 0ms;
2620 }
2621 return {};
2622 }
2623 // fallthrough, mark as unhealthy, and retry with delay
2624 }
2625
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002626 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002627 mPreviousBindTs = now;
2628
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002629 const auto nonCrashingInterval =
2630 std::max(castToMs(now - previousBindTs - mPreviousBindDelay), 100ms);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002631 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2632 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2633 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002634 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002635 }
2636
2637 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2638 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2639
2640 const auto bindDelayMs =
2641 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2642 maxBindDelayMs)
2643 .count();
2644 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -07002645 // rand() is enough, not worth maintaining a full-blown <rand> object for delay jitter
2646 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - // NOLINT
2647 bindDelayJitterRangeMs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002648 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002649 return mPreviousBindDelay;
2650}
2651
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002652bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002653 const auto maybeBindDelay = needToBind();
2654 if (!maybeBindDelay) {
2655 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2656 return true;
2657 }
2658 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002659 if (bindDelay > 1s) {
2660 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002661 << bindDelay.count() / 1000 << "s"
2662 << " for storage " << mId;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002663 }
2664
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002665 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002666 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2667 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002668 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002669 const bool healthy = (bindDelay == 0ms);
2670 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2671 << (healthy ? ", retrying." : "");
2672
2673 // Internal error, retry for healthy/new DLs.
2674 // Let needToBind migrate it to unhealthy after too many retries.
2675 if (healthy) {
2676 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2677 [this]() { fsmStep(); })) {
2678 // Mark as binding so that we know it's not the DL's fault.
2679 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2680 return true;
2681 }
2682 }
2683
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002684 return false;
2685 }
2686 return true;
2687}
2688
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002689bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002690 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002691 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002692 return false;
2693 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002694 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002695 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002696 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002697 return false;
2698 }
2699 return true;
2700}
2701
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002702bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002703 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002704 if (!dataloader) {
2705 return false;
2706 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002707 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002708 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002709 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002710 return false;
2711 }
2712 return true;
2713}
2714
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002715bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002716 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002717}
2718
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002719bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002720 if (!isValid()) {
2721 return false;
2722 }
2723
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002724 int currentStatus;
2725 int targetStatus;
2726 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002727 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002728 currentStatus = mCurrentStatus;
2729 targetStatus = mTargetStatus;
2730 }
2731
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002732 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002733
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002734 if (currentStatus == targetStatus) {
2735 return true;
2736 }
2737
2738 switch (targetStatus) {
2739 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002740 switch (currentStatus) {
2741 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2742 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2743 return true;
2744 default:
2745 return destroy();
2746 }
2747 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002748 }
2749 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2750 switch (currentStatus) {
2751 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2752 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2753 return start();
2754 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002755 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002756 }
2757 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2758 switch (currentStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002759 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002760 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2761 // Before binding need to make sure we are unbound.
2762 // Otherwise we'll get stuck binding.
2763 return destroy();
2764 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002765 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002766 return bind();
2767 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002768 return create();
2769 }
2770 break;
2771 default:
2772 LOG(ERROR) << "Invalid target status: " << targetStatus
2773 << ", current status: " << currentStatus;
2774 break;
2775 }
2776 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002777}
2778
2779binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002780 if (!isValid()) {
2781 return binder::Status::
2782 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2783 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002784 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002785 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2786 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002787 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2788 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002789 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2790 newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002791 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2792 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2793 [this, newStatus]() { setCurrentStatus(newStatus); });
2794 return binder::Status::ok();
2795 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002796
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002797 setCurrentStatus(newStatus);
2798 return binder::Status::ok();
2799}
2800
2801void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002802 int oldStatus, oldTargetStatus, newTargetStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002803 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002804 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002805 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002806 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002807 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002808 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002809
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002810 oldStatus = mCurrentStatus;
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002811 oldTargetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002812 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002813
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002814 // Change the status.
2815 mCurrentStatus = newStatus;
2816 mCurrentStatusTs = mService.mClock->now();
2817
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002818 switch (mCurrentStatus) {
2819 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2820 // Unavailable, retry.
2821 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2822 break;
2823 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2824 // Unrecoverable, just unbind.
2825 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2826 break;
2827 default:
2828 break;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002829 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002830
2831 newTargetStatus = mTargetStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002832 }
2833
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002834 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002835 << newStatus << " (target " << oldTargetStatus << " -> " << newTargetStatus << ")";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002836
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002837 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002838 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002839 }
2840
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002841 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002842
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002843 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002844}
2845
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002846bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2847 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2848 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002849}
2850
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002851void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002852 int healthStatus) {
2853 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2854 if (healthListener) {
2855 healthListener->onHealthStatus(id(), healthStatus);
2856 }
Songchun Fan9471be52021-04-21 17:49:27 -07002857 mHealthStatus = healthStatus;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002858}
2859
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002860void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2861 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002862
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002863 int healthStatusToReport = -1;
2864 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002865
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002866 {
2867 std::unique_lock lock(mMutex);
2868 unregisterFromPendingReads();
2869
2870 healthListener = mHealthListener;
2871
2872 // Healthcheck depends on timestamp of the oldest pending read.
2873 // 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 -07002874 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2875 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002876 const auto now = Clock::now();
2877 const auto kernelTsUs = getOldestPendingReadTs();
2878 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002879 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2880 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002881 mHealthBase = {now, kernelTsUs};
2882 }
2883
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002884 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2885 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002886 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2887 registerForPendingReads();
2888 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2889 lock.unlock();
2890 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002891 return;
2892 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002893
2894 resetHealthControl();
2895
2896 // Always make sure the data loader is started.
2897 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2898
2899 // Skip any further processing if health check params are invalid.
2900 if (!isHealthParamsValid()) {
2901 LOG(DEBUG) << id()
2902 << ": Skip any further processing if health check params are invalid.";
2903 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2904 lock.unlock();
2905 onHealthStatus(healthListener, healthStatusToReport);
2906 // Triggering data loader start. This is a one-time action.
2907 fsmStep();
2908 return;
2909 }
2910
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002911 // Don't schedule timer job less than 500ms in advance.
2912 static constexpr auto kTolerance = 500ms;
2913
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002914 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2915 const auto unhealthyTimeout =
2916 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2917 const auto unhealthyMonitoring =
2918 std::max(1000ms,
2919 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2920
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002921 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002922
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002923 Milliseconds checkBackAfter;
2924 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002925 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002926 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002927 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002928 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002929 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002930 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002931 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2932 } else {
2933 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002934 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002935 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2936 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002937 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002938 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002939 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2940 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002941 }
2942
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002943 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002944 if (healthStatusToReport != -1) {
2945 onHealthStatus(healthListener, healthStatusToReport);
2946 }
2947
2948 fsmStep();
2949}
2950
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002951Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2952 BootClockTsUs kernelTsUs) {
2953 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2954 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2955 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2956}
2957
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002958const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2959 if (mHealthPath.empty()) {
2960 resetHealthControl();
2961 return mHealthControl;
2962 }
2963 if (mHealthControl.pendingReads() < 0) {
2964 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2965 }
2966 if (mHealthControl.pendingReads() < 0) {
2967 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2968 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2969 << mHealthControl.logs() << ")";
2970 }
2971 return mHealthControl;
2972}
2973
2974void IncrementalService::DataLoaderStub::resetHealthControl() {
2975 mHealthControl = {};
2976}
2977
2978BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2979 auto result = kMaxBootClockTsUs;
2980
2981 const auto& control = initializeHealthControl();
2982 if (control.pendingReads() < 0) {
2983 return result;
2984 }
2985
Songchun Fan6944f1e2020-11-06 15:24:24 -08002986 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002987 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002988 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002989 // Clear previous pending reads
2990 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002991 return result;
2992 }
2993
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07002994 LOG(DEBUG) << id() << ": pendingReads: fd(" << control.pendingReads() << "), count("
2995 << mLastPendingReads.size() << "), block: " << mLastPendingReads.front().block
2996 << ", time: " << mLastPendingReads.front().bootClockTsUs
2997 << ", uid: " << mLastPendingReads.front().uid;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002998
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002999 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003000}
3001
3002void IncrementalService::DataLoaderStub::registerForPendingReads() {
3003 const auto pendingReadsFd = mHealthControl.pendingReads();
3004 if (pendingReadsFd < 0) {
3005 return;
3006 }
3007
3008 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
3009
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003010 mService.mLooper->addFd(
3011 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
3012 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07003013 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003014 self->updateHealthStatus(/*baseline=*/true);
3015 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003016 },
3017 this);
3018 mService.mLooper->wake();
3019}
3020
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003021BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
3022 auto result = kMaxBootClockTsUs;
3023 for (auto&& pendingRead : mLastPendingReads) {
3024 result = std::min(result, pendingRead.bootClockTsUs);
3025 }
3026 return result;
3027}
3028
Songchun Fan9471be52021-04-21 17:49:27 -07003029void IncrementalService::DataLoaderStub::getMetrics(android::os::PersistableBundle* result) {
3030 const auto duration = elapsedMsSinceOldestPendingRead();
3031 if (duration >= 0) {
Songchun Fan0dc77722021-05-03 17:13:52 -07003032 const auto& kMetricsMillisSinceOldestPendingRead =
Songchun Fan9471be52021-04-21 17:49:27 -07003033 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
Songchun Fan0dc77722021-05-03 17:13:52 -07003034 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.c_str()), duration);
Songchun Fan9471be52021-04-21 17:49:27 -07003035 }
Songchun Fan0dc77722021-05-03 17:13:52 -07003036 const auto& kMetricsStorageHealthStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003037 os::incremental::BnIncrementalService::METRICS_STORAGE_HEALTH_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003038 result->putInt(String16(kMetricsStorageHealthStatusCode.c_str()), mHealthStatus);
3039 const auto& kMetricsDataLoaderStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003040 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003041 result->putInt(String16(kMetricsDataLoaderStatusCode.c_str()), mCurrentStatus);
3042 const auto& kMetricsMillisSinceLastDataLoaderBind =
Songchun Fan9471be52021-04-21 17:49:27 -07003043 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_DATA_LOADER_BIND();
Songchun Fan0dc77722021-05-03 17:13:52 -07003044 result->putLong(String16(kMetricsMillisSinceLastDataLoaderBind.c_str()),
3045 elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000);
3046 const auto& kMetricsDataLoaderBindDelayMillis =
Songchun Fan9471be52021-04-21 17:49:27 -07003047 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_BIND_DELAY_MILLIS();
Songchun Fan0dc77722021-05-03 17:13:52 -07003048 result->putLong(String16(kMetricsDataLoaderBindDelayMillis.c_str()),
3049 mPreviousBindDelay.count());
Songchun Fan9471be52021-04-21 17:49:27 -07003050}
3051
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003052long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
3053 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
3054 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
3055 return 0;
3056 }
3057 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
3058}
3059
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07003060void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003061 const auto pendingReadsFd = mHealthControl.pendingReads();
3062 if (pendingReadsFd < 0) {
3063 return;
3064 }
3065
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003066 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
3067
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003068 mService.mLooper->removeFd(pendingReadsFd);
3069 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003070}
3071
Songchun Fan2570ec02020-10-08 17:22:33 -07003072void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003073 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07003074 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003075 mHealthCheckParams = healthCheckParams;
3076 mHealthListener = std::move(healthListener);
3077 if (!mHealthListener) {
3078 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07003079 }
3080}
3081
Songchun Fan6944f1e2020-11-06 15:24:24 -08003082static std::string toHexString(const RawMetadata& metadata) {
3083 int n = metadata.size();
3084 std::string res(n * 2, '\0');
3085 // Same as incfs::toString(fileId)
3086 static constexpr char kHexChar[] = "0123456789abcdef";
3087 for (int i = 0; i < n; ++i) {
3088 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
3089 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
3090 }
3091 return res;
3092}
3093
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003094void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003095 dprintf(fd, " dataLoader: {\n");
3096 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08003097 dprintf(fd, " currentStatusTs: %lldmcs\n",
3098 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003099 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
3100 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003101 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003102 dprintf(fd, " health: {\n");
3103 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3104 dprintf(fd, " base: %lldmcs (%lld)\n",
3105 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3106 (long long)mHealthBase.kernelTsUs);
3107 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3108 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3109 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3110 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003111 dprintf(fd, " lastPendingReads: \n");
3112 const auto control = mService.mIncFs->openMount(mHealthPath);
3113 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003114 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003115 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3116 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3117 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3118 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3119 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003120 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
Songchun Fan9471be52021-04-21 17:49:27 -07003121 (long long)(elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000000),
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003122 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003123 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003124 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003125 dprintf(fd, " dataLoaderParams: {\n");
3126 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3127 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3128 dprintf(fd, " className: %s\n", params.className.c_str());
3129 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3130 dprintf(fd, " }\n");
3131 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003132}
3133
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003134void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3135 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003136}
3137
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003138binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3139 bool enableReadLogs, int32_t* _aidl_return) {
3140 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3141 return binder::Status::ok();
3142}
3143
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003144FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3145 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3146}
3147
Songchun Fan3c82a302019-11-29 14:23:45 -08003148} // namespace android::incremental