blob: 68b5bd975dbce7451aebc374d11ce1d79b752719 [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "IncrementalService"
18
19#include "IncrementalService.h"
20
Songchun Fan3c82a302019-11-29 14:23:45 -080021#include <android-base/logging.h>
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -070022#include <android-base/no_destructor.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080023#include <android-base/properties.h>
24#include <android-base/stringprintf.h>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070025#include <binder/AppOpsManager.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080026#include <binder/Status.h>
27#include <sys/stat.h>
28#include <uuid/uuid.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080029
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070030#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080031#include <ctime>
Songchun Fan3c82a302019-11-29 14:23:45 -080032#include <iterator>
33#include <span>
Songchun Fan3c82a302019-11-29 14:23:45 -080034#include <type_traits>
35
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070036#include "IncrementalServiceValidation.h"
Songchun Fan3c82a302019-11-29 14:23:45 -080037#include "Metadata.pb.h"
38
39using namespace std::literals;
Songchun Fan3c82a302019-11-29 14:23:45 -080040
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -080041constexpr const char* kLoaderUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070042constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070043
Alex Buynytskyy42d4ba42021-01-12 11:10:03 -080044constexpr const char* kInteractAcrossUsers = "android.permission.INTERACT_ACROSS_USERS";
45
Songchun Fan3c82a302019-11-29 14:23:45 -080046namespace android::incremental {
47
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070048using content::pm::DataLoaderParamsParcel;
49using content::pm::FileSystemControlParcel;
50using content::pm::IDataLoader;
51
Songchun Fan3c82a302019-11-29 14:23:45 -080052namespace {
53
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070054using IncrementalFileSystemControlParcel = os::incremental::IncrementalFileSystemControlParcel;
Songchun Fan3c82a302019-11-29 14:23:45 -080055
56struct Constants {
57 static constexpr auto backing = "backing_store"sv;
58 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080059 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080060 static constexpr auto storagePrefix = "st"sv;
61 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
62 static constexpr auto infoMdName = ".info"sv;
Alex Buynytskyy04035452020-06-06 20:15:58 -070063 static constexpr auto readLogsDisabledMarkerName = ".readlogs_disabled"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080064 static constexpr auto libDir = "lib"sv;
65 static constexpr auto libSuffix = ".so"sv;
66 static constexpr auto blockSize = 4096;
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -070067 static constexpr auto systemPackage = "android"sv;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -080068
Alex Buynytskyy060c9d62021-02-18 20:55:17 -080069 static constexpr auto userStatusDelay = 100ms;
70
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -080071 static constexpr auto progressUpdateInterval = 1000ms;
72 static constexpr auto perUidTimeoutOffset = progressUpdateInterval * 2;
73 static constexpr auto minPerUidTimeout = progressUpdateInterval * 3;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080074
75 // If DL was up and not crashing for 10mins, we consider it healthy and reset all delays.
76 static constexpr auto healthyDataLoaderUptime = 10min;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -080077
78 // For healthy DLs, we'll retry every ~5secs for ~10min
79 static constexpr auto bindRetryInterval = 5s;
80 static constexpr auto bindGracePeriod = 10min;
81
82 static constexpr auto bindingTimeout = 1min;
83
Alex Buynytskyy7b3e06e2021-03-23 11:29:05 -070084 // 1s, 10s, 100s (~2min), 1000s (~15min), 10000s (~3hrs)
85 static constexpr auto minBindDelay = 1s;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080086 static constexpr auto maxBindDelay = 10000s;
87 static constexpr auto bindDelayMultiplier = 10;
88 static constexpr auto bindDelayJitterDivider = 10;
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -070089
90 // Max interval after system invoked the DL when readlog collection can be enabled.
91 static constexpr auto readLogsMaxInterval = 2h;
Songchun Fan3c82a302019-11-29 14:23:45 -080092};
93
94static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070095 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080096 return c;
97}
98
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -070099static bool isPageAligned(IncFsSize s) {
100 return (s & (Constants::blockSize - 1)) == 0;
101}
102
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700103static bool getAlwaysEnableReadTimeoutsForSystemDataLoaders() {
104 return android::base::
105 GetBoolProperty("debug.incremental.always_enable_read_timeouts_for_system_dataloaders",
106 true);
107}
108
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700109static bool getEnforceReadLogsMaxIntervalForSystemDataLoaders() {
110 return android::base::GetBoolProperty("debug.incremental.enforce_readlogs_max_interval_for_"
111 "system_dataloaders",
112 false);
113}
114
115static Seconds getReadLogsMaxInterval() {
116 constexpr int limit = duration_cast<Seconds>(Constants::readLogsMaxInterval).count();
117 int readlogs_max_interval_secs =
118 std::min(limit,
119 android::base::GetIntProperty<
120 int>("debug.incremental.readlogs_max_interval_sec", limit));
121 return Seconds{readlogs_max_interval_secs};
122}
123
Songchun Fan3c82a302019-11-29 14:23:45 -0800124template <base::LogSeverity level = base::ERROR>
125bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
126 auto cstr = path::c_str(name);
127 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800128 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800129 PLOG(level) << "Can't create directory '" << name << '\'';
130 return false;
131 }
132 struct stat st;
133 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
134 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
135 return false;
136 }
137 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800138 if (::chmod(cstr, mode)) {
139 PLOG(level) << "Changing permission failed for '" << name << '\'';
140 return false;
141 }
142
Songchun Fan3c82a302019-11-29 14:23:45 -0800143 return true;
144}
145
146static std::string toMountKey(std::string_view path) {
147 if (path.empty()) {
148 return "@none";
149 }
150 if (path == "/"sv) {
151 return "@root";
152 }
153 if (path::isAbsolute(path)) {
154 path.remove_prefix(1);
155 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700156 if (path.size() > 16) {
157 path = path.substr(0, 16);
158 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800159 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700160 std::replace_if(
161 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
162 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800163}
164
165static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
166 std::string_view path) {
167 auto mountKey = toMountKey(path);
168 const auto prefixSize = mountKey.size();
169 for (int counter = 0; counter < 1000;
170 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
171 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800172 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800173 return {mountKey, mountRoot};
174 }
175 }
176 return {};
177}
178
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700179template <class Map>
180typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
181 const auto nextIt = map.upper_bound(path);
182 if (nextIt == map.begin()) {
183 return map.end();
184 }
185 const auto suspectIt = std::prev(nextIt);
186 if (!path::startsWith(path, suspectIt->first)) {
187 return map.end();
188 }
189 return suspectIt;
190}
191
192static base::unique_fd dup(base::borrowed_fd fd) {
193 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
194 return base::unique_fd(res);
195}
196
Songchun Fan3c82a302019-11-29 14:23:45 -0800197template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700198static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800199 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800200 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800201 ProtoMessage message;
202 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
203}
204
205static bool isValidMountTarget(std::string_view path) {
206 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
207}
208
209std::string makeBindMdName() {
210 static constexpr auto uuidStringSize = 36;
211
212 uuid_t guid;
213 uuid_generate(guid);
214
215 std::string name;
216 const auto prefixSize = constants().mountpointMdPrefix.size();
217 name.reserve(prefixSize + uuidStringSize);
218
219 name = constants().mountpointMdPrefix;
220 name.resize(prefixSize + uuidStringSize);
221 uuid_unparse(guid, name.data() + prefixSize);
222
223 return name;
224}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700225
226static bool checkReadLogsDisabledMarker(std::string_view root) {
227 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
228 struct stat st;
229 return (::stat(markerPath, &st) == 0);
230}
231
Songchun Fan3c82a302019-11-29 14:23:45 -0800232} // namespace
233
234IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700235 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700236 dataLoaderStub->cleanupResources();
237 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700238 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700239 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800240 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
241 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700242 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800243 incrementalService.mVold->unmountIncFs(target);
244 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700245 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800246 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
247 cleanupFilesystem(root);
248}
249
250auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800251 std::string name;
252 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
253 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
254 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800255 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
256 constants().storagePrefix.data(), id, no);
257 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800258 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800259 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800260 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
261 } else if (err != EEXIST) {
262 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
263 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800264 }
265 }
266 nextStorageDirNo = 0;
267 return storages.end();
268}
269
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700270template <class Func>
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700271static auto makeCleanup(Func&& f) requires(!std::is_lvalue_reference_v<Func>) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700272 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700273 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700274 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
275}
276
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700277static auto openDir(const char* dir) {
278 struct DirCloser {
279 void operator()(DIR* d) const noexcept { ::closedir(d); }
280 };
281 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700282}
283
284static auto openDir(std::string_view dir) {
285 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800286}
287
288static int rmDirContent(const char* path) {
289 auto dir = openDir(path);
290 if (!dir) {
291 return -EINVAL;
292 }
293 while (auto entry = ::readdir(dir.get())) {
294 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
295 continue;
296 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700297 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800298 if (entry->d_type == DT_DIR) {
299 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
300 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
301 return err;
302 }
303 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
304 PLOG(WARNING) << "Failed to rmdir " << fullPath;
305 return err;
306 }
307 } else {
308 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
309 PLOG(WARNING) << "Failed to delete " << fullPath;
310 return err;
311 }
312 }
313 }
314 return 0;
315}
316
Songchun Fan3c82a302019-11-29 14:23:45 -0800317void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800318 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800319 ::rmdir(path::join(root, constants().backing).c_str());
320 ::rmdir(path::join(root, constants().mount).c_str());
321 ::rmdir(path::c_str(root));
322}
323
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700324void IncrementalService::IncFsMount::setFlag(StorageFlags flag, bool value) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700325 if (value) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700326 flags |= flag;
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700327 } else {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700328 flags &= ~flag;
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700329 }
330}
331
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800332IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800333 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800334 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800335 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700336 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700337 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700338 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700339 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700340 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700341 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800342 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800343 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700344 CHECK(mVold) << "Vold service is unavailable";
345 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
346 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
347 CHECK(mJni) << "JNI is unavailable";
348 CHECK(mLooper) << "Looper is unavailable";
349 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700350 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700351 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800352 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700353
354 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700355 mJobProcessor = std::thread([this]() {
356 mJni->initializeForCurrentThread();
357 runJobProcessing();
358 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700359 mCmdLooperThread = std::thread([this]() {
360 mJni->initializeForCurrentThread();
361 runCmdLooper();
362 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700363
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700364 const auto mountedRootNames = adoptMountedInstances();
365 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800366}
367
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700368IncrementalService::~IncrementalService() {
369 {
370 std::lock_guard lock(mJobMutex);
371 mRunning = false;
372 }
373 mJobCondition.notify_all();
374 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700375 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700376 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700377 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700378 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700379 // Ensure that mounts are destroyed while the service is still valid.
380 mBindsByPath.clear();
381 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700382}
Songchun Fan3c82a302019-11-29 14:23:45 -0800383
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700384static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800385 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800386 case IncrementalService::BindKind::Temporary:
387 return "Temporary";
388 case IncrementalService::BindKind::Permanent:
389 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800390 }
391}
392
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700393template <class Duration>
394static long elapsedMcs(Duration start, Duration end) {
395 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
396}
397
Songchun Fand48a25e2021-04-30 09:50:58 -0700398static uint64_t elapsedUsSinceMonoTs(uint64_t monoTsUs) {
399 timespec now;
400 if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) {
401 return 0;
402 }
403 uint64_t nowUs = now.tv_sec * 1000000LL + now.tv_nsec / 1000;
404 return nowUs - monoTsUs;
405}
406
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800407void IncrementalService::onDump(int fd) {
408 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
409 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
410
411 std::unique_lock l(mLock);
412
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700413 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800414 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700415 std::unique_lock ll(ifs->lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700416 const IncFsMount& mnt = *ifs;
417 dprintf(fd, " [%d]: {\n", id);
418 if (id != mnt.mountId) {
419 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
420 } else {
421 dprintf(fd, " mountId: %d\n", mnt.mountId);
422 dprintf(fd, " root: %s\n", mnt.root.c_str());
Songchun Fanf949c372021-04-27 11:26:25 -0700423 const auto metricsInstanceName = path::basename(ifs->root);
424 dprintf(fd, " metrics instance name: %s\n", path::c_str(metricsInstanceName).get());
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700425 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700426 dprintf(fd, " flags: %d\n", int(mnt.flags));
427 if (mnt.startLoadingTs.time_since_epoch() == Clock::duration::zero()) {
428 dprintf(fd, " not loading\n");
429 } else {
430 dprintf(fd, " startLoading: %llds\n",
431 (long long)(elapsedMcs(mnt.startLoadingTs, Clock::now()) / 1000000));
432 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700433 if (mnt.dataLoaderStub) {
434 mnt.dataLoaderStub->onDump(fd);
435 } else {
436 dprintf(fd, " dataLoader: null\n");
437 }
438 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
439 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700440 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700441 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800442 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700443 }
444 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800445
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700446 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
447 for (auto&& [target, bind] : mnt.bindPoints) {
448 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
449 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
450 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
451 dprintf(fd, " kind: %s\n", toString(bind.kind));
452 }
453 dprintf(fd, " }\n");
Songchun Fanf949c372021-04-27 11:26:25 -0700454
455 dprintf(fd, " incfsMetrics: {\n");
456 const auto incfsMetrics = mIncFs->getMetrics(metricsInstanceName);
457 if (incfsMetrics) {
458 dprintf(fd, " readsDelayedMin: %d\n", incfsMetrics.value().readsDelayedMin);
459 dprintf(fd, " readsDelayedMinUs: %lld\n",
460 (long long)incfsMetrics.value().readsDelayedMinUs);
461 dprintf(fd, " readsDelayedPending: %d\n",
462 incfsMetrics.value().readsDelayedPending);
463 dprintf(fd, " readsDelayedPendingUs: %lld\n",
464 (long long)incfsMetrics.value().readsDelayedPendingUs);
465 dprintf(fd, " readsFailedHashVerification: %d\n",
466 incfsMetrics.value().readsFailedHashVerification);
467 dprintf(fd, " readsFailedOther: %d\n", incfsMetrics.value().readsFailedOther);
468 dprintf(fd, " readsFailedTimedOut: %d\n",
469 incfsMetrics.value().readsFailedTimedOut);
470 } else {
471 dprintf(fd, " Metrics not available. Errno: %d\n", errno);
472 }
473 dprintf(fd, " }\n");
Songchun Fand48a25e2021-04-30 09:50:58 -0700474
475 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
476 const auto errorNo = errno;
477 dprintf(fd, " lastReadError: {\n");
478 if (lastReadError) {
479 if (lastReadError->timestampUs == 0) {
480 dprintf(fd, " No read errors.\n");
481 } else {
482 dprintf(fd, " fileId: %s\n",
483 IncFsWrapper::toString(lastReadError->id).c_str());
484 dprintf(fd, " time: %llu microseconds ago\n",
485 (unsigned long long)elapsedUsSinceMonoTs(lastReadError->timestampUs));
486 dprintf(fd, " blockIndex: %d\n", lastReadError->block);
487 dprintf(fd, " errno: %d\n", lastReadError->errorNo);
488 }
489 } else {
490 dprintf(fd, " Info not available. Errno: %d\n", errorNo);
491 }
492 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800493 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700494 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800495 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700496 dprintf(fd, "}\n");
497 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800498 for (auto&& [target, mountPairIt] : mBindsByPath) {
499 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700500 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
501 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
502 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
503 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800504 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700505 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800506}
507
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800508bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700509 if (!ifs.dataLoaderStub) {
510 return false;
511 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700512 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800513 return true;
514 }
515
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700516 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800517}
518
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700519void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800520 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700521 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800522 }
523
524 std::vector<IfsMountPtr> mounts;
525 {
526 std::lock_guard l(mLock);
527 mounts.reserve(mMounts.size());
528 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700529 std::unique_lock ll(ifs->lock);
530
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800531 if (ifs->mountId != id) {
532 continue;
533 }
534
535 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800536 mounts.push_back(ifs);
537 }
538 }
539 }
540
Alex Buynytskyy69941662020-04-11 21:40:37 -0700541 if (mounts.empty()) {
542 return;
543 }
544
Songchun Fan3c82a302019-11-29 14:23:45 -0800545 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700546 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800547 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700548 std::unique_lock l(ifs->lock);
549 if (ifs->dataLoaderStub) {
550 ifs->dataLoaderStub->requestStart();
551 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800552 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800553 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800554}
555
556auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
557 for (;;) {
558 if (mNextId == kMaxStorageId) {
559 mNextId = 0;
560 }
561 auto id = ++mNextId;
562 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
563 if (inserted) {
564 return it;
565 }
566 }
567}
568
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700569StorageId IncrementalService::createStorage(std::string_view mountPoint,
570 content::pm::DataLoaderParamsParcel dataLoaderParams,
571 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800572 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
573 if (!path::isAbsolute(mountPoint)) {
574 LOG(ERROR) << "path is not absolute: " << mountPoint;
575 return kInvalidStorageId;
576 }
577
578 auto mountNorm = path::normalize(mountPoint);
579 {
580 const auto id = findStorageId(mountNorm);
581 if (id != kInvalidStorageId) {
582 if (options & CreateOptions::OpenExisting) {
583 LOG(INFO) << "Opened existing storage " << id;
584 return id;
585 }
586 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
587 return kInvalidStorageId;
588 }
589 }
590
591 if (!(options & CreateOptions::CreateNew)) {
592 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
593 return kInvalidStorageId;
594 }
595
596 if (!path::isEmptyDir(mountNorm)) {
597 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
598 return kInvalidStorageId;
599 }
600 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
601 if (mountRoot.empty()) {
602 LOG(ERROR) << "Bad mount point";
603 return kInvalidStorageId;
604 }
605 // Make sure the code removes all crap it may create while still failing.
606 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
607 auto firstCleanupOnFailure =
608 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
609
610 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800611 const auto backing = path::join(mountRoot, constants().backing);
612 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800613 return kInvalidStorageId;
614 }
615
Songchun Fan3c82a302019-11-29 14:23:45 -0800616 IncFsMount::Control control;
617 {
618 std::lock_guard l(mMountOperationLock);
619 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800620
621 if (auto err = rmDirContent(backing.c_str())) {
622 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
623 return kInvalidStorageId;
624 }
625 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
626 return kInvalidStorageId;
627 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800628 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
629 return kInvalidStorageId;
630 }
Songchun Fanf949c372021-04-27 11:26:25 -0700631 auto status = mVold->mountIncFs(backing, mountTarget, 0, mountKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800632 if (!status.isOk()) {
633 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
634 return kInvalidStorageId;
635 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800636 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
637 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800638 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
639 return kInvalidStorageId;
640 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800641 int cmd = controlParcel.cmd.release().release();
642 int pendingReads = controlParcel.pendingReads.release().release();
643 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800644 int blocksWritten =
645 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
646 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800647 }
648
649 std::unique_lock l(mLock);
650 const auto mountIt = getStorageSlotLocked();
651 const auto mountId = mountIt->first;
652 l.unlock();
653
654 auto ifs =
655 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
656 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
657 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700658 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800659
660 auto secondCleanup = [this, &l](auto itPtr) {
661 if (!l.owns_lock()) {
662 l.lock();
663 }
664 mMounts.erase(*itPtr);
665 };
666 auto secondCleanupOnFailure =
667 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
668
669 const auto storageIt = ifs->makeStorage(ifs->mountId);
670 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800671 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800672 return kInvalidStorageId;
673 }
674
675 {
676 metadata::Mount m;
677 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700678 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700679 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
680 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
681 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800682 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800683 if (auto err =
684 mIncFs->makeFile(ifs->control,
685 path::join(ifs->root, constants().mount,
686 constants().infoMdName),
687 0777, idFromMetadata(metadata),
688 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800689 LOG(ERROR) << "Saving mount metadata failed: " << -err;
690 return kInvalidStorageId;
691 }
692 }
693
694 const auto bk =
695 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800696 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
697 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800698 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800699 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800700 return kInvalidStorageId;
701 }
702
703 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700704 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800705
Songchun Fan3c82a302019-11-29 14:23:45 -0800706 mountIt->second = std::move(ifs);
707 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700708
Songchun Fan3c82a302019-11-29 14:23:45 -0800709 LOG(INFO) << "created storage " << mountId;
710 return mountId;
711}
712
713StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
714 StorageId linkedStorage,
715 IncrementalService::CreateOptions options) {
716 if (!isValidMountTarget(mountPoint)) {
717 LOG(ERROR) << "Mount point is invalid or missing";
718 return kInvalidStorageId;
719 }
720
721 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700722 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800723 if (!ifs) {
724 LOG(ERROR) << "Ifs unavailable";
725 return kInvalidStorageId;
726 }
727
728 const auto mountIt = getStorageSlotLocked();
729 const auto storageId = mountIt->first;
730 const auto storageIt = ifs->makeStorage(storageId);
731 if (storageIt == ifs->storages.end()) {
732 LOG(ERROR) << "Can't create a new storage";
733 mMounts.erase(mountIt);
734 return kInvalidStorageId;
735 }
736
737 l.unlock();
738
739 const auto bk =
740 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800741 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
742 std::string(storageIt->second.name), path::normalize(mountPoint),
743 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800744 err < 0) {
745 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700746 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
747 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800748 return kInvalidStorageId;
749 }
750
751 mountIt->second = ifs;
752 return storageId;
753}
754
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700755bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700756 content::pm::DataLoaderParamsParcel dataLoaderParams,
757 DataLoaderStatusListener statusListener,
758 const StorageHealthCheckParams& healthCheckParams,
759 StorageHealthListener healthListener,
760 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800761 // Per Uid timeouts.
762 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700763 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800764 }
765
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700766 IfsMountPtr ifs;
767 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800768
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700769 // Re-initialize DataLoader.
770 {
771 ifs = getIfs(storageId);
772 if (!ifs) {
773 return false;
774 }
775
776 std::unique_lock l(ifs->lock);
777 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
778 }
779
780 if (dataLoaderStub) {
781 dataLoaderStub->cleanupResources();
782 dataLoaderStub = {};
783 }
784
785 {
786 std::unique_lock l(ifs->lock);
787 if (ifs->dataLoaderStub) {
788 LOG(INFO) << "Skipped data loader stub creation because it already exists";
789 return false;
790 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700791
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700792 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
793 healthCheckParams, std::move(healthListener));
794 CHECK(ifs->dataLoaderStub);
795 dataLoaderStub = ifs->dataLoaderStub;
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700796
797 // Disable long read timeouts for non-system dataloaders.
798 // To be re-enabled after installation is complete.
799 ifs->setReadTimeoutsRequested(dataLoaderStub->isSystemDataLoader() &&
800 getAlwaysEnableReadTimeoutsForSystemDataLoaders());
801 applyStorageParamsLocked(*ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700802 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800803
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700804 if (dataLoaderStub->isSystemDataLoader() &&
805 !getEnforceReadLogsMaxIntervalForSystemDataLoaders()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700806 // Readlogs from system dataloader (adb) can always be collected.
807 ifs->startLoadingTs = TimePoint::max();
808 } else {
809 // Assign time when installation wants the DL to start streaming.
810 const auto startLoadingTs = mClock->now();
811 ifs->startLoadingTs = startLoadingTs;
812 // Setup a callback to disable the readlogs after max interval.
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700813 addTimedJob(*mTimedQueue, storageId, getReadLogsMaxInterval(),
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700814 [this, storageId, startLoadingTs]() {
815 const auto ifs = getIfs(storageId);
816 if (!ifs) {
817 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
818 << storageId;
819 return;
820 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700821 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700822 if (ifs->startLoadingTs != startLoadingTs) {
823 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
824 "installation?): "
825 << storageId;
826 return;
827 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700828 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700829 });
830 }
831
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800832 return dataLoaderStub->requestStart();
833}
834
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700835void IncrementalService::onInstallationComplete(StorageId storage) {
836 IfsMountPtr ifs = getIfs(storage);
837 if (!ifs) {
838 return;
839 }
840
841 // Always enable long read timeouts after installation is complete.
842 std::unique_lock l(ifs->lock);
843 ifs->setReadTimeoutsRequested(true);
844 applyStorageParamsLocked(*ifs);
845}
846
Songchun Fan3c82a302019-11-29 14:23:45 -0800847IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
848 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700849 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800850}
851
852StorageId IncrementalService::findStorageId(std::string_view path) const {
853 std::lock_guard l(mLock);
854 auto it = findStorageLocked(path);
855 if (it == mBindsByPath.end()) {
856 return kInvalidStorageId;
857 }
858 return it->second->second.storage;
859}
860
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800861void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700862 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700863 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800864 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700865 return;
866 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700867
868 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800869 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700870 return;
871 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800872 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700873
874 const auto metadata = constants().readLogsDisabledMarkerName;
875 if (auto err = mIncFs->makeFile(ifs->control,
876 path::join(ifs->root, constants().mount,
877 constants().readLogsDisabledMarkerName),
878 0777, idFromMetadata(metadata), {})) {
879 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
880 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
881 return;
882 }
883
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700884 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700885}
886
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700887int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
888 const auto ifs = getIfs(storageId);
889 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700890 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700891 return -EINVAL;
892 }
893
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700894 std::string packageName;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700895
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700896 {
897 std::unique_lock l(ifs->lock);
898 if (!enableReadLogs) {
899 return disableReadLogsLocked(*ifs);
900 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700901
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700902 if (!ifs->readLogsAllowed()) {
903 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
904 return -EPERM;
905 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700906
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700907 if (!ifs->dataLoaderStub) {
908 // This should never happen - only DL can call enableReadLogs.
909 LOG(ERROR) << "enableReadLogs failed: invalid state";
910 return -EPERM;
911 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700912
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700913 // Check installation time.
914 const auto now = mClock->now();
915 const auto startLoadingTs = ifs->startLoadingTs;
916 if (startLoadingTs <= now && now - startLoadingTs > getReadLogsMaxInterval()) {
917 LOG(ERROR)
918 << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
919 << storageId;
920 return -EPERM;
921 }
922
923 packageName = ifs->dataLoaderStub->params().packageName;
924 ifs->setReadLogsRequested(true);
925 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700926
927 // Check loader usage stats permission and apop.
928 if (auto status =
929 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
930 !status.isOk()) {
931 LOG(ERROR) << " Permission: " << kLoaderUsageStats
932 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700933 return fromBinderStatus(status);
934 }
935
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700936 // Check multiuser permission.
937 if (auto status =
938 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
939 !status.isOk()) {
940 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
941 << " check failed: " << status.toString8();
942 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700943 }
944
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700945 {
946 std::unique_lock l(ifs->lock);
947 if (!ifs->readLogsRequested()) {
948 return 0;
949 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700950 if (auto status = applyStorageParamsLocked(*ifs); status != 0) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700951 return status;
952 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700953 }
954
955 registerAppOpsCallback(packageName);
956
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700957 return 0;
958}
959
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700960int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700961 ifs.setReadLogsRequested(false);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700962 return applyStorageParamsLocked(ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700963}
964
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700965int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700966 os::incremental::IncrementalFileSystemControlParcel control;
967 control.cmd.reset(dup(ifs.control.cmd()));
968 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700969 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700970 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700971 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700972 }
973
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700974 bool enableReadLogs = ifs.readLogsRequested();
975 bool enableReadTimeouts = ifs.readTimeoutsRequested();
976
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700977 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700978 auto status = mVold->setIncFsMountOptions(control, enableReadLogs, enableReadTimeouts);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800979 if (status.isOk()) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700980 // Store states.
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800981 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700982 ifs.setReadTimeoutsEnabled(enableReadTimeouts);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700983 } else {
984 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800985 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700986 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700987}
988
Songchun Fan3c82a302019-11-29 14:23:45 -0800989void IncrementalService::deleteStorage(StorageId storageId) {
990 const auto ifs = getIfs(storageId);
991 if (!ifs) {
992 return;
993 }
994 deleteStorage(*ifs);
995}
996
997void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
998 std::unique_lock l(ifs.lock);
999 deleteStorageLocked(ifs, std::move(l));
1000}
1001
1002void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
1003 std::unique_lock<std::mutex>&& ifsLock) {
1004 const auto storages = std::move(ifs.storages);
1005 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
1006 const auto bindPoints = ifs.bindPoints;
1007 ifsLock.unlock();
1008
1009 std::lock_guard l(mLock);
1010 for (auto&& [id, _] : storages) {
1011 if (id != ifs.mountId) {
1012 mMounts.erase(id);
1013 }
1014 }
1015 for (auto&& [path, _] : bindPoints) {
1016 mBindsByPath.erase(path);
1017 }
1018 mMounts.erase(ifs.mountId);
1019}
1020
1021StorageId IncrementalService::openStorage(std::string_view pathInMount) {
1022 if (!path::isAbsolute(pathInMount)) {
1023 return kInvalidStorageId;
1024 }
1025
1026 return findStorageId(path::normalize(pathInMount));
1027}
1028
Songchun Fan3c82a302019-11-29 14:23:45 -08001029IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
1030 std::lock_guard l(mLock);
1031 return getIfsLocked(storage);
1032}
1033
1034const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
1035 auto it = mMounts.find(storage);
1036 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001037 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -07001038 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -08001039 }
1040 return it->second;
1041}
1042
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001043int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
1044 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001045 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001046 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001047 return -EINVAL;
1048 }
1049
1050 const auto ifs = getIfs(storage);
1051 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001052 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001053 return -EINVAL;
1054 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001055
Songchun Fan3c82a302019-11-29 14:23:45 -08001056 std::unique_lock l(ifs->lock);
1057 const auto storageInfo = ifs->storages.find(storage);
1058 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001059 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -08001060 return -EINVAL;
1061 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001062 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001063 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001064 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001065 return -EINVAL;
1066 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001067 l.unlock();
1068 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001069 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
1070 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -08001071}
1072
1073int IncrementalService::unbind(StorageId storage, std::string_view target) {
1074 if (!path::isAbsolute(target)) {
1075 return -EINVAL;
1076 }
1077
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001078 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001079
1080 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
1081 // otherwise there's a chance to unmount something completely unrelated
1082 const auto norm = path::normalize(target);
1083 std::unique_lock l(mLock);
1084 const auto storageIt = mBindsByPath.find(norm);
1085 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
1086 return -EINVAL;
1087 }
1088 const auto bindIt = storageIt->second;
1089 const auto storageId = bindIt->second.storage;
1090 const auto ifs = getIfsLocked(storageId);
1091 if (!ifs) {
1092 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
1093 << " is missing";
1094 return -EFAULT;
1095 }
1096 mBindsByPath.erase(storageIt);
1097 l.unlock();
1098
1099 mVold->unmountIncFs(bindIt->first);
1100 std::unique_lock l2(ifs->lock);
1101 if (ifs->bindPoints.size() <= 1) {
1102 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -07001103 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001104 } else {
1105 const std::string savedFile = std::move(bindIt->second.savedFilename);
1106 ifs->bindPoints.erase(bindIt);
1107 l2.unlock();
1108 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001109 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001110 }
1111 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001112
Songchun Fan3c82a302019-11-29 14:23:45 -08001113 return 0;
1114}
1115
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001116std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001117 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001118 std::string_view path) const {
1119 if (!path::isAbsolute(path)) {
1120 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001121 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001122 auto normPath = path::normalize(path);
1123 if (path::startsWith(normPath, storageIt->second.name)) {
1124 return normPath;
1125 }
1126 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001127 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1128 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001129 return {};
1130 }
1131 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001132}
1133
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001134std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001135 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001136 std::unique_lock l(ifs.lock);
1137 const auto storageInfo = ifs.storages.find(storage);
1138 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001139 return {};
1140 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001141 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001142}
1143
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001144int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001145 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001146 const auto ifs = getIfs(storage);
1147 if (!ifs) {
1148 return -EINVAL;
1149 }
1150 if (data.size() > params.size) {
1151 LOG(ERROR) << "Bad data size - bigger than file size";
1152 return -EINVAL;
1153 }
1154 if (!data.empty() && data.size() != params.size) {
1155 // Writing a page is an irreversible operation, and it can't be updated with additional
1156 // data later. Check that the last written page is complete, or we may break the file.
1157 if (!isPageAligned(data.size())) {
1158 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001159 return -EINVAL;
1160 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001161 }
1162 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1163 if (normPath.empty()) {
1164 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1165 return -EINVAL;
1166 }
1167 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1168 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1169 return err;
1170 }
1171 if (params.size > 0) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001172 if (auto err = mIncFs->reserveSpace(ifs->control, id, params.size)) {
1173 if (err != -EOPNOTSUPP) {
1174 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1175 (void)mIncFs->unlink(ifs->control, normPath);
1176 return err;
1177 } else {
1178 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1179 "may run out of disk later";
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001180 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001181 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001182 if (!data.empty()) {
1183 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001184 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001185 return err;
1186 }
1187 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001188 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001189 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001190}
1191
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001192int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001193 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001194 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001195 if (normPath.empty()) {
1196 return -EINVAL;
1197 }
1198 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001199 }
1200 return -EINVAL;
1201}
1202
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001203int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001204 const auto ifs = getIfs(storageId);
1205 if (!ifs) {
1206 return -EINVAL;
1207 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001208 return makeDirs(*ifs, storageId, path, mode);
1209}
1210
1211int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1212 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001213 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1214 if (normPath.empty()) {
1215 return -EINVAL;
1216 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001217 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001218}
1219
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001220int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1221 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001222 std::unique_lock l(mLock);
1223 auto ifsSrc = getIfsLocked(sourceStorageId);
1224 if (!ifsSrc) {
1225 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001226 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001227 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1228 return -EINVAL;
1229 }
1230 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001231 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1232 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001233 if (normOldPath.empty() || normNewPath.empty()) {
1234 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1235 return -EINVAL;
1236 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001237 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1238 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1239 << " to " << newPath << "[" << normNewPath << "]";
1240 return err;
1241 }
1242 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001243}
1244
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001245int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001246 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001247 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001248 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001249 }
1250 return -EINVAL;
1251}
1252
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001253int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1254 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001255 std::string&& target, BindKind kind,
1256 std::unique_lock<std::mutex>& mainLock) {
1257 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001258 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001259 return -EINVAL;
1260 }
1261
1262 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001263 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001264 if (kind != BindKind::Temporary) {
1265 metadata::BindPoint bp;
1266 bp.set_storage_id(storage);
1267 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001268 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001269 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001270 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001271 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001272 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001273 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1274 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1275 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001276 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001277 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001278 return int(node);
1279 }
1280 }
1281
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001282 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1283 std::move(target), kind, mainLock);
1284 if (res) {
1285 mIncFs->unlink(ifs.control, metadataFullPath);
1286 }
1287 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001288}
1289
1290int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001291 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001292 std::string&& target, BindKind kind,
1293 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001294 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001295 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001296 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001297 if (!status.isOk()) {
1298 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1299 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1300 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1301 : status.serviceSpecificErrorCode() == 0
1302 ? -EFAULT
1303 : status.serviceSpecificErrorCode()
1304 : -EIO;
1305 }
1306 }
1307
1308 if (!mainLock.owns_lock()) {
1309 mainLock.lock();
1310 }
1311 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001312 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1313 std::move(target), kind);
1314 return 0;
1315}
1316
1317void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1318 std::string&& metadataName, std::string&& source,
1319 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001320 const auto [it, _] =
1321 ifs.bindPoints.insert_or_assign(target,
1322 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001323 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001324 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001325}
1326
1327RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1328 const auto ifs = getIfs(storage);
1329 if (!ifs) {
1330 return {};
1331 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001332 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001333 if (normPath.empty()) {
1334 return {};
1335 }
1336 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001337}
1338
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001339RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001340 const auto ifs = getIfs(storage);
1341 if (!ifs) {
1342 return {};
1343 }
1344 return mIncFs->getMetadata(ifs->control, node);
1345}
1346
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001347void IncrementalService::setUidReadTimeouts(StorageId storage,
1348 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001349 using microseconds = std::chrono::microseconds;
1350 using milliseconds = std::chrono::milliseconds;
1351
1352 auto maxPendingTimeUs = microseconds(0);
1353 for (const auto& timeouts : perUidReadTimeouts) {
1354 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1355 }
1356 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07001357 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001358 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1359 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001360 return;
1361 }
1362
1363 const auto ifs = getIfs(storage);
1364 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001365 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001366 return;
1367 }
1368
1369 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1370 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1371 return;
1372 }
1373
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001374 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1375 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1376 if (checkUidReadTimeouts(storageId, state, timeout)) {
1377 return true;
1378 }
1379 clearUidReadTimeouts(storageId);
1380 return false;
1381 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001382}
1383
1384void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1385 const auto ifs = getIfs(storage);
1386 if (!ifs) {
1387 return;
1388 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001389 mIncFs->setUidReadTimeouts(ifs->control, {});
1390}
1391
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001392bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1393 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001394 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001395 // Reached maximum timeout.
1396 return false;
1397 }
1398 if (state.error) {
1399 // Something is wrong, abort.
1400 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001401 }
1402
1403 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001404 if (state.fullyLoaded && !state.readLogsEnabled) {
1405 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001406 }
1407
1408 const auto timeLeft = timeLimit - Clock::now();
1409 if (timeLeft < Constants::progressUpdateInterval) {
1410 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001411 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001412 }
1413
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001414 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001415}
1416
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001417std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1418 std::unordered_set<std::string_view> mountedRootNames;
1419 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1420 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1421 for (auto [source, target] : binds) {
1422 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1423 LOG(INFO) << " " << path::join(root, source);
1424 }
1425
1426 // Ensure it's a kind of a mount that's managed by IncrementalService
1427 if (path::basename(root) != constants().mount ||
1428 path::basename(backingDir) != constants().backing) {
1429 return;
1430 }
1431 const auto expectedRoot = path::dirname(root);
1432 if (path::dirname(backingDir) != expectedRoot) {
1433 return;
1434 }
1435 if (path::dirname(expectedRoot) != mIncrementalDir) {
1436 return;
1437 }
1438 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1439 return;
1440 }
1441
1442 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1443
1444 // make sure we clean up the mount if it happens to be a bad one.
1445 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1446 auto cleanupFiles = makeCleanup([&]() {
1447 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1448 IncFsMount::cleanupFilesystem(expectedRoot);
1449 });
1450 auto cleanupMounts = makeCleanup([&]() {
1451 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1452 for (auto&& [_, target] : binds) {
1453 mVold->unmountIncFs(std::string(target));
1454 }
1455 mVold->unmountIncFs(std::string(root));
1456 });
1457
1458 auto control = mIncFs->openMount(root);
1459 if (!control) {
1460 LOG(INFO) << "failed to open mount " << root;
1461 return;
1462 }
1463
1464 auto mountRecord =
1465 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1466 path::join(root, constants().infoMdName));
1467 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1468 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1469 return;
1470 }
1471
1472 auto mountId = mountRecord.storage().id();
1473 mNextId = std::max(mNextId, mountId + 1);
1474
1475 DataLoaderParamsParcel dataLoaderParams;
1476 {
1477 const auto& loader = mountRecord.loader();
1478 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1479 dataLoaderParams.packageName = loader.package_name();
1480 dataLoaderParams.className = loader.class_name();
1481 dataLoaderParams.arguments = loader.arguments();
1482 }
1483
1484 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1485 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001486 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001487
Alex Buynytskyy04035452020-06-06 20:15:58 -07001488 // Check if marker file present.
1489 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001490 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001491 }
1492
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001493 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1494 auto d = openDir(root);
1495 while (auto e = ::readdir(d.get())) {
1496 if (e->d_type == DT_REG) {
1497 auto name = std::string_view(e->d_name);
1498 if (name.starts_with(constants().mountpointMdPrefix)) {
1499 permanentBindPoints
1500 .emplace_back(name,
1501 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1502 ifs->control,
1503 path::join(root,
1504 name)));
1505 if (permanentBindPoints.back().second.dest_path().empty() ||
1506 permanentBindPoints.back().second.source_subdir().empty()) {
1507 permanentBindPoints.pop_back();
1508 mIncFs->unlink(ifs->control, path::join(root, name));
1509 } else {
1510 LOG(INFO) << "Permanent bind record: '"
1511 << permanentBindPoints.back().second.source_subdir() << "'->'"
1512 << permanentBindPoints.back().second.dest_path() << "'";
1513 }
1514 }
1515 } else if (e->d_type == DT_DIR) {
1516 if (e->d_name == "."sv || e->d_name == ".."sv) {
1517 continue;
1518 }
1519 auto name = std::string_view(e->d_name);
1520 if (name.starts_with(constants().storagePrefix)) {
1521 int storageId;
1522 const auto res =
1523 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1524 name.data() + name.size(), storageId);
1525 if (res.ec != std::errc{} || *res.ptr != '_') {
1526 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1527 << "' for mount " << expectedRoot;
1528 continue;
1529 }
1530 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1531 if (!inserted) {
1532 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1533 << " for mount " << expectedRoot;
1534 continue;
1535 }
1536 ifs->storages.insert_or_assign(storageId,
1537 IncFsMount::Storage{path::join(root, name)});
1538 mNextId = std::max(mNextId, storageId + 1);
1539 }
1540 }
1541 }
1542
1543 if (ifs->storages.empty()) {
1544 LOG(WARNING) << "No valid storages in mount " << root;
1545 return;
1546 }
1547
1548 // now match the mounted directories with what we expect to have in the metadata
1549 {
1550 std::unique_lock l(mLock, std::defer_lock);
1551 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1552 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1553 [&, bindRecord = bindRecord](auto&& bind) {
1554 return bind.second == bindRecord.dest_path() &&
1555 path::join(root, bind.first) ==
1556 bindRecord.source_subdir();
1557 });
1558 if (mountedIt != binds.end()) {
1559 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1560 << " to mount " << mountedIt->first;
1561 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1562 std::move(*bindRecord.mutable_source_subdir()),
1563 std::move(*bindRecord.mutable_dest_path()),
1564 BindKind::Permanent);
1565 if (mountedIt != binds.end() - 1) {
1566 std::iter_swap(mountedIt, binds.end() - 1);
1567 }
1568 binds = binds.first(binds.size() - 1);
1569 } else {
1570 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1571 << ", mounting";
1572 // doesn't exist - try mounting back
1573 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1574 std::move(*bindRecord.mutable_source_subdir()),
1575 std::move(*bindRecord.mutable_dest_path()),
1576 BindKind::Permanent, l)) {
1577 mIncFs->unlink(ifs->control, metadataFile);
1578 }
1579 }
1580 }
1581 }
1582
1583 // if anything stays in |binds| those are probably temporary binds; system restarted since
1584 // they were mounted - so let's unmount them all.
1585 for (auto&& [source, target] : binds) {
1586 if (source.empty()) {
1587 continue;
1588 }
1589 mVold->unmountIncFs(std::string(target));
1590 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001591 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001592
1593 if (ifs->bindPoints.empty()) {
1594 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1595 deleteStorage(*ifs);
1596 return;
1597 }
1598
1599 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1600 CHECK(ifs->dataLoaderStub);
1601
1602 mountedRootNames.insert(path::basename(ifs->root));
1603
1604 // not locking here at all: we're still in the constructor, no other calls can happen
1605 mMounts[ifs->mountId] = std::move(ifs);
1606 });
1607
1608 return mountedRootNames;
1609}
1610
1611void IncrementalService::mountExistingImages(
1612 const std::unordered_set<std::string_view>& mountedRootNames) {
1613 auto dir = openDir(mIncrementalDir);
1614 if (!dir) {
1615 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1616 return;
1617 }
1618 while (auto entry = ::readdir(dir.get())) {
1619 if (entry->d_type != DT_DIR) {
1620 continue;
1621 }
1622 std::string_view name = entry->d_name;
1623 if (!name.starts_with(constants().mountKeyPrefix)) {
1624 continue;
1625 }
1626 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001627 continue;
1628 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001629 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001630 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001631 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001632 }
1633 }
1634}
1635
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001636bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001637 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001638 const auto backing = path::join(root, constants().backing);
Songchun Fanf949c372021-04-27 11:26:25 -07001639 std::string mountKey(path::basename(path::dirname(mountTarget)));
Songchun Fan3c82a302019-11-29 14:23:45 -08001640
Songchun Fan3c82a302019-11-29 14:23:45 -08001641 IncrementalFileSystemControlParcel controlParcel;
Songchun Fanf949c372021-04-27 11:26:25 -07001642 auto status = mVold->mountIncFs(backing, mountTarget, 0, mountKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001643 if (!status.isOk()) {
1644 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1645 return false;
1646 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001647
1648 int cmd = controlParcel.cmd.release().release();
1649 int pendingReads = controlParcel.pendingReads.release().release();
1650 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001651 int blocksWritten =
1652 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1653 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001654
1655 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1656
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001657 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1658 path::join(mountTarget, constants().infoMdName));
1659 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001660 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1661 return false;
1662 }
1663
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001664 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001665 mNextId = std::max(mNextId, ifs->mountId + 1);
1666
Alex Buynytskyy04035452020-06-06 20:15:58 -07001667 // Check if marker file present.
1668 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001669 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001670 }
1671
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001672 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001673 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001674 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001675 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001676 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001677 dataLoaderParams.packageName = loader.package_name();
1678 dataLoaderParams.className = loader.class_name();
1679 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001680 }
1681
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001682 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001683 CHECK(ifs->dataLoaderStub);
1684
Songchun Fan3c82a302019-11-29 14:23:45 -08001685 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001686 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001687 while (auto e = ::readdir(d.get())) {
1688 if (e->d_type == DT_REG) {
1689 auto name = std::string_view(e->d_name);
1690 if (name.starts_with(constants().mountpointMdPrefix)) {
1691 bindPoints.emplace_back(name,
1692 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1693 ifs->control,
1694 path::join(mountTarget,
1695 name)));
1696 if (bindPoints.back().second.dest_path().empty() ||
1697 bindPoints.back().second.source_subdir().empty()) {
1698 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001699 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001700 }
1701 }
1702 } else if (e->d_type == DT_DIR) {
1703 if (e->d_name == "."sv || e->d_name == ".."sv) {
1704 continue;
1705 }
1706 auto name = std::string_view(e->d_name);
1707 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001708 int storageId;
1709 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1710 name.data() + name.size(), storageId);
1711 if (res.ec != std::errc{} || *res.ptr != '_') {
1712 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1713 << root;
1714 continue;
1715 }
1716 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001717 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001718 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001719 << " for mount " << root;
1720 continue;
1721 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001722 ifs->storages.insert_or_assign(storageId,
1723 IncFsMount::Storage{
1724 path::join(root, constants().mount, name)});
1725 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001726 }
1727 }
1728 }
1729
1730 if (ifs->storages.empty()) {
1731 LOG(WARNING) << "No valid storages in mount " << root;
1732 return false;
1733 }
1734
1735 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001736 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001737 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001738 for (auto&& bp : bindPoints) {
1739 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1740 std::move(*bp.second.mutable_source_subdir()),
1741 std::move(*bp.second.mutable_dest_path()),
1742 BindKind::Permanent, l);
1743 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001744 }
1745
1746 if (bindCount == 0) {
1747 LOG(WARNING) << "No valid bind points for mount " << root;
1748 deleteStorage(*ifs);
1749 return false;
1750 }
1751
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001752 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001753 mMounts[ifs->mountId] = std::move(ifs);
1754 return true;
1755}
1756
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001757void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001758 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001759 while (mRunning.load(std::memory_order_relaxed)) {
1760 mLooper->pollAll(kTimeoutMsecs);
1761 }
1762}
1763
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001764void IncrementalService::trimReservedSpaceV1(const IncFsMount& ifs) {
1765 mIncFs->forEachFile(ifs.control, [this](auto&& control, auto&& fileId) {
1766 if (mIncFs->isFileFullyLoaded(control, fileId) == incfs::LoadingState::Full) {
1767 mIncFs->reserveSpace(control, fileId, -1);
1768 }
1769 return true;
1770 });
1771}
1772
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001773void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001774 DataLoaderStatusListener&& statusListener,
1775 const StorageHealthCheckParams& healthCheckParams,
1776 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001777 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001778 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001779 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1780 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1781 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001782 if (ifs.control.blocksWritten() >= 0) {
1783 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1784 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001785 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001786
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001787 ifs.dataLoaderStub =
1788 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001789 std::move(statusListener), healthCheckParams,
1790 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001791
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001792 // pre-v2 IncFS doesn't do automatic reserved space trimming - need to run it manually
1793 if (!(mIncFs->features() & incfs::Features::v2)) {
1794 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1795 if (!state.fullyLoaded) {
1796 return true;
1797 }
1798
1799 const auto ifs = getIfs(storageId);
1800 if (!ifs) {
1801 return false;
1802 }
1803 trimReservedSpaceV1(*ifs);
1804 return false;
1805 });
1806 }
1807
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001808 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1809 if (!state.fullyLoaded || state.readLogsEnabled) {
1810 return true;
1811 }
1812
1813 DataLoaderStubPtr dataLoaderStub;
1814 {
1815 const auto ifs = getIfs(storageId);
1816 if (!ifs) {
1817 return false;
1818 }
1819
1820 std::unique_lock l(ifs->lock);
1821 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1822 }
1823
1824 if (dataLoaderStub) {
1825 dataLoaderStub->cleanupResources();
1826 }
1827
1828 return false;
1829 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001830}
1831
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001832template <class Duration>
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001833static constexpr auto castToMs(Duration d) {
1834 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1835}
1836
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001837// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001838// Lib files should be placed next to the APK file in the following matter:
1839// Example:
1840// /path/to/base.apk
1841// /path/to/lib/arm/first.so
1842// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001843bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1844 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001845 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001846 auto start = Clock::now();
1847
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001848 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001849 if (!ifs) {
1850 LOG(ERROR) << "Invalid storage " << storage;
1851 return false;
1852 }
1853
Songchun Fanc8975312020-07-13 12:14:37 -07001854 const auto targetLibPathRelativeToStorage =
1855 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1856 libDirRelativePath);
1857
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001858 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001859 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1860 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001861 << " errno: " << res;
1862 return false;
1863 }
1864
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001865 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001866 ZipArchiveHandle zipFileHandle;
1867 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001868 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1869 return false;
1870 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001871
1872 // Need a shared pointer: will be passing it into all unpacking jobs.
1873 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001874 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001875 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001876 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001877 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1878 return false;
1879 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001880 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001881 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1882
1883 auto openZipTs = Clock::now();
1884
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001885 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1886 incfs::FileId sourceId;
1887 if (mapFiles) {
1888 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1889 if (!incfs::isValidFileId(sourceId)) {
1890 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1891 << "', mapping disabled";
1892 mapFiles = false;
1893 }
1894 }
1895
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001896 std::vector<Job> jobQueue;
1897 ZipEntry entry;
1898 std::string_view fileName;
1899 while (!Next(cookie, &entry, &fileName)) {
1900 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001901 continue;
1902 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001903
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001904 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001905 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001906
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001907 if (!extractNativeLibs) {
1908 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001909 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001910 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1911 return false;
1912 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001913 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001914 LOG(WARNING) << "Library " << fileName
1915 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1916 << entry.offset;
1917 return false;
1918 }
1919 continue;
1920 }
1921
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001922 auto startFileTs = Clock::now();
1923
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001924 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001925 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001926 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001927 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001928 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001929 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001930 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1931 << "; skipping extraction, spent "
1932 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1933 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001934 continue;
1935 }
1936
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001937 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1938 incfs::NewMappedFileParams mappedFileParams = {
1939 .sourceId = sourceId,
1940 .sourceOffset = entry.offset,
1941 .size = entry.uncompressed_length,
1942 };
1943
1944 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1945 mappedFileParams);
1946 res == 0) {
1947 if (perfLoggingEnabled()) {
1948 auto doneTs = Clock::now();
1949 LOG(INFO) << "incfs: Mapped " << libName << ": "
1950 << elapsedMcs(startFileTs, doneTs) << "mcs";
1951 }
1952 continue;
1953 } else {
1954 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1955 << "; falling back to full extraction";
1956 }
1957 }
1958
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001959 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001960 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001961 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001962 .signature = {},
1963 // Metadata of the new lib file is its relative path
1964 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1965 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001966 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001967 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001968 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001969 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001970 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001971 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001972 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001973
1974 auto makeFileTs = Clock::now();
1975
Songchun Fanafaf6e92020-03-18 14:12:20 -07001976 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001977 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001978 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001979 LOG(INFO) << "incfs: Extracted " << libName
1980 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001981 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001982 continue;
1983 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001984
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001985 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1986 libFileId, libPath = std::move(targetLibPath),
1987 makeFileTs]() mutable {
1988 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001989 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001990
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001991 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001992 auto prepareJobTs = Clock::now();
1993 LOG(INFO) << "incfs: Processed " << libName << ": "
1994 << elapsedMcs(startFileTs, prepareJobTs)
1995 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1996 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001997 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001998 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001999
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002000 auto processedTs = Clock::now();
2001
2002 if (!jobQueue.empty()) {
2003 {
2004 std::lock_guard lock(mJobMutex);
2005 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002006 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002007 if (existingJobs.empty()) {
2008 existingJobs = std::move(jobQueue);
2009 } else {
2010 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
2011 std::move_iterator(jobQueue.end()));
2012 }
2013 }
2014 }
2015 mJobCondition.notify_all();
2016 }
2017
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002018 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002019 auto end = Clock::now();
2020 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
2021 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
2022 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002023 << " make files: " << elapsedMcs(openZipTs, processedTs)
2024 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002025 }
2026
2027 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002028}
2029
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002030void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
2031 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002032 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002033 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002034 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002035 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002036 return;
2037 }
2038
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002039 auto startedTs = Clock::now();
2040
2041 // Write extracted data to new file
2042 // NOTE: don't zero-initialize memory, it may take a while for nothing
2043 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
2044 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002045 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002046 return;
2047 }
2048
2049 auto extractFileTs = Clock::now();
2050
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002051 if (setFileContent(ifs, libFileId, debugLibPath,
2052 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002053 return;
2054 }
2055
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002056 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002057 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002058 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
2059 << entry.compressed_length << " -> " << entry.uncompressed_length
2060 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002061 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
2062 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002063 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002064 }
2065}
2066
2067bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002068 struct WaitPrinter {
2069 const Clock::time_point startTs = Clock::now();
2070 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002071 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002072 const auto endTs = Clock::now();
2073 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
2074 << elapsedMcs(startTs, endTs) << "mcs";
2075 }
2076 }
2077 } waitPrinter;
2078
2079 MountId mount;
2080 {
2081 auto ifs = getIfs(storage);
2082 if (!ifs) {
2083 return true;
2084 }
2085 mount = ifs->mountId;
2086 }
2087
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002088 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002089 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002090 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002091 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002092 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002093 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002094}
2095
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002096int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
2097 std::string_view debugFilePath,
2098 std::span<const uint8_t> data) const {
2099 auto startTs = Clock::now();
2100
2101 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2102 if (!writeFd.ok()) {
2103 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2104 << " errno: " << writeFd.get();
2105 return writeFd.get();
2106 }
2107
2108 const auto dataLength = data.size();
2109
2110 auto openFileTs = Clock::now();
2111 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2112 std::vector<IncFsDataBlock> instructions(numBlocks);
2113 for (int i = 0; i < numBlocks; i++) {
2114 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2115 instructions[i] = IncFsDataBlock{
2116 .fileFd = writeFd.get(),
2117 .pageIndex = static_cast<IncFsBlockIndex>(i),
2118 .compression = INCFS_COMPRESSION_KIND_NONE,
2119 .kind = INCFS_BLOCK_KIND_DATA,
2120 .dataSize = static_cast<uint32_t>(blockSize),
2121 .data = reinterpret_cast<const char*>(data.data()),
2122 };
2123 data = data.subspan(blockSize);
2124 }
2125 auto prepareInstsTs = Clock::now();
2126
2127 size_t res = mIncFs->writeBlocks(instructions);
2128 if (res != instructions.size()) {
2129 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2130 return res;
2131 }
2132
2133 if (perfLoggingEnabled()) {
2134 auto endTs = Clock::now();
2135 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2136 << " bytes): " << elapsedMcs(startTs, endTs)
2137 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2138 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2139 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2140 }
2141
2142 return 0;
2143}
2144
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002145incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2146 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002147 std::unique_lock l(mLock);
2148 const auto ifs = getIfsLocked(storage);
2149 if (!ifs) {
2150 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002151 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002152 }
2153 const auto storageInfo = ifs->storages.find(storage);
2154 if (storageInfo == ifs->storages.end()) {
2155 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002156 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002157 }
2158 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002159 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002160}
2161
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002162incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2163 const auto ifs = getIfs(storage);
2164 if (!ifs) {
2165 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2166 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002167 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002168 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002169}
2170
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002171IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002172 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002173 std::unique_lock l(mLock);
2174 const auto ifs = getIfsLocked(storage);
2175 if (!ifs) {
2176 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002177 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002178 }
2179 const auto storageInfo = ifs->storages.find(storage);
2180 if (storageInfo == ifs->storages.end()) {
2181 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002182 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002183 }
2184 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002185 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002186}
2187
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002188IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002189 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002190 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2191 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002192 const auto [filledBlocksCount, totalBlocksCount] =
2193 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002194 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2195 filledBlocksCount == -ENOENT) {
2196 // a kind of a file that's not really being loaded, e.g. a mapped range
2197 // an older IncFS used to return ENOENT in this case, so handle it the same way
2198 return true;
2199 }
Songchun Fan374f7652020-08-20 08:40:29 -07002200 if (filledBlocksCount < 0) {
2201 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002202 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002203 error = filledBlocksCount;
2204 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002205 }
2206 totalBlocks += totalBlocksCount;
2207 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002208 return true;
2209 });
Songchun Fan374f7652020-08-20 08:40:29 -07002210
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002211 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002212}
2213
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002214bool IncrementalService::updateLoadingProgress(StorageId storage,
2215 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002216 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002217 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002218 // Failed to get progress from incfs, abort.
2219 return false;
2220 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002221 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2222 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002223 // Stop updating progress once it is fully loaded
2224 return true;
2225 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002226 addTimedJob(*mProgressUpdateJobQueue, storage,
2227 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002228 [storage, progressListener = std::move(progressListener), this]() mutable {
2229 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002230 });
2231 return true;
2232}
2233
2234bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002235 StorageId storage, StorageLoadingProgressListener progressListener) {
2236 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002237}
2238
2239bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2240 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2241}
2242
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002243bool IncrementalService::perfLoggingEnabled() {
2244 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2245 return enabled;
2246}
2247
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002248void IncrementalService::runJobProcessing() {
2249 for (;;) {
2250 std::unique_lock lock(mJobMutex);
2251 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2252 if (!mRunning) {
2253 return;
2254 }
2255
2256 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002257 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002258 auto queue = std::move(it->second);
2259 mJobQueue.erase(it);
2260 lock.unlock();
2261
2262 for (auto&& job : queue) {
2263 job();
2264 }
2265
2266 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002267 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002268 lock.unlock();
2269 mJobCondition.notify_all();
2270 }
2271}
2272
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002273void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002274 sp<IAppOpsCallback> listener;
2275 {
2276 std::unique_lock lock{mCallbacksLock};
2277 auto& cb = mCallbackRegistered[packageName];
2278 if (cb) {
2279 return;
2280 }
2281 cb = new AppOpsListener(*this, packageName);
2282 listener = cb;
2283 }
2284
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002285 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2286 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002287}
2288
2289bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2290 sp<IAppOpsCallback> listener;
2291 {
2292 std::unique_lock lock{mCallbacksLock};
2293 auto found = mCallbackRegistered.find(packageName);
2294 if (found == mCallbackRegistered.end()) {
2295 return false;
2296 }
2297 listener = found->second;
2298 mCallbackRegistered.erase(found);
2299 }
2300
2301 mAppOpsManager->stopWatchingMode(listener);
2302 return true;
2303}
2304
2305void IncrementalService::onAppOpChanged(const std::string& packageName) {
2306 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002307 return;
2308 }
2309
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002310 std::vector<IfsMountPtr> affected;
2311 {
2312 std::lock_guard l(mLock);
2313 affected.reserve(mMounts.size());
2314 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002315 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002316 if (ifs->mountId == id && ifs->dataLoaderStub &&
2317 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002318 affected.push_back(ifs);
2319 }
2320 }
2321 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002322 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002323 std::unique_lock ll(ifs->lock);
2324 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002325 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002326}
2327
Songchun Fana7098592020-09-03 11:45:53 -07002328bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2329 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002330 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002331 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002332 }
Songchun Fana7098592020-09-03 11:45:53 -07002333 timedQueue.addJob(id, after, std::move(what));
2334 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002335}
2336
Songchun Fana7098592020-09-03 11:45:53 -07002337bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002338 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002339 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002340 }
Songchun Fana7098592020-09-03 11:45:53 -07002341 timedQueue.removeJobs(id);
2342 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002343}
2344
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002345void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2346 bool wasEmpty;
2347 {
2348 std::lock_guard l(mIfsStateCallbacksLock);
2349 wasEmpty = mIfsStateCallbacks.empty();
2350 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2351 }
2352 if (wasEmpty) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002353 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002354 [this]() { processIfsStateCallbacks(); });
2355 }
2356}
2357
2358void IncrementalService::processIfsStateCallbacks() {
2359 StorageId storageId = kInvalidStorageId;
2360 std::vector<IfsStateCallback> local;
2361 while (true) {
2362 {
2363 std::lock_guard l(mIfsStateCallbacksLock);
2364 if (mIfsStateCallbacks.empty()) {
2365 return;
2366 }
2367 IfsStateCallbacks::iterator it;
2368 if (storageId == kInvalidStorageId) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002369 // First entry, initialize the |it|.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002370 it = mIfsStateCallbacks.begin();
2371 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002372 // Subsequent entries, update the |storageId|, and shift to the new one (not that
2373 // it guarantees much about updated items, but at least the loop will finish).
2374 it = mIfsStateCallbacks.lower_bound(storageId);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002375 if (it == mIfsStateCallbacks.end()) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002376 // Nothing else left, too bad.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002377 break;
2378 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002379 if (it->first != storageId) {
2380 local.clear(); // Was removed during processing, forget the old callbacks.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002381 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002382 // Put the 'surviving' callbacks back into the map and advance the position.
2383 auto& callbacks = it->second;
2384 if (callbacks.empty()) {
2385 std::swap(callbacks, local);
2386 } else {
2387 callbacks.insert(callbacks.end(), std::move_iterator(local.begin()),
2388 std::move_iterator(local.end()));
2389 local.clear();
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002390 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002391 if (callbacks.empty()) {
2392 it = mIfsStateCallbacks.erase(it);
2393 if (mIfsStateCallbacks.empty()) {
2394 return;
2395 }
2396 } else {
2397 ++it;
2398 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002399 }
2400 }
2401
2402 if (it == mIfsStateCallbacks.end()) {
2403 break;
2404 }
2405
2406 storageId = it->first;
2407 auto& callbacks = it->second;
2408 if (callbacks.empty()) {
2409 // Invalid case, one extra lookup should be ok.
2410 continue;
2411 }
2412 std::swap(callbacks, local);
2413 }
2414
2415 processIfsStateCallbacks(storageId, local);
2416 }
2417
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002418 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002419 [this]() { processIfsStateCallbacks(); });
2420}
2421
2422void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2423 std::vector<IfsStateCallback>& callbacks) {
2424 const auto state = isMountFullyLoaded(storageId);
2425 IfsState storageState = {};
2426 storageState.error = int(state) < 0;
2427 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2428 if (storageState.fullyLoaded) {
2429 const auto ifs = getIfs(storageId);
2430 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2431 }
2432
2433 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2434 if ((*cur)(storageId, storageState)) {
2435 ++cur;
2436 } else {
2437 cur = callbacks.erase(cur);
2438 }
2439 }
2440}
2441
2442void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2443 std::lock_guard l(mIfsStateCallbacksLock);
2444 mIfsStateCallbacks.erase(storageId);
2445}
2446
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002447void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002448 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002449 if (!ifs) {
Songchun Fan9471be52021-04-21 17:49:27 -07002450 LOG(ERROR) << "getMetrics failed, invalid storageId: " << storageId;
2451 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002452 }
Songchun Fan9471be52021-04-21 17:49:27 -07002453 const auto kMetricsReadLogsEnabled =
2454 os::incremental::BnIncrementalService::METRICS_READ_LOGS_ENABLED();
2455 result->putBoolean(String16(kMetricsReadLogsEnabled.data()), ifs->readLogsEnabled() != 0);
2456
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002457 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002458 if (!ifs->dataLoaderStub) {
Songchun Fan9471be52021-04-21 17:49:27 -07002459 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002460 }
Songchun Fan9471be52021-04-21 17:49:27 -07002461 ifs->dataLoaderStub->getMetrics(result);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002462}
2463
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002464IncrementalService::DataLoaderStub::DataLoaderStub(
2465 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2466 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2467 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2468 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002469 : mService(service),
2470 mId(id),
2471 mParams(std::move(params)),
2472 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002473 mStatusListener(std::move(statusListener)),
2474 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002475 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002476 mHealthCheckParams(healthCheckParams) {
2477 if (mHealthListener && !isHealthParamsValid()) {
2478 mHealthListener = {};
2479 }
2480 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002481 // Disable advanced health check statuses.
2482 mHealthCheckParams.blockedTimeoutMs = -1;
2483 }
2484 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002485}
2486
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002487IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002488 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002489 cleanupResources();
2490 }
2491}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002492
2493void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002494 auto now = Clock::now();
2495 {
2496 std::unique_lock lock(mMutex);
2497 mHealthPath.clear();
2498 unregisterFromPendingReads();
2499 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002500 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002501 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002502 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002503
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002504 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002505
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002506 {
2507 std::unique_lock lock(mMutex);
2508 mParams = {};
2509 mControl = {};
2510 mHealthControl = {};
2511 mHealthListener = {};
2512 mStatusCondition.wait_until(lock, now + 60s, [this] {
2513 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2514 });
2515 mStatusListener = {};
2516 mId = kInvalidStorageId;
2517 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002518}
2519
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002520sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2521 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002522 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002523 if (!status.isOk()) {
2524 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2525 return {};
2526 }
2527 if (!dataloader) {
2528 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2529 return {};
2530 }
2531 return dataloader;
2532}
2533
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002534bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2535 return (params().packageName == Constants::systemPackage);
2536}
2537
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002538bool IncrementalService::DataLoaderStub::requestCreate() {
2539 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2540}
2541
2542bool IncrementalService::DataLoaderStub::requestStart() {
2543 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2544}
2545
2546bool IncrementalService::DataLoaderStub::requestDestroy() {
2547 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2548}
2549
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002550bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002551 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002552 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002553 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002554 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002555 return fsmStep();
2556}
2557
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002558void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002559 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002560 mTargetStatus = status;
2561 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002562 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002563 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002564}
2565
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002566std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002567 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002568
2569 const auto now = mService.mClock->now();
2570 const bool healthy = (mPreviousBindDelay == 0ms);
2571
2572 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2573 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2574 LOG(INFO) << "Binding still in progress. "
2575 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002576 : "Already unhealthy, don't do anything.")
2577 << " for storage " << mId;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002578 // Binding still in progress.
2579 if (!healthy) {
2580 // Already unhealthy, don't do anything.
2581 return {};
2582 }
2583 // The DL is healthy/freshly bound, ok to retry for a few times.
2584 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2585 // Still within grace period.
2586 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2587 // Retry interval passed, retrying.
2588 mCurrentStatusTs = now;
2589 mPreviousBindDelay = 0ms;
2590 return 0ms;
2591 }
2592 return {};
2593 }
2594 // fallthrough, mark as unhealthy, and retry with delay
2595 }
2596
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002597 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002598 mPreviousBindTs = now;
2599
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002600 const auto nonCrashingInterval =
2601 std::max(castToMs(now - previousBindTs - mPreviousBindDelay), 100ms);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002602 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2603 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2604 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002605 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002606 }
2607
2608 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2609 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2610
2611 const auto bindDelayMs =
2612 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2613 maxBindDelayMs)
2614 .count();
2615 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2616 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2617 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002618 return mPreviousBindDelay;
2619}
2620
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002621bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002622 const auto maybeBindDelay = needToBind();
2623 if (!maybeBindDelay) {
2624 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2625 return true;
2626 }
2627 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002628 if (bindDelay > 1s) {
2629 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002630 << bindDelay.count() / 1000 << "s"
2631 << " for storage " << mId;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002632 }
2633
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002634 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002635 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2636 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002637 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002638 const bool healthy = (bindDelay == 0ms);
2639 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2640 << (healthy ? ", retrying." : "");
2641
2642 // Internal error, retry for healthy/new DLs.
2643 // Let needToBind migrate it to unhealthy after too many retries.
2644 if (healthy) {
2645 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2646 [this]() { fsmStep(); })) {
2647 // Mark as binding so that we know it's not the DL's fault.
2648 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2649 return true;
2650 }
2651 }
2652
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002653 return false;
2654 }
2655 return true;
2656}
2657
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002658bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002659 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002660 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002661 return false;
2662 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002663 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002664 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002665 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002666 return false;
2667 }
2668 return true;
2669}
2670
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002671bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002672 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002673 if (!dataloader) {
2674 return false;
2675 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002676 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002677 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002678 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002679 return false;
2680 }
2681 return true;
2682}
2683
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002684bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002685 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002686}
2687
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002688bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002689 if (!isValid()) {
2690 return false;
2691 }
2692
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002693 int currentStatus;
2694 int targetStatus;
2695 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002696 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002697 currentStatus = mCurrentStatus;
2698 targetStatus = mTargetStatus;
2699 }
2700
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002701 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002702
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002703 if (currentStatus == targetStatus) {
2704 return true;
2705 }
2706
2707 switch (targetStatus) {
2708 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002709 switch (currentStatus) {
2710 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2711 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2712 return true;
2713 default:
2714 return destroy();
2715 }
2716 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002717 }
2718 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2719 switch (currentStatus) {
2720 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2721 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2722 return start();
2723 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002724 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002725 }
2726 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2727 switch (currentStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002728 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002729 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2730 // Before binding need to make sure we are unbound.
2731 // Otherwise we'll get stuck binding.
2732 return destroy();
2733 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002734 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002735 return bind();
2736 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002737 return create();
2738 }
2739 break;
2740 default:
2741 LOG(ERROR) << "Invalid target status: " << targetStatus
2742 << ", current status: " << currentStatus;
2743 break;
2744 }
2745 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002746}
2747
2748binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002749 if (!isValid()) {
2750 return binder::Status::
2751 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2752 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002753 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002754 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2755 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002756 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2757 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002758 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2759 newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002760 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2761 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2762 [this, newStatus]() { setCurrentStatus(newStatus); });
2763 return binder::Status::ok();
2764 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002765
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002766 setCurrentStatus(newStatus);
2767 return binder::Status::ok();
2768}
2769
2770void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002771 int oldStatus, oldTargetStatus, newTargetStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002772 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002773 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002774 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002775 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002776 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002777 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002778
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002779 oldStatus = mCurrentStatus;
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002780 oldTargetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002781 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002782
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002783 // Change the status.
2784 mCurrentStatus = newStatus;
2785 mCurrentStatusTs = mService.mClock->now();
2786
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002787 switch (mCurrentStatus) {
2788 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2789 // Unavailable, retry.
2790 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2791 break;
2792 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2793 // Unrecoverable, just unbind.
2794 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2795 break;
2796 default:
2797 break;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002798 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002799
2800 newTargetStatus = mTargetStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002801 }
2802
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002803 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002804 << newStatus << " (target " << oldTargetStatus << " -> " << newTargetStatus << ")";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002805
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002806 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002807 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002808 }
2809
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002810 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002811
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002812 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002813}
2814
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002815bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2816 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2817 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002818}
2819
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002820void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002821 int healthStatus) {
2822 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2823 if (healthListener) {
2824 healthListener->onHealthStatus(id(), healthStatus);
2825 }
Songchun Fan9471be52021-04-21 17:49:27 -07002826 mHealthStatus = healthStatus;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002827}
2828
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002829void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2830 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002831
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002832 int healthStatusToReport = -1;
2833 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002834
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002835 {
2836 std::unique_lock lock(mMutex);
2837 unregisterFromPendingReads();
2838
2839 healthListener = mHealthListener;
2840
2841 // Healthcheck depends on timestamp of the oldest pending read.
2842 // 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 -07002843 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2844 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002845 const auto now = Clock::now();
2846 const auto kernelTsUs = getOldestPendingReadTs();
2847 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002848 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2849 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002850 mHealthBase = {now, kernelTsUs};
2851 }
2852
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002853 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2854 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002855 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2856 registerForPendingReads();
2857 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2858 lock.unlock();
2859 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002860 return;
2861 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002862
2863 resetHealthControl();
2864
2865 // Always make sure the data loader is started.
2866 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2867
2868 // Skip any further processing if health check params are invalid.
2869 if (!isHealthParamsValid()) {
2870 LOG(DEBUG) << id()
2871 << ": Skip any further processing if health check params are invalid.";
2872 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2873 lock.unlock();
2874 onHealthStatus(healthListener, healthStatusToReport);
2875 // Triggering data loader start. This is a one-time action.
2876 fsmStep();
2877 return;
2878 }
2879
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002880 // Don't schedule timer job less than 500ms in advance.
2881 static constexpr auto kTolerance = 500ms;
2882
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002883 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2884 const auto unhealthyTimeout =
2885 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2886 const auto unhealthyMonitoring =
2887 std::max(1000ms,
2888 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2889
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002890 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002891
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002892 Milliseconds checkBackAfter;
2893 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002894 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002895 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002896 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002897 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002898 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002899 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002900 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2901 } else {
2902 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002903 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002904 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2905 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002906 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002907 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002908 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2909 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002910 }
2911
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002912 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002913 if (healthStatusToReport != -1) {
2914 onHealthStatus(healthListener, healthStatusToReport);
2915 }
2916
2917 fsmStep();
2918}
2919
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002920Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2921 BootClockTsUs kernelTsUs) {
2922 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2923 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2924 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2925}
2926
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002927const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2928 if (mHealthPath.empty()) {
2929 resetHealthControl();
2930 return mHealthControl;
2931 }
2932 if (mHealthControl.pendingReads() < 0) {
2933 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2934 }
2935 if (mHealthControl.pendingReads() < 0) {
2936 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2937 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2938 << mHealthControl.logs() << ")";
2939 }
2940 return mHealthControl;
2941}
2942
2943void IncrementalService::DataLoaderStub::resetHealthControl() {
2944 mHealthControl = {};
2945}
2946
2947BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2948 auto result = kMaxBootClockTsUs;
2949
2950 const auto& control = initializeHealthControl();
2951 if (control.pendingReads() < 0) {
2952 return result;
2953 }
2954
Songchun Fan6944f1e2020-11-06 15:24:24 -08002955 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002956 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002957 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002958 // Clear previous pending reads
2959 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002960 return result;
2961 }
2962
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07002963 LOG(DEBUG) << id() << ": pendingReads: fd(" << control.pendingReads() << "), count("
2964 << mLastPendingReads.size() << "), block: " << mLastPendingReads.front().block
2965 << ", time: " << mLastPendingReads.front().bootClockTsUs
2966 << ", uid: " << mLastPendingReads.front().uid;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002967
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002968 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002969}
2970
2971void IncrementalService::DataLoaderStub::registerForPendingReads() {
2972 const auto pendingReadsFd = mHealthControl.pendingReads();
2973 if (pendingReadsFd < 0) {
2974 return;
2975 }
2976
2977 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2978
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002979 mService.mLooper->addFd(
2980 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2981 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002982 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002983 self->updateHealthStatus(/*baseline=*/true);
2984 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002985 },
2986 this);
2987 mService.mLooper->wake();
2988}
2989
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002990BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2991 auto result = kMaxBootClockTsUs;
2992 for (auto&& pendingRead : mLastPendingReads) {
2993 result = std::min(result, pendingRead.bootClockTsUs);
2994 }
2995 return result;
2996}
2997
Songchun Fan9471be52021-04-21 17:49:27 -07002998void IncrementalService::DataLoaderStub::getMetrics(android::os::PersistableBundle* result) {
2999 const auto duration = elapsedMsSinceOldestPendingRead();
3000 if (duration >= 0) {
3001 const auto kMetricsMillisSinceOldestPendingRead =
3002 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
3003 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
3004 }
3005 const auto kMetricsStorageHealthStatusCode =
3006 os::incremental::BnIncrementalService::METRICS_STORAGE_HEALTH_STATUS_CODE();
3007 result->putInt(String16(kMetricsStorageHealthStatusCode.data()), mHealthStatus);
3008 const auto kMetricsDataLoaderStatusCode =
3009 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_STATUS_CODE();
3010 result->putInt(String16(kMetricsDataLoaderStatusCode.data()), mCurrentStatus);
3011 const auto kMetricsMillisSinceLastDataLoaderBind =
3012 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_DATA_LOADER_BIND();
3013 result->putLong(String16(kMetricsMillisSinceLastDataLoaderBind.data()),
3014 (long)(elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000));
3015 const auto kMetricsDataLoaderBindDelayMillis =
3016 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_BIND_DELAY_MILLIS();
3017 result->putLong(String16(kMetricsDataLoaderBindDelayMillis.data()),
3018 (long)(mPreviousBindDelay.count()));
3019}
3020
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003021long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
3022 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
3023 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
3024 return 0;
3025 }
3026 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
3027}
3028
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07003029void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003030 const auto pendingReadsFd = mHealthControl.pendingReads();
3031 if (pendingReadsFd < 0) {
3032 return;
3033 }
3034
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003035 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
3036
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003037 mService.mLooper->removeFd(pendingReadsFd);
3038 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003039}
3040
Songchun Fan2570ec02020-10-08 17:22:33 -07003041void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003042 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07003043 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003044 mHealthCheckParams = healthCheckParams;
3045 mHealthListener = std::move(healthListener);
3046 if (!mHealthListener) {
3047 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07003048 }
3049}
3050
Songchun Fan6944f1e2020-11-06 15:24:24 -08003051static std::string toHexString(const RawMetadata& metadata) {
3052 int n = metadata.size();
3053 std::string res(n * 2, '\0');
3054 // Same as incfs::toString(fileId)
3055 static constexpr char kHexChar[] = "0123456789abcdef";
3056 for (int i = 0; i < n; ++i) {
3057 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
3058 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
3059 }
3060 return res;
3061}
3062
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003063void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003064 dprintf(fd, " dataLoader: {\n");
3065 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08003066 dprintf(fd, " currentStatusTs: %lldmcs\n",
3067 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003068 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
3069 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003070 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003071 dprintf(fd, " health: {\n");
3072 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3073 dprintf(fd, " base: %lldmcs (%lld)\n",
3074 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3075 (long long)mHealthBase.kernelTsUs);
3076 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3077 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3078 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3079 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003080 dprintf(fd, " lastPendingReads: \n");
3081 const auto control = mService.mIncFs->openMount(mHealthPath);
3082 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003083 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003084 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3085 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3086 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3087 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3088 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003089 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
Songchun Fan9471be52021-04-21 17:49:27 -07003090 (long long)(elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000000),
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003091 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003092 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003093 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003094 dprintf(fd, " dataLoaderParams: {\n");
3095 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3096 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3097 dprintf(fd, " className: %s\n", params.className.c_str());
3098 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3099 dprintf(fd, " }\n");
3100 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003101}
3102
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003103void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3104 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003105}
3106
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003107binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3108 bool enableReadLogs, int32_t* _aidl_return) {
3109 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3110 return binder::Status::ok();
3111}
3112
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003113FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3114 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3115}
3116
Songchun Fan3c82a302019-11-29 14:23:45 -08003117} // namespace android::incremental