blob: de8c8bc945682232bcc10f4aecdc976002fe5656 [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
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800398void IncrementalService::onDump(int fd) {
399 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
400 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
401
402 std::unique_lock l(mLock);
403
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700404 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800405 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700406 std::unique_lock ll(ifs->lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700407 const IncFsMount& mnt = *ifs;
408 dprintf(fd, " [%d]: {\n", id);
409 if (id != mnt.mountId) {
410 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
411 } else {
412 dprintf(fd, " mountId: %d\n", mnt.mountId);
413 dprintf(fd, " root: %s\n", mnt.root.c_str());
Songchun Fanf949c372021-04-27 11:26:25 -0700414 const auto metricsInstanceName = path::basename(ifs->root);
415 dprintf(fd, " metrics instance name: %s\n", path::c_str(metricsInstanceName).get());
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700416 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700417 dprintf(fd, " flags: %d\n", int(mnt.flags));
418 if (mnt.startLoadingTs.time_since_epoch() == Clock::duration::zero()) {
419 dprintf(fd, " not loading\n");
420 } else {
421 dprintf(fd, " startLoading: %llds\n",
422 (long long)(elapsedMcs(mnt.startLoadingTs, Clock::now()) / 1000000));
423 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700424 if (mnt.dataLoaderStub) {
425 mnt.dataLoaderStub->onDump(fd);
426 } else {
427 dprintf(fd, " dataLoader: null\n");
428 }
429 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
430 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700431 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700432 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800433 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700434 }
435 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800436
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700437 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
438 for (auto&& [target, bind] : mnt.bindPoints) {
439 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
440 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
441 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
442 dprintf(fd, " kind: %s\n", toString(bind.kind));
443 }
444 dprintf(fd, " }\n");
Songchun Fanf949c372021-04-27 11:26:25 -0700445
446 dprintf(fd, " incfsMetrics: {\n");
447 const auto incfsMetrics = mIncFs->getMetrics(metricsInstanceName);
448 if (incfsMetrics) {
449 dprintf(fd, " readsDelayedMin: %d\n", incfsMetrics.value().readsDelayedMin);
450 dprintf(fd, " readsDelayedMinUs: %lld\n",
451 (long long)incfsMetrics.value().readsDelayedMinUs);
452 dprintf(fd, " readsDelayedPending: %d\n",
453 incfsMetrics.value().readsDelayedPending);
454 dprintf(fd, " readsDelayedPendingUs: %lld\n",
455 (long long)incfsMetrics.value().readsDelayedPendingUs);
456 dprintf(fd, " readsFailedHashVerification: %d\n",
457 incfsMetrics.value().readsFailedHashVerification);
458 dprintf(fd, " readsFailedOther: %d\n", incfsMetrics.value().readsFailedOther);
459 dprintf(fd, " readsFailedTimedOut: %d\n",
460 incfsMetrics.value().readsFailedTimedOut);
461 } else {
462 dprintf(fd, " Metrics not available. Errno: %d\n", errno);
463 }
464 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800465 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700466 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800467 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700468 dprintf(fd, "}\n");
469 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800470 for (auto&& [target, mountPairIt] : mBindsByPath) {
471 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700472 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
473 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
474 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
475 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800476 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700477 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800478}
479
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800480bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700481 if (!ifs.dataLoaderStub) {
482 return false;
483 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700484 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800485 return true;
486 }
487
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700488 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800489}
490
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700491void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800492 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700493 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800494 }
495
496 std::vector<IfsMountPtr> mounts;
497 {
498 std::lock_guard l(mLock);
499 mounts.reserve(mMounts.size());
500 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700501 std::unique_lock ll(ifs->lock);
502
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800503 if (ifs->mountId != id) {
504 continue;
505 }
506
507 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800508 mounts.push_back(ifs);
509 }
510 }
511 }
512
Alex Buynytskyy69941662020-04-11 21:40:37 -0700513 if (mounts.empty()) {
514 return;
515 }
516
Songchun Fan3c82a302019-11-29 14:23:45 -0800517 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700518 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800519 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700520 std::unique_lock l(ifs->lock);
521 if (ifs->dataLoaderStub) {
522 ifs->dataLoaderStub->requestStart();
523 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800524 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800525 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800526}
527
528auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
529 for (;;) {
530 if (mNextId == kMaxStorageId) {
531 mNextId = 0;
532 }
533 auto id = ++mNextId;
534 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
535 if (inserted) {
536 return it;
537 }
538 }
539}
540
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700541StorageId IncrementalService::createStorage(std::string_view mountPoint,
542 content::pm::DataLoaderParamsParcel dataLoaderParams,
543 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800544 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
545 if (!path::isAbsolute(mountPoint)) {
546 LOG(ERROR) << "path is not absolute: " << mountPoint;
547 return kInvalidStorageId;
548 }
549
550 auto mountNorm = path::normalize(mountPoint);
551 {
552 const auto id = findStorageId(mountNorm);
553 if (id != kInvalidStorageId) {
554 if (options & CreateOptions::OpenExisting) {
555 LOG(INFO) << "Opened existing storage " << id;
556 return id;
557 }
558 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
559 return kInvalidStorageId;
560 }
561 }
562
563 if (!(options & CreateOptions::CreateNew)) {
564 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
565 return kInvalidStorageId;
566 }
567
568 if (!path::isEmptyDir(mountNorm)) {
569 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
570 return kInvalidStorageId;
571 }
572 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
573 if (mountRoot.empty()) {
574 LOG(ERROR) << "Bad mount point";
575 return kInvalidStorageId;
576 }
577 // Make sure the code removes all crap it may create while still failing.
578 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
579 auto firstCleanupOnFailure =
580 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
581
582 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800583 const auto backing = path::join(mountRoot, constants().backing);
584 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800585 return kInvalidStorageId;
586 }
587
Songchun Fan3c82a302019-11-29 14:23:45 -0800588 IncFsMount::Control control;
589 {
590 std::lock_guard l(mMountOperationLock);
591 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800592
593 if (auto err = rmDirContent(backing.c_str())) {
594 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
595 return kInvalidStorageId;
596 }
597 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
598 return kInvalidStorageId;
599 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800600 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
601 return kInvalidStorageId;
602 }
Songchun Fanf949c372021-04-27 11:26:25 -0700603 auto status = mVold->mountIncFs(backing, mountTarget, 0, mountKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800604 if (!status.isOk()) {
605 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
606 return kInvalidStorageId;
607 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800608 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
609 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800610 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
611 return kInvalidStorageId;
612 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800613 int cmd = controlParcel.cmd.release().release();
614 int pendingReads = controlParcel.pendingReads.release().release();
615 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800616 int blocksWritten =
617 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
618 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800619 }
620
621 std::unique_lock l(mLock);
622 const auto mountIt = getStorageSlotLocked();
623 const auto mountId = mountIt->first;
624 l.unlock();
625
626 auto ifs =
627 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
628 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
629 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700630 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800631
632 auto secondCleanup = [this, &l](auto itPtr) {
633 if (!l.owns_lock()) {
634 l.lock();
635 }
636 mMounts.erase(*itPtr);
637 };
638 auto secondCleanupOnFailure =
639 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
640
641 const auto storageIt = ifs->makeStorage(ifs->mountId);
642 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800643 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800644 return kInvalidStorageId;
645 }
646
647 {
648 metadata::Mount m;
649 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700650 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700651 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
652 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
653 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800654 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800655 if (auto err =
656 mIncFs->makeFile(ifs->control,
657 path::join(ifs->root, constants().mount,
658 constants().infoMdName),
659 0777, idFromMetadata(metadata),
660 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800661 LOG(ERROR) << "Saving mount metadata failed: " << -err;
662 return kInvalidStorageId;
663 }
664 }
665
666 const auto bk =
667 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800668 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
669 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800670 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800671 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800672 return kInvalidStorageId;
673 }
674
675 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700676 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800677
Songchun Fan3c82a302019-11-29 14:23:45 -0800678 mountIt->second = std::move(ifs);
679 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700680
Songchun Fan3c82a302019-11-29 14:23:45 -0800681 LOG(INFO) << "created storage " << mountId;
682 return mountId;
683}
684
685StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
686 StorageId linkedStorage,
687 IncrementalService::CreateOptions options) {
688 if (!isValidMountTarget(mountPoint)) {
689 LOG(ERROR) << "Mount point is invalid or missing";
690 return kInvalidStorageId;
691 }
692
693 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700694 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800695 if (!ifs) {
696 LOG(ERROR) << "Ifs unavailable";
697 return kInvalidStorageId;
698 }
699
700 const auto mountIt = getStorageSlotLocked();
701 const auto storageId = mountIt->first;
702 const auto storageIt = ifs->makeStorage(storageId);
703 if (storageIt == ifs->storages.end()) {
704 LOG(ERROR) << "Can't create a new storage";
705 mMounts.erase(mountIt);
706 return kInvalidStorageId;
707 }
708
709 l.unlock();
710
711 const auto bk =
712 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800713 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
714 std::string(storageIt->second.name), path::normalize(mountPoint),
715 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800716 err < 0) {
717 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700718 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
719 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800720 return kInvalidStorageId;
721 }
722
723 mountIt->second = ifs;
724 return storageId;
725}
726
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700727bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700728 content::pm::DataLoaderParamsParcel dataLoaderParams,
729 DataLoaderStatusListener statusListener,
730 const StorageHealthCheckParams& healthCheckParams,
731 StorageHealthListener healthListener,
732 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800733 // Per Uid timeouts.
734 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700735 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800736 }
737
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700738 IfsMountPtr ifs;
739 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800740
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700741 // Re-initialize DataLoader.
742 {
743 ifs = getIfs(storageId);
744 if (!ifs) {
745 return false;
746 }
747
748 std::unique_lock l(ifs->lock);
749 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
750 }
751
752 if (dataLoaderStub) {
753 dataLoaderStub->cleanupResources();
754 dataLoaderStub = {};
755 }
756
757 {
758 std::unique_lock l(ifs->lock);
759 if (ifs->dataLoaderStub) {
760 LOG(INFO) << "Skipped data loader stub creation because it already exists";
761 return false;
762 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700763
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700764 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
765 healthCheckParams, std::move(healthListener));
766 CHECK(ifs->dataLoaderStub);
767 dataLoaderStub = ifs->dataLoaderStub;
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700768
769 // Disable long read timeouts for non-system dataloaders.
770 // To be re-enabled after installation is complete.
771 ifs->setReadTimeoutsRequested(dataLoaderStub->isSystemDataLoader() &&
772 getAlwaysEnableReadTimeoutsForSystemDataLoaders());
773 applyStorageParamsLocked(*ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700774 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800775
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700776 if (dataLoaderStub->isSystemDataLoader() &&
777 !getEnforceReadLogsMaxIntervalForSystemDataLoaders()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700778 // Readlogs from system dataloader (adb) can always be collected.
779 ifs->startLoadingTs = TimePoint::max();
780 } else {
781 // Assign time when installation wants the DL to start streaming.
782 const auto startLoadingTs = mClock->now();
783 ifs->startLoadingTs = startLoadingTs;
784 // Setup a callback to disable the readlogs after max interval.
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700785 addTimedJob(*mTimedQueue, storageId, getReadLogsMaxInterval(),
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700786 [this, storageId, startLoadingTs]() {
787 const auto ifs = getIfs(storageId);
788 if (!ifs) {
789 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
790 << storageId;
791 return;
792 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700793 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700794 if (ifs->startLoadingTs != startLoadingTs) {
795 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
796 "installation?): "
797 << storageId;
798 return;
799 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700800 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700801 });
802 }
803
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800804 return dataLoaderStub->requestStart();
805}
806
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700807void IncrementalService::onInstallationComplete(StorageId storage) {
808 IfsMountPtr ifs = getIfs(storage);
809 if (!ifs) {
810 return;
811 }
812
813 // Always enable long read timeouts after installation is complete.
814 std::unique_lock l(ifs->lock);
815 ifs->setReadTimeoutsRequested(true);
816 applyStorageParamsLocked(*ifs);
817}
818
Songchun Fan3c82a302019-11-29 14:23:45 -0800819IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
820 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700821 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800822}
823
824StorageId IncrementalService::findStorageId(std::string_view path) const {
825 std::lock_guard l(mLock);
826 auto it = findStorageLocked(path);
827 if (it == mBindsByPath.end()) {
828 return kInvalidStorageId;
829 }
830 return it->second->second.storage;
831}
832
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800833void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700834 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700835 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800836 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700837 return;
838 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700839
840 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800841 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700842 return;
843 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800844 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700845
846 const auto metadata = constants().readLogsDisabledMarkerName;
847 if (auto err = mIncFs->makeFile(ifs->control,
848 path::join(ifs->root, constants().mount,
849 constants().readLogsDisabledMarkerName),
850 0777, idFromMetadata(metadata), {})) {
851 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
852 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
853 return;
854 }
855
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700856 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700857}
858
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700859int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
860 const auto ifs = getIfs(storageId);
861 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700862 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700863 return -EINVAL;
864 }
865
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700866 std::string packageName;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700867
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700868 {
869 std::unique_lock l(ifs->lock);
870 if (!enableReadLogs) {
871 return disableReadLogsLocked(*ifs);
872 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700873
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700874 if (!ifs->readLogsAllowed()) {
875 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
876 return -EPERM;
877 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700878
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700879 if (!ifs->dataLoaderStub) {
880 // This should never happen - only DL can call enableReadLogs.
881 LOG(ERROR) << "enableReadLogs failed: invalid state";
882 return -EPERM;
883 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700884
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700885 // Check installation time.
886 const auto now = mClock->now();
887 const auto startLoadingTs = ifs->startLoadingTs;
888 if (startLoadingTs <= now && now - startLoadingTs > getReadLogsMaxInterval()) {
889 LOG(ERROR)
890 << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
891 << storageId;
892 return -EPERM;
893 }
894
895 packageName = ifs->dataLoaderStub->params().packageName;
896 ifs->setReadLogsRequested(true);
897 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700898
899 // Check loader usage stats permission and apop.
900 if (auto status =
901 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
902 !status.isOk()) {
903 LOG(ERROR) << " Permission: " << kLoaderUsageStats
904 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700905 return fromBinderStatus(status);
906 }
907
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700908 // Check multiuser permission.
909 if (auto status =
910 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
911 !status.isOk()) {
912 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
913 << " check failed: " << status.toString8();
914 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700915 }
916
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700917 {
918 std::unique_lock l(ifs->lock);
919 if (!ifs->readLogsRequested()) {
920 return 0;
921 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700922 if (auto status = applyStorageParamsLocked(*ifs); status != 0) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700923 return status;
924 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700925 }
926
927 registerAppOpsCallback(packageName);
928
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700929 return 0;
930}
931
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700932int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700933 ifs.setReadLogsRequested(false);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700934 return applyStorageParamsLocked(ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700935}
936
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700937int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700938 os::incremental::IncrementalFileSystemControlParcel control;
939 control.cmd.reset(dup(ifs.control.cmd()));
940 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700941 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700942 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700943 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700944 }
945
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700946 bool enableReadLogs = ifs.readLogsRequested();
947 bool enableReadTimeouts = ifs.readTimeoutsRequested();
948
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700949 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700950 auto status = mVold->setIncFsMountOptions(control, enableReadLogs, enableReadTimeouts);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800951 if (status.isOk()) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700952 // Store states.
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800953 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700954 ifs.setReadTimeoutsEnabled(enableReadTimeouts);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700955 } else {
956 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800957 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700958 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700959}
960
Songchun Fan3c82a302019-11-29 14:23:45 -0800961void IncrementalService::deleteStorage(StorageId storageId) {
962 const auto ifs = getIfs(storageId);
963 if (!ifs) {
964 return;
965 }
966 deleteStorage(*ifs);
967}
968
969void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
970 std::unique_lock l(ifs.lock);
971 deleteStorageLocked(ifs, std::move(l));
972}
973
974void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
975 std::unique_lock<std::mutex>&& ifsLock) {
976 const auto storages = std::move(ifs.storages);
977 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
978 const auto bindPoints = ifs.bindPoints;
979 ifsLock.unlock();
980
981 std::lock_guard l(mLock);
982 for (auto&& [id, _] : storages) {
983 if (id != ifs.mountId) {
984 mMounts.erase(id);
985 }
986 }
987 for (auto&& [path, _] : bindPoints) {
988 mBindsByPath.erase(path);
989 }
990 mMounts.erase(ifs.mountId);
991}
992
993StorageId IncrementalService::openStorage(std::string_view pathInMount) {
994 if (!path::isAbsolute(pathInMount)) {
995 return kInvalidStorageId;
996 }
997
998 return findStorageId(path::normalize(pathInMount));
999}
1000
Songchun Fan3c82a302019-11-29 14:23:45 -08001001IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
1002 std::lock_guard l(mLock);
1003 return getIfsLocked(storage);
1004}
1005
1006const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
1007 auto it = mMounts.find(storage);
1008 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001009 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -07001010 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -08001011 }
1012 return it->second;
1013}
1014
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001015int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
1016 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001017 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001018 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001019 return -EINVAL;
1020 }
1021
1022 const auto ifs = getIfs(storage);
1023 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001024 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001025 return -EINVAL;
1026 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001027
Songchun Fan3c82a302019-11-29 14:23:45 -08001028 std::unique_lock l(ifs->lock);
1029 const auto storageInfo = ifs->storages.find(storage);
1030 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001031 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -08001032 return -EINVAL;
1033 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001034 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001035 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001036 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001037 return -EINVAL;
1038 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001039 l.unlock();
1040 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001041 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
1042 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -08001043}
1044
1045int IncrementalService::unbind(StorageId storage, std::string_view target) {
1046 if (!path::isAbsolute(target)) {
1047 return -EINVAL;
1048 }
1049
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001050 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001051
1052 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
1053 // otherwise there's a chance to unmount something completely unrelated
1054 const auto norm = path::normalize(target);
1055 std::unique_lock l(mLock);
1056 const auto storageIt = mBindsByPath.find(norm);
1057 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
1058 return -EINVAL;
1059 }
1060 const auto bindIt = storageIt->second;
1061 const auto storageId = bindIt->second.storage;
1062 const auto ifs = getIfsLocked(storageId);
1063 if (!ifs) {
1064 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
1065 << " is missing";
1066 return -EFAULT;
1067 }
1068 mBindsByPath.erase(storageIt);
1069 l.unlock();
1070
1071 mVold->unmountIncFs(bindIt->first);
1072 std::unique_lock l2(ifs->lock);
1073 if (ifs->bindPoints.size() <= 1) {
1074 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -07001075 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001076 } else {
1077 const std::string savedFile = std::move(bindIt->second.savedFilename);
1078 ifs->bindPoints.erase(bindIt);
1079 l2.unlock();
1080 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001081 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001082 }
1083 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001084
Songchun Fan3c82a302019-11-29 14:23:45 -08001085 return 0;
1086}
1087
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001088std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001089 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001090 std::string_view path) const {
1091 if (!path::isAbsolute(path)) {
1092 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001093 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001094 auto normPath = path::normalize(path);
1095 if (path::startsWith(normPath, storageIt->second.name)) {
1096 return normPath;
1097 }
1098 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001099 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1100 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001101 return {};
1102 }
1103 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001104}
1105
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001106std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001107 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001108 std::unique_lock l(ifs.lock);
1109 const auto storageInfo = ifs.storages.find(storage);
1110 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001111 return {};
1112 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001113 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001114}
1115
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001116int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001117 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001118 const auto ifs = getIfs(storage);
1119 if (!ifs) {
1120 return -EINVAL;
1121 }
1122 if (data.size() > params.size) {
1123 LOG(ERROR) << "Bad data size - bigger than file size";
1124 return -EINVAL;
1125 }
1126 if (!data.empty() && data.size() != params.size) {
1127 // Writing a page is an irreversible operation, and it can't be updated with additional
1128 // data later. Check that the last written page is complete, or we may break the file.
1129 if (!isPageAligned(data.size())) {
1130 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001131 return -EINVAL;
1132 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001133 }
1134 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1135 if (normPath.empty()) {
1136 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1137 return -EINVAL;
1138 }
1139 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1140 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1141 return err;
1142 }
1143 if (params.size > 0) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001144 if (auto err = mIncFs->reserveSpace(ifs->control, id, params.size)) {
1145 if (err != -EOPNOTSUPP) {
1146 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1147 (void)mIncFs->unlink(ifs->control, normPath);
1148 return err;
1149 } else {
1150 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1151 "may run out of disk later";
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001152 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001153 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001154 if (!data.empty()) {
1155 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001156 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001157 return err;
1158 }
1159 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001160 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001161 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001162}
1163
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001164int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001165 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001166 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001167 if (normPath.empty()) {
1168 return -EINVAL;
1169 }
1170 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001171 }
1172 return -EINVAL;
1173}
1174
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001175int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001176 const auto ifs = getIfs(storageId);
1177 if (!ifs) {
1178 return -EINVAL;
1179 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001180 return makeDirs(*ifs, storageId, path, mode);
1181}
1182
1183int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1184 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001185 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1186 if (normPath.empty()) {
1187 return -EINVAL;
1188 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001189 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001190}
1191
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001192int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1193 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001194 std::unique_lock l(mLock);
1195 auto ifsSrc = getIfsLocked(sourceStorageId);
1196 if (!ifsSrc) {
1197 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001198 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001199 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1200 return -EINVAL;
1201 }
1202 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001203 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1204 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001205 if (normOldPath.empty() || normNewPath.empty()) {
1206 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1207 return -EINVAL;
1208 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001209 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1210 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1211 << " to " << newPath << "[" << normNewPath << "]";
1212 return err;
1213 }
1214 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001215}
1216
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001217int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001218 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001219 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001220 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001221 }
1222 return -EINVAL;
1223}
1224
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001225int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1226 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001227 std::string&& target, BindKind kind,
1228 std::unique_lock<std::mutex>& mainLock) {
1229 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001230 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001231 return -EINVAL;
1232 }
1233
1234 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001235 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001236 if (kind != BindKind::Temporary) {
1237 metadata::BindPoint bp;
1238 bp.set_storage_id(storage);
1239 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001240 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001241 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001242 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001243 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001244 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001245 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1246 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1247 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001248 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001249 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001250 return int(node);
1251 }
1252 }
1253
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001254 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1255 std::move(target), kind, mainLock);
1256 if (res) {
1257 mIncFs->unlink(ifs.control, metadataFullPath);
1258 }
1259 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001260}
1261
1262int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001263 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001264 std::string&& target, BindKind kind,
1265 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001266 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001267 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001268 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001269 if (!status.isOk()) {
1270 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1271 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1272 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1273 : status.serviceSpecificErrorCode() == 0
1274 ? -EFAULT
1275 : status.serviceSpecificErrorCode()
1276 : -EIO;
1277 }
1278 }
1279
1280 if (!mainLock.owns_lock()) {
1281 mainLock.lock();
1282 }
1283 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001284 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1285 std::move(target), kind);
1286 return 0;
1287}
1288
1289void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1290 std::string&& metadataName, std::string&& source,
1291 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001292 const auto [it, _] =
1293 ifs.bindPoints.insert_or_assign(target,
1294 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001295 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001296 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001297}
1298
1299RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1300 const auto ifs = getIfs(storage);
1301 if (!ifs) {
1302 return {};
1303 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001304 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001305 if (normPath.empty()) {
1306 return {};
1307 }
1308 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001309}
1310
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001311RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001312 const auto ifs = getIfs(storage);
1313 if (!ifs) {
1314 return {};
1315 }
1316 return mIncFs->getMetadata(ifs->control, node);
1317}
1318
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001319void IncrementalService::setUidReadTimeouts(StorageId storage,
1320 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001321 using microseconds = std::chrono::microseconds;
1322 using milliseconds = std::chrono::milliseconds;
1323
1324 auto maxPendingTimeUs = microseconds(0);
1325 for (const auto& timeouts : perUidReadTimeouts) {
1326 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1327 }
1328 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07001329 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001330 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1331 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001332 return;
1333 }
1334
1335 const auto ifs = getIfs(storage);
1336 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001337 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001338 return;
1339 }
1340
1341 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1342 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1343 return;
1344 }
1345
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001346 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1347 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1348 if (checkUidReadTimeouts(storageId, state, timeout)) {
1349 return true;
1350 }
1351 clearUidReadTimeouts(storageId);
1352 return false;
1353 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001354}
1355
1356void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1357 const auto ifs = getIfs(storage);
1358 if (!ifs) {
1359 return;
1360 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001361 mIncFs->setUidReadTimeouts(ifs->control, {});
1362}
1363
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001364bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1365 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001366 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001367 // Reached maximum timeout.
1368 return false;
1369 }
1370 if (state.error) {
1371 // Something is wrong, abort.
1372 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001373 }
1374
1375 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001376 if (state.fullyLoaded && !state.readLogsEnabled) {
1377 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001378 }
1379
1380 const auto timeLeft = timeLimit - Clock::now();
1381 if (timeLeft < Constants::progressUpdateInterval) {
1382 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001383 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001384 }
1385
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001386 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001387}
1388
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001389std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1390 std::unordered_set<std::string_view> mountedRootNames;
1391 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1392 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1393 for (auto [source, target] : binds) {
1394 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1395 LOG(INFO) << " " << path::join(root, source);
1396 }
1397
1398 // Ensure it's a kind of a mount that's managed by IncrementalService
1399 if (path::basename(root) != constants().mount ||
1400 path::basename(backingDir) != constants().backing) {
1401 return;
1402 }
1403 const auto expectedRoot = path::dirname(root);
1404 if (path::dirname(backingDir) != expectedRoot) {
1405 return;
1406 }
1407 if (path::dirname(expectedRoot) != mIncrementalDir) {
1408 return;
1409 }
1410 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1411 return;
1412 }
1413
1414 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1415
1416 // make sure we clean up the mount if it happens to be a bad one.
1417 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1418 auto cleanupFiles = makeCleanup([&]() {
1419 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1420 IncFsMount::cleanupFilesystem(expectedRoot);
1421 });
1422 auto cleanupMounts = makeCleanup([&]() {
1423 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1424 for (auto&& [_, target] : binds) {
1425 mVold->unmountIncFs(std::string(target));
1426 }
1427 mVold->unmountIncFs(std::string(root));
1428 });
1429
1430 auto control = mIncFs->openMount(root);
1431 if (!control) {
1432 LOG(INFO) << "failed to open mount " << root;
1433 return;
1434 }
1435
1436 auto mountRecord =
1437 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1438 path::join(root, constants().infoMdName));
1439 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1440 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1441 return;
1442 }
1443
1444 auto mountId = mountRecord.storage().id();
1445 mNextId = std::max(mNextId, mountId + 1);
1446
1447 DataLoaderParamsParcel dataLoaderParams;
1448 {
1449 const auto& loader = mountRecord.loader();
1450 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1451 dataLoaderParams.packageName = loader.package_name();
1452 dataLoaderParams.className = loader.class_name();
1453 dataLoaderParams.arguments = loader.arguments();
1454 }
1455
1456 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1457 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001458 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001459
Alex Buynytskyy04035452020-06-06 20:15:58 -07001460 // Check if marker file present.
1461 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001462 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001463 }
1464
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001465 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1466 auto d = openDir(root);
1467 while (auto e = ::readdir(d.get())) {
1468 if (e->d_type == DT_REG) {
1469 auto name = std::string_view(e->d_name);
1470 if (name.starts_with(constants().mountpointMdPrefix)) {
1471 permanentBindPoints
1472 .emplace_back(name,
1473 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1474 ifs->control,
1475 path::join(root,
1476 name)));
1477 if (permanentBindPoints.back().second.dest_path().empty() ||
1478 permanentBindPoints.back().second.source_subdir().empty()) {
1479 permanentBindPoints.pop_back();
1480 mIncFs->unlink(ifs->control, path::join(root, name));
1481 } else {
1482 LOG(INFO) << "Permanent bind record: '"
1483 << permanentBindPoints.back().second.source_subdir() << "'->'"
1484 << permanentBindPoints.back().second.dest_path() << "'";
1485 }
1486 }
1487 } else if (e->d_type == DT_DIR) {
1488 if (e->d_name == "."sv || e->d_name == ".."sv) {
1489 continue;
1490 }
1491 auto name = std::string_view(e->d_name);
1492 if (name.starts_with(constants().storagePrefix)) {
1493 int storageId;
1494 const auto res =
1495 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1496 name.data() + name.size(), storageId);
1497 if (res.ec != std::errc{} || *res.ptr != '_') {
1498 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1499 << "' for mount " << expectedRoot;
1500 continue;
1501 }
1502 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1503 if (!inserted) {
1504 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1505 << " for mount " << expectedRoot;
1506 continue;
1507 }
1508 ifs->storages.insert_or_assign(storageId,
1509 IncFsMount::Storage{path::join(root, name)});
1510 mNextId = std::max(mNextId, storageId + 1);
1511 }
1512 }
1513 }
1514
1515 if (ifs->storages.empty()) {
1516 LOG(WARNING) << "No valid storages in mount " << root;
1517 return;
1518 }
1519
1520 // now match the mounted directories with what we expect to have in the metadata
1521 {
1522 std::unique_lock l(mLock, std::defer_lock);
1523 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1524 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1525 [&, bindRecord = bindRecord](auto&& bind) {
1526 return bind.second == bindRecord.dest_path() &&
1527 path::join(root, bind.first) ==
1528 bindRecord.source_subdir();
1529 });
1530 if (mountedIt != binds.end()) {
1531 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1532 << " to mount " << mountedIt->first;
1533 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1534 std::move(*bindRecord.mutable_source_subdir()),
1535 std::move(*bindRecord.mutable_dest_path()),
1536 BindKind::Permanent);
1537 if (mountedIt != binds.end() - 1) {
1538 std::iter_swap(mountedIt, binds.end() - 1);
1539 }
1540 binds = binds.first(binds.size() - 1);
1541 } else {
1542 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1543 << ", mounting";
1544 // doesn't exist - try mounting back
1545 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1546 std::move(*bindRecord.mutable_source_subdir()),
1547 std::move(*bindRecord.mutable_dest_path()),
1548 BindKind::Permanent, l)) {
1549 mIncFs->unlink(ifs->control, metadataFile);
1550 }
1551 }
1552 }
1553 }
1554
1555 // if anything stays in |binds| those are probably temporary binds; system restarted since
1556 // they were mounted - so let's unmount them all.
1557 for (auto&& [source, target] : binds) {
1558 if (source.empty()) {
1559 continue;
1560 }
1561 mVold->unmountIncFs(std::string(target));
1562 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001563 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001564
1565 if (ifs->bindPoints.empty()) {
1566 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1567 deleteStorage(*ifs);
1568 return;
1569 }
1570
1571 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1572 CHECK(ifs->dataLoaderStub);
1573
1574 mountedRootNames.insert(path::basename(ifs->root));
1575
1576 // not locking here at all: we're still in the constructor, no other calls can happen
1577 mMounts[ifs->mountId] = std::move(ifs);
1578 });
1579
1580 return mountedRootNames;
1581}
1582
1583void IncrementalService::mountExistingImages(
1584 const std::unordered_set<std::string_view>& mountedRootNames) {
1585 auto dir = openDir(mIncrementalDir);
1586 if (!dir) {
1587 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1588 return;
1589 }
1590 while (auto entry = ::readdir(dir.get())) {
1591 if (entry->d_type != DT_DIR) {
1592 continue;
1593 }
1594 std::string_view name = entry->d_name;
1595 if (!name.starts_with(constants().mountKeyPrefix)) {
1596 continue;
1597 }
1598 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001599 continue;
1600 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001601 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001602 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001603 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001604 }
1605 }
1606}
1607
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001608bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001609 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001610 const auto backing = path::join(root, constants().backing);
Songchun Fanf949c372021-04-27 11:26:25 -07001611 std::string mountKey(path::basename(path::dirname(mountTarget)));
Songchun Fan3c82a302019-11-29 14:23:45 -08001612
Songchun Fan3c82a302019-11-29 14:23:45 -08001613 IncrementalFileSystemControlParcel controlParcel;
Songchun Fanf949c372021-04-27 11:26:25 -07001614 auto status = mVold->mountIncFs(backing, mountTarget, 0, mountKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001615 if (!status.isOk()) {
1616 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1617 return false;
1618 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001619
1620 int cmd = controlParcel.cmd.release().release();
1621 int pendingReads = controlParcel.pendingReads.release().release();
1622 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001623 int blocksWritten =
1624 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1625 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001626
1627 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1628
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001629 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1630 path::join(mountTarget, constants().infoMdName));
1631 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001632 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1633 return false;
1634 }
1635
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001636 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001637 mNextId = std::max(mNextId, ifs->mountId + 1);
1638
Alex Buynytskyy04035452020-06-06 20:15:58 -07001639 // Check if marker file present.
1640 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001641 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001642 }
1643
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001644 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001645 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001646 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001647 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001648 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001649 dataLoaderParams.packageName = loader.package_name();
1650 dataLoaderParams.className = loader.class_name();
1651 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001652 }
1653
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001654 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001655 CHECK(ifs->dataLoaderStub);
1656
Songchun Fan3c82a302019-11-29 14:23:45 -08001657 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001658 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001659 while (auto e = ::readdir(d.get())) {
1660 if (e->d_type == DT_REG) {
1661 auto name = std::string_view(e->d_name);
1662 if (name.starts_with(constants().mountpointMdPrefix)) {
1663 bindPoints.emplace_back(name,
1664 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1665 ifs->control,
1666 path::join(mountTarget,
1667 name)));
1668 if (bindPoints.back().second.dest_path().empty() ||
1669 bindPoints.back().second.source_subdir().empty()) {
1670 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001671 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001672 }
1673 }
1674 } else if (e->d_type == DT_DIR) {
1675 if (e->d_name == "."sv || e->d_name == ".."sv) {
1676 continue;
1677 }
1678 auto name = std::string_view(e->d_name);
1679 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001680 int storageId;
1681 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1682 name.data() + name.size(), storageId);
1683 if (res.ec != std::errc{} || *res.ptr != '_') {
1684 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1685 << root;
1686 continue;
1687 }
1688 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001689 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001690 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001691 << " for mount " << root;
1692 continue;
1693 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001694 ifs->storages.insert_or_assign(storageId,
1695 IncFsMount::Storage{
1696 path::join(root, constants().mount, name)});
1697 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001698 }
1699 }
1700 }
1701
1702 if (ifs->storages.empty()) {
1703 LOG(WARNING) << "No valid storages in mount " << root;
1704 return false;
1705 }
1706
1707 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001708 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001709 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001710 for (auto&& bp : bindPoints) {
1711 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1712 std::move(*bp.second.mutable_source_subdir()),
1713 std::move(*bp.second.mutable_dest_path()),
1714 BindKind::Permanent, l);
1715 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001716 }
1717
1718 if (bindCount == 0) {
1719 LOG(WARNING) << "No valid bind points for mount " << root;
1720 deleteStorage(*ifs);
1721 return false;
1722 }
1723
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001724 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001725 mMounts[ifs->mountId] = std::move(ifs);
1726 return true;
1727}
1728
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001729void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001730 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001731 while (mRunning.load(std::memory_order_relaxed)) {
1732 mLooper->pollAll(kTimeoutMsecs);
1733 }
1734}
1735
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001736void IncrementalService::trimReservedSpaceV1(const IncFsMount& ifs) {
1737 mIncFs->forEachFile(ifs.control, [this](auto&& control, auto&& fileId) {
1738 if (mIncFs->isFileFullyLoaded(control, fileId) == incfs::LoadingState::Full) {
1739 mIncFs->reserveSpace(control, fileId, -1);
1740 }
1741 return true;
1742 });
1743}
1744
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001745void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001746 DataLoaderStatusListener&& statusListener,
1747 const StorageHealthCheckParams& healthCheckParams,
1748 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001749 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001750 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001751 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1752 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1753 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001754 if (ifs.control.blocksWritten() >= 0) {
1755 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1756 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001757 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001758
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001759 ifs.dataLoaderStub =
1760 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001761 std::move(statusListener), healthCheckParams,
1762 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001763
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001764 // pre-v2 IncFS doesn't do automatic reserved space trimming - need to run it manually
1765 if (!(mIncFs->features() & incfs::Features::v2)) {
1766 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1767 if (!state.fullyLoaded) {
1768 return true;
1769 }
1770
1771 const auto ifs = getIfs(storageId);
1772 if (!ifs) {
1773 return false;
1774 }
1775 trimReservedSpaceV1(*ifs);
1776 return false;
1777 });
1778 }
1779
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001780 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1781 if (!state.fullyLoaded || state.readLogsEnabled) {
1782 return true;
1783 }
1784
1785 DataLoaderStubPtr dataLoaderStub;
1786 {
1787 const auto ifs = getIfs(storageId);
1788 if (!ifs) {
1789 return false;
1790 }
1791
1792 std::unique_lock l(ifs->lock);
1793 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1794 }
1795
1796 if (dataLoaderStub) {
1797 dataLoaderStub->cleanupResources();
1798 }
1799
1800 return false;
1801 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001802}
1803
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001804template <class Duration>
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001805static constexpr auto castToMs(Duration d) {
1806 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1807}
1808
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001809// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001810// Lib files should be placed next to the APK file in the following matter:
1811// Example:
1812// /path/to/base.apk
1813// /path/to/lib/arm/first.so
1814// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001815bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1816 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001817 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001818 auto start = Clock::now();
1819
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001820 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001821 if (!ifs) {
1822 LOG(ERROR) << "Invalid storage " << storage;
1823 return false;
1824 }
1825
Songchun Fanc8975312020-07-13 12:14:37 -07001826 const auto targetLibPathRelativeToStorage =
1827 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1828 libDirRelativePath);
1829
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001830 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001831 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1832 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001833 << " errno: " << res;
1834 return false;
1835 }
1836
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001837 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001838 ZipArchiveHandle zipFileHandle;
1839 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001840 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1841 return false;
1842 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001843
1844 // Need a shared pointer: will be passing it into all unpacking jobs.
1845 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001846 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001847 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001848 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001849 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1850 return false;
1851 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001852 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001853 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1854
1855 auto openZipTs = Clock::now();
1856
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001857 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1858 incfs::FileId sourceId;
1859 if (mapFiles) {
1860 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1861 if (!incfs::isValidFileId(sourceId)) {
1862 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1863 << "', mapping disabled";
1864 mapFiles = false;
1865 }
1866 }
1867
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001868 std::vector<Job> jobQueue;
1869 ZipEntry entry;
1870 std::string_view fileName;
1871 while (!Next(cookie, &entry, &fileName)) {
1872 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001873 continue;
1874 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001875
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001876 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001877 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001878
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001879 if (!extractNativeLibs) {
1880 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001881 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001882 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1883 return false;
1884 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001885 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001886 LOG(WARNING) << "Library " << fileName
1887 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1888 << entry.offset;
1889 return false;
1890 }
1891 continue;
1892 }
1893
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001894 auto startFileTs = Clock::now();
1895
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001896 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001897 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001898 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001899 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001900 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001901 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001902 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1903 << "; skipping extraction, spent "
1904 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1905 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001906 continue;
1907 }
1908
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001909 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1910 incfs::NewMappedFileParams mappedFileParams = {
1911 .sourceId = sourceId,
1912 .sourceOffset = entry.offset,
1913 .size = entry.uncompressed_length,
1914 };
1915
1916 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1917 mappedFileParams);
1918 res == 0) {
1919 if (perfLoggingEnabled()) {
1920 auto doneTs = Clock::now();
1921 LOG(INFO) << "incfs: Mapped " << libName << ": "
1922 << elapsedMcs(startFileTs, doneTs) << "mcs";
1923 }
1924 continue;
1925 } else {
1926 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1927 << "; falling back to full extraction";
1928 }
1929 }
1930
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001931 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001932 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001933 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001934 .signature = {},
1935 // Metadata of the new lib file is its relative path
1936 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1937 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001938 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001939 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001940 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001941 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001942 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001943 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001944 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001945
1946 auto makeFileTs = Clock::now();
1947
Songchun Fanafaf6e92020-03-18 14:12:20 -07001948 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001949 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001950 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001951 LOG(INFO) << "incfs: Extracted " << libName
1952 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001953 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001954 continue;
1955 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001956
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001957 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1958 libFileId, libPath = std::move(targetLibPath),
1959 makeFileTs]() mutable {
1960 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001961 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001962
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001963 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001964 auto prepareJobTs = Clock::now();
1965 LOG(INFO) << "incfs: Processed " << libName << ": "
1966 << elapsedMcs(startFileTs, prepareJobTs)
1967 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1968 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001969 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001970 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001971
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001972 auto processedTs = Clock::now();
1973
1974 if (!jobQueue.empty()) {
1975 {
1976 std::lock_guard lock(mJobMutex);
1977 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001978 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001979 if (existingJobs.empty()) {
1980 existingJobs = std::move(jobQueue);
1981 } else {
1982 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1983 std::move_iterator(jobQueue.end()));
1984 }
1985 }
1986 }
1987 mJobCondition.notify_all();
1988 }
1989
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001990 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001991 auto end = Clock::now();
1992 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1993 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1994 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001995 << " make files: " << elapsedMcs(openZipTs, processedTs)
1996 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001997 }
1998
1999 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002000}
2001
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002002void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
2003 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002004 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002005 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002006 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002007 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002008 return;
2009 }
2010
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002011 auto startedTs = Clock::now();
2012
2013 // Write extracted data to new file
2014 // NOTE: don't zero-initialize memory, it may take a while for nothing
2015 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
2016 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002017 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002018 return;
2019 }
2020
2021 auto extractFileTs = Clock::now();
2022
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002023 if (setFileContent(ifs, libFileId, debugLibPath,
2024 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002025 return;
2026 }
2027
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002028 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002029 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002030 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
2031 << entry.compressed_length << " -> " << entry.uncompressed_length
2032 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002033 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
2034 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002035 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002036 }
2037}
2038
2039bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002040 struct WaitPrinter {
2041 const Clock::time_point startTs = Clock::now();
2042 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002043 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002044 const auto endTs = Clock::now();
2045 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
2046 << elapsedMcs(startTs, endTs) << "mcs";
2047 }
2048 }
2049 } waitPrinter;
2050
2051 MountId mount;
2052 {
2053 auto ifs = getIfs(storage);
2054 if (!ifs) {
2055 return true;
2056 }
2057 mount = ifs->mountId;
2058 }
2059
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002060 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002061 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002062 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002063 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002064 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002065 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002066}
2067
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002068int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
2069 std::string_view debugFilePath,
2070 std::span<const uint8_t> data) const {
2071 auto startTs = Clock::now();
2072
2073 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2074 if (!writeFd.ok()) {
2075 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2076 << " errno: " << writeFd.get();
2077 return writeFd.get();
2078 }
2079
2080 const auto dataLength = data.size();
2081
2082 auto openFileTs = Clock::now();
2083 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2084 std::vector<IncFsDataBlock> instructions(numBlocks);
2085 for (int i = 0; i < numBlocks; i++) {
2086 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2087 instructions[i] = IncFsDataBlock{
2088 .fileFd = writeFd.get(),
2089 .pageIndex = static_cast<IncFsBlockIndex>(i),
2090 .compression = INCFS_COMPRESSION_KIND_NONE,
2091 .kind = INCFS_BLOCK_KIND_DATA,
2092 .dataSize = static_cast<uint32_t>(blockSize),
2093 .data = reinterpret_cast<const char*>(data.data()),
2094 };
2095 data = data.subspan(blockSize);
2096 }
2097 auto prepareInstsTs = Clock::now();
2098
2099 size_t res = mIncFs->writeBlocks(instructions);
2100 if (res != instructions.size()) {
2101 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2102 return res;
2103 }
2104
2105 if (perfLoggingEnabled()) {
2106 auto endTs = Clock::now();
2107 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2108 << " bytes): " << elapsedMcs(startTs, endTs)
2109 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2110 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2111 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2112 }
2113
2114 return 0;
2115}
2116
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002117incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2118 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002119 std::unique_lock l(mLock);
2120 const auto ifs = getIfsLocked(storage);
2121 if (!ifs) {
2122 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002123 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002124 }
2125 const auto storageInfo = ifs->storages.find(storage);
2126 if (storageInfo == ifs->storages.end()) {
2127 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002128 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002129 }
2130 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002131 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002132}
2133
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002134incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2135 const auto ifs = getIfs(storage);
2136 if (!ifs) {
2137 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2138 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002139 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002140 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002141}
2142
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002143IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002144 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002145 std::unique_lock l(mLock);
2146 const auto ifs = getIfsLocked(storage);
2147 if (!ifs) {
2148 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002149 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002150 }
2151 const auto storageInfo = ifs->storages.find(storage);
2152 if (storageInfo == ifs->storages.end()) {
2153 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002154 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002155 }
2156 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002157 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002158}
2159
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002160IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002161 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002162 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2163 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002164 const auto [filledBlocksCount, totalBlocksCount] =
2165 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002166 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2167 filledBlocksCount == -ENOENT) {
2168 // a kind of a file that's not really being loaded, e.g. a mapped range
2169 // an older IncFS used to return ENOENT in this case, so handle it the same way
2170 return true;
2171 }
Songchun Fan374f7652020-08-20 08:40:29 -07002172 if (filledBlocksCount < 0) {
2173 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002174 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002175 error = filledBlocksCount;
2176 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002177 }
2178 totalBlocks += totalBlocksCount;
2179 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002180 return true;
2181 });
Songchun Fan374f7652020-08-20 08:40:29 -07002182
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002183 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002184}
2185
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002186bool IncrementalService::updateLoadingProgress(StorageId storage,
2187 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002188 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002189 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002190 // Failed to get progress from incfs, abort.
2191 return false;
2192 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002193 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2194 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002195 // Stop updating progress once it is fully loaded
2196 return true;
2197 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002198 addTimedJob(*mProgressUpdateJobQueue, storage,
2199 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002200 [storage, progressListener = std::move(progressListener), this]() mutable {
2201 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002202 });
2203 return true;
2204}
2205
2206bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002207 StorageId storage, StorageLoadingProgressListener progressListener) {
2208 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002209}
2210
2211bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2212 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2213}
2214
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002215bool IncrementalService::perfLoggingEnabled() {
2216 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2217 return enabled;
2218}
2219
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002220void IncrementalService::runJobProcessing() {
2221 for (;;) {
2222 std::unique_lock lock(mJobMutex);
2223 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2224 if (!mRunning) {
2225 return;
2226 }
2227
2228 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002229 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002230 auto queue = std::move(it->second);
2231 mJobQueue.erase(it);
2232 lock.unlock();
2233
2234 for (auto&& job : queue) {
2235 job();
2236 }
2237
2238 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002239 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002240 lock.unlock();
2241 mJobCondition.notify_all();
2242 }
2243}
2244
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002245void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002246 sp<IAppOpsCallback> listener;
2247 {
2248 std::unique_lock lock{mCallbacksLock};
2249 auto& cb = mCallbackRegistered[packageName];
2250 if (cb) {
2251 return;
2252 }
2253 cb = new AppOpsListener(*this, packageName);
2254 listener = cb;
2255 }
2256
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002257 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2258 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002259}
2260
2261bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2262 sp<IAppOpsCallback> listener;
2263 {
2264 std::unique_lock lock{mCallbacksLock};
2265 auto found = mCallbackRegistered.find(packageName);
2266 if (found == mCallbackRegistered.end()) {
2267 return false;
2268 }
2269 listener = found->second;
2270 mCallbackRegistered.erase(found);
2271 }
2272
2273 mAppOpsManager->stopWatchingMode(listener);
2274 return true;
2275}
2276
2277void IncrementalService::onAppOpChanged(const std::string& packageName) {
2278 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002279 return;
2280 }
2281
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002282 std::vector<IfsMountPtr> affected;
2283 {
2284 std::lock_guard l(mLock);
2285 affected.reserve(mMounts.size());
2286 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002287 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002288 if (ifs->mountId == id && ifs->dataLoaderStub &&
2289 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002290 affected.push_back(ifs);
2291 }
2292 }
2293 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002294 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002295 std::unique_lock ll(ifs->lock);
2296 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002297 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002298}
2299
Songchun Fana7098592020-09-03 11:45:53 -07002300bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2301 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002302 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002303 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002304 }
Songchun Fana7098592020-09-03 11:45:53 -07002305 timedQueue.addJob(id, after, std::move(what));
2306 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002307}
2308
Songchun Fana7098592020-09-03 11:45:53 -07002309bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002310 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002311 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002312 }
Songchun Fana7098592020-09-03 11:45:53 -07002313 timedQueue.removeJobs(id);
2314 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002315}
2316
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002317void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2318 bool wasEmpty;
2319 {
2320 std::lock_guard l(mIfsStateCallbacksLock);
2321 wasEmpty = mIfsStateCallbacks.empty();
2322 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2323 }
2324 if (wasEmpty) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002325 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002326 [this]() { processIfsStateCallbacks(); });
2327 }
2328}
2329
2330void IncrementalService::processIfsStateCallbacks() {
2331 StorageId storageId = kInvalidStorageId;
2332 std::vector<IfsStateCallback> local;
2333 while (true) {
2334 {
2335 std::lock_guard l(mIfsStateCallbacksLock);
2336 if (mIfsStateCallbacks.empty()) {
2337 return;
2338 }
2339 IfsStateCallbacks::iterator it;
2340 if (storageId == kInvalidStorageId) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002341 // First entry, initialize the |it|.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002342 it = mIfsStateCallbacks.begin();
2343 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002344 // Subsequent entries, update the |storageId|, and shift to the new one (not that
2345 // it guarantees much about updated items, but at least the loop will finish).
2346 it = mIfsStateCallbacks.lower_bound(storageId);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002347 if (it == mIfsStateCallbacks.end()) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002348 // Nothing else left, too bad.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002349 break;
2350 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002351 if (it->first != storageId) {
2352 local.clear(); // Was removed during processing, forget the old callbacks.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002353 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002354 // Put the 'surviving' callbacks back into the map and advance the position.
2355 auto& callbacks = it->second;
2356 if (callbacks.empty()) {
2357 std::swap(callbacks, local);
2358 } else {
2359 callbacks.insert(callbacks.end(), std::move_iterator(local.begin()),
2360 std::move_iterator(local.end()));
2361 local.clear();
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002362 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002363 if (callbacks.empty()) {
2364 it = mIfsStateCallbacks.erase(it);
2365 if (mIfsStateCallbacks.empty()) {
2366 return;
2367 }
2368 } else {
2369 ++it;
2370 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002371 }
2372 }
2373
2374 if (it == mIfsStateCallbacks.end()) {
2375 break;
2376 }
2377
2378 storageId = it->first;
2379 auto& callbacks = it->second;
2380 if (callbacks.empty()) {
2381 // Invalid case, one extra lookup should be ok.
2382 continue;
2383 }
2384 std::swap(callbacks, local);
2385 }
2386
2387 processIfsStateCallbacks(storageId, local);
2388 }
2389
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002390 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002391 [this]() { processIfsStateCallbacks(); });
2392}
2393
2394void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2395 std::vector<IfsStateCallback>& callbacks) {
2396 const auto state = isMountFullyLoaded(storageId);
2397 IfsState storageState = {};
2398 storageState.error = int(state) < 0;
2399 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2400 if (storageState.fullyLoaded) {
2401 const auto ifs = getIfs(storageId);
2402 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2403 }
2404
2405 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2406 if ((*cur)(storageId, storageState)) {
2407 ++cur;
2408 } else {
2409 cur = callbacks.erase(cur);
2410 }
2411 }
2412}
2413
2414void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2415 std::lock_guard l(mIfsStateCallbacksLock);
2416 mIfsStateCallbacks.erase(storageId);
2417}
2418
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002419void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002420 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002421 if (!ifs) {
Songchun Fan9471be52021-04-21 17:49:27 -07002422 LOG(ERROR) << "getMetrics failed, invalid storageId: " << storageId;
2423 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002424 }
Songchun Fan9471be52021-04-21 17:49:27 -07002425 const auto kMetricsReadLogsEnabled =
2426 os::incremental::BnIncrementalService::METRICS_READ_LOGS_ENABLED();
2427 result->putBoolean(String16(kMetricsReadLogsEnabled.data()), ifs->readLogsEnabled() != 0);
2428
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002429 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002430 if (!ifs->dataLoaderStub) {
Songchun Fan9471be52021-04-21 17:49:27 -07002431 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002432 }
Songchun Fan9471be52021-04-21 17:49:27 -07002433 ifs->dataLoaderStub->getMetrics(result);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002434}
2435
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002436IncrementalService::DataLoaderStub::DataLoaderStub(
2437 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2438 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2439 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2440 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002441 : mService(service),
2442 mId(id),
2443 mParams(std::move(params)),
2444 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002445 mStatusListener(std::move(statusListener)),
2446 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002447 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002448 mHealthCheckParams(healthCheckParams) {
2449 if (mHealthListener && !isHealthParamsValid()) {
2450 mHealthListener = {};
2451 }
2452 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002453 // Disable advanced health check statuses.
2454 mHealthCheckParams.blockedTimeoutMs = -1;
2455 }
2456 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002457}
2458
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002459IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002460 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002461 cleanupResources();
2462 }
2463}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002464
2465void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002466 auto now = Clock::now();
2467 {
2468 std::unique_lock lock(mMutex);
2469 mHealthPath.clear();
2470 unregisterFromPendingReads();
2471 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002472 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002473 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002474 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002475
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002476 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002477
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002478 {
2479 std::unique_lock lock(mMutex);
2480 mParams = {};
2481 mControl = {};
2482 mHealthControl = {};
2483 mHealthListener = {};
2484 mStatusCondition.wait_until(lock, now + 60s, [this] {
2485 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2486 });
2487 mStatusListener = {};
2488 mId = kInvalidStorageId;
2489 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002490}
2491
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002492sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2493 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002494 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002495 if (!status.isOk()) {
2496 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2497 return {};
2498 }
2499 if (!dataloader) {
2500 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2501 return {};
2502 }
2503 return dataloader;
2504}
2505
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002506bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2507 return (params().packageName == Constants::systemPackage);
2508}
2509
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002510bool IncrementalService::DataLoaderStub::requestCreate() {
2511 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2512}
2513
2514bool IncrementalService::DataLoaderStub::requestStart() {
2515 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2516}
2517
2518bool IncrementalService::DataLoaderStub::requestDestroy() {
2519 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2520}
2521
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002522bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002523 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002524 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002525 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002526 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002527 return fsmStep();
2528}
2529
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002530void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002531 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002532 mTargetStatus = status;
2533 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002534 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002535 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002536}
2537
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002538std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002539 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002540
2541 const auto now = mService.mClock->now();
2542 const bool healthy = (mPreviousBindDelay == 0ms);
2543
2544 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2545 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2546 LOG(INFO) << "Binding still in progress. "
2547 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002548 : "Already unhealthy, don't do anything.")
2549 << " for storage " << mId;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002550 // Binding still in progress.
2551 if (!healthy) {
2552 // Already unhealthy, don't do anything.
2553 return {};
2554 }
2555 // The DL is healthy/freshly bound, ok to retry for a few times.
2556 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2557 // Still within grace period.
2558 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2559 // Retry interval passed, retrying.
2560 mCurrentStatusTs = now;
2561 mPreviousBindDelay = 0ms;
2562 return 0ms;
2563 }
2564 return {};
2565 }
2566 // fallthrough, mark as unhealthy, and retry with delay
2567 }
2568
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002569 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002570 mPreviousBindTs = now;
2571
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002572 const auto nonCrashingInterval =
2573 std::max(castToMs(now - previousBindTs - mPreviousBindDelay), 100ms);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002574 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2575 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2576 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002577 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002578 }
2579
2580 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2581 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2582
2583 const auto bindDelayMs =
2584 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2585 maxBindDelayMs)
2586 .count();
2587 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2588 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2589 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002590 return mPreviousBindDelay;
2591}
2592
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002593bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002594 const auto maybeBindDelay = needToBind();
2595 if (!maybeBindDelay) {
2596 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2597 return true;
2598 }
2599 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002600 if (bindDelay > 1s) {
2601 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002602 << bindDelay.count() / 1000 << "s"
2603 << " for storage " << mId;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002604 }
2605
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002606 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002607 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2608 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002609 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002610 const bool healthy = (bindDelay == 0ms);
2611 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2612 << (healthy ? ", retrying." : "");
2613
2614 // Internal error, retry for healthy/new DLs.
2615 // Let needToBind migrate it to unhealthy after too many retries.
2616 if (healthy) {
2617 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2618 [this]() { fsmStep(); })) {
2619 // Mark as binding so that we know it's not the DL's fault.
2620 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2621 return true;
2622 }
2623 }
2624
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002625 return false;
2626 }
2627 return true;
2628}
2629
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002630bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002631 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002632 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002633 return false;
2634 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002635 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002636 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002637 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002638 return false;
2639 }
2640 return true;
2641}
2642
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002643bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002644 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002645 if (!dataloader) {
2646 return false;
2647 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002648 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002649 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002650 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002651 return false;
2652 }
2653 return true;
2654}
2655
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002656bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002657 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002658}
2659
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002660bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002661 if (!isValid()) {
2662 return false;
2663 }
2664
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002665 int currentStatus;
2666 int targetStatus;
2667 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002668 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002669 currentStatus = mCurrentStatus;
2670 targetStatus = mTargetStatus;
2671 }
2672
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002673 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002674
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002675 if (currentStatus == targetStatus) {
2676 return true;
2677 }
2678
2679 switch (targetStatus) {
2680 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002681 switch (currentStatus) {
2682 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2683 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2684 return true;
2685 default:
2686 return destroy();
2687 }
2688 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002689 }
2690 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2691 switch (currentStatus) {
2692 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2693 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2694 return start();
2695 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002696 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002697 }
2698 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2699 switch (currentStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002700 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002701 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2702 // Before binding need to make sure we are unbound.
2703 // Otherwise we'll get stuck binding.
2704 return destroy();
2705 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002706 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002707 return bind();
2708 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002709 return create();
2710 }
2711 break;
2712 default:
2713 LOG(ERROR) << "Invalid target status: " << targetStatus
2714 << ", current status: " << currentStatus;
2715 break;
2716 }
2717 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002718}
2719
2720binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002721 if (!isValid()) {
2722 return binder::Status::
2723 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2724 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002725 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002726 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2727 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002728 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2729 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002730 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2731 newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002732 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2733 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2734 [this, newStatus]() { setCurrentStatus(newStatus); });
2735 return binder::Status::ok();
2736 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002737
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002738 setCurrentStatus(newStatus);
2739 return binder::Status::ok();
2740}
2741
2742void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002743 int oldStatus, oldTargetStatus, newTargetStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002744 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002745 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002746 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002747 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002748 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002749 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002750
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002751 oldStatus = mCurrentStatus;
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002752 oldTargetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002753 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002754
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002755 // Change the status.
2756 mCurrentStatus = newStatus;
2757 mCurrentStatusTs = mService.mClock->now();
2758
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002759 switch (mCurrentStatus) {
2760 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2761 // Unavailable, retry.
2762 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2763 break;
2764 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2765 // Unrecoverable, just unbind.
2766 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2767 break;
2768 default:
2769 break;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002770 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002771
2772 newTargetStatus = mTargetStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002773 }
2774
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002775 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002776 << newStatus << " (target " << oldTargetStatus << " -> " << newTargetStatus << ")";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002777
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002778 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002779 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002780 }
2781
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002782 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002783
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002784 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002785}
2786
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002787bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2788 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2789 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002790}
2791
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002792void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002793 int healthStatus) {
2794 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2795 if (healthListener) {
2796 healthListener->onHealthStatus(id(), healthStatus);
2797 }
Songchun Fan9471be52021-04-21 17:49:27 -07002798 mHealthStatus = healthStatus;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002799}
2800
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002801void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2802 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002803
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002804 int healthStatusToReport = -1;
2805 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002806
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002807 {
2808 std::unique_lock lock(mMutex);
2809 unregisterFromPendingReads();
2810
2811 healthListener = mHealthListener;
2812
2813 // Healthcheck depends on timestamp of the oldest pending read.
2814 // 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 -07002815 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2816 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002817 const auto now = Clock::now();
2818 const auto kernelTsUs = getOldestPendingReadTs();
2819 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002820 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2821 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002822 mHealthBase = {now, kernelTsUs};
2823 }
2824
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002825 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2826 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002827 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2828 registerForPendingReads();
2829 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2830 lock.unlock();
2831 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002832 return;
2833 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002834
2835 resetHealthControl();
2836
2837 // Always make sure the data loader is started.
2838 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2839
2840 // Skip any further processing if health check params are invalid.
2841 if (!isHealthParamsValid()) {
2842 LOG(DEBUG) << id()
2843 << ": Skip any further processing if health check params are invalid.";
2844 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2845 lock.unlock();
2846 onHealthStatus(healthListener, healthStatusToReport);
2847 // Triggering data loader start. This is a one-time action.
2848 fsmStep();
2849 return;
2850 }
2851
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002852 // Don't schedule timer job less than 500ms in advance.
2853 static constexpr auto kTolerance = 500ms;
2854
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002855 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2856 const auto unhealthyTimeout =
2857 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2858 const auto unhealthyMonitoring =
2859 std::max(1000ms,
2860 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2861
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002862 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002863
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002864 Milliseconds checkBackAfter;
2865 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002866 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002867 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002868 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002869 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002870 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002871 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002872 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2873 } else {
2874 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002875 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002876 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2877 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002878 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002879 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002880 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2881 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002882 }
2883
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002884 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002885 if (healthStatusToReport != -1) {
2886 onHealthStatus(healthListener, healthStatusToReport);
2887 }
2888
2889 fsmStep();
2890}
2891
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002892Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2893 BootClockTsUs kernelTsUs) {
2894 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2895 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2896 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2897}
2898
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002899const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2900 if (mHealthPath.empty()) {
2901 resetHealthControl();
2902 return mHealthControl;
2903 }
2904 if (mHealthControl.pendingReads() < 0) {
2905 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2906 }
2907 if (mHealthControl.pendingReads() < 0) {
2908 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2909 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2910 << mHealthControl.logs() << ")";
2911 }
2912 return mHealthControl;
2913}
2914
2915void IncrementalService::DataLoaderStub::resetHealthControl() {
2916 mHealthControl = {};
2917}
2918
2919BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2920 auto result = kMaxBootClockTsUs;
2921
2922 const auto& control = initializeHealthControl();
2923 if (control.pendingReads() < 0) {
2924 return result;
2925 }
2926
Songchun Fan6944f1e2020-11-06 15:24:24 -08002927 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002928 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002929 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002930 // Clear previous pending reads
2931 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002932 return result;
2933 }
2934
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07002935 LOG(DEBUG) << id() << ": pendingReads: fd(" << control.pendingReads() << "), count("
2936 << mLastPendingReads.size() << "), block: " << mLastPendingReads.front().block
2937 << ", time: " << mLastPendingReads.front().bootClockTsUs
2938 << ", uid: " << mLastPendingReads.front().uid;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002939
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002940 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002941}
2942
2943void IncrementalService::DataLoaderStub::registerForPendingReads() {
2944 const auto pendingReadsFd = mHealthControl.pendingReads();
2945 if (pendingReadsFd < 0) {
2946 return;
2947 }
2948
2949 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2950
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002951 mService.mLooper->addFd(
2952 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2953 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002954 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002955 self->updateHealthStatus(/*baseline=*/true);
2956 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002957 },
2958 this);
2959 mService.mLooper->wake();
2960}
2961
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002962BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2963 auto result = kMaxBootClockTsUs;
2964 for (auto&& pendingRead : mLastPendingReads) {
2965 result = std::min(result, pendingRead.bootClockTsUs);
2966 }
2967 return result;
2968}
2969
Songchun Fan9471be52021-04-21 17:49:27 -07002970void IncrementalService::DataLoaderStub::getMetrics(android::os::PersistableBundle* result) {
2971 const auto duration = elapsedMsSinceOldestPendingRead();
2972 if (duration >= 0) {
2973 const auto kMetricsMillisSinceOldestPendingRead =
2974 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2975 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2976 }
2977 const auto kMetricsStorageHealthStatusCode =
2978 os::incremental::BnIncrementalService::METRICS_STORAGE_HEALTH_STATUS_CODE();
2979 result->putInt(String16(kMetricsStorageHealthStatusCode.data()), mHealthStatus);
2980 const auto kMetricsDataLoaderStatusCode =
2981 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_STATUS_CODE();
2982 result->putInt(String16(kMetricsDataLoaderStatusCode.data()), mCurrentStatus);
2983 const auto kMetricsMillisSinceLastDataLoaderBind =
2984 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_DATA_LOADER_BIND();
2985 result->putLong(String16(kMetricsMillisSinceLastDataLoaderBind.data()),
2986 (long)(elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000));
2987 const auto kMetricsDataLoaderBindDelayMillis =
2988 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_BIND_DELAY_MILLIS();
2989 result->putLong(String16(kMetricsDataLoaderBindDelayMillis.data()),
2990 (long)(mPreviousBindDelay.count()));
2991}
2992
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002993long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
2994 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
2995 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
2996 return 0;
2997 }
2998 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
2999}
3000
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07003001void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003002 const auto pendingReadsFd = mHealthControl.pendingReads();
3003 if (pendingReadsFd < 0) {
3004 return;
3005 }
3006
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003007 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
3008
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003009 mService.mLooper->removeFd(pendingReadsFd);
3010 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003011}
3012
Songchun Fan2570ec02020-10-08 17:22:33 -07003013void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003014 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07003015 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003016 mHealthCheckParams = healthCheckParams;
3017 mHealthListener = std::move(healthListener);
3018 if (!mHealthListener) {
3019 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07003020 }
3021}
3022
Songchun Fan6944f1e2020-11-06 15:24:24 -08003023static std::string toHexString(const RawMetadata& metadata) {
3024 int n = metadata.size();
3025 std::string res(n * 2, '\0');
3026 // Same as incfs::toString(fileId)
3027 static constexpr char kHexChar[] = "0123456789abcdef";
3028 for (int i = 0; i < n; ++i) {
3029 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
3030 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
3031 }
3032 return res;
3033}
3034
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003035void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003036 dprintf(fd, " dataLoader: {\n");
3037 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08003038 dprintf(fd, " currentStatusTs: %lldmcs\n",
3039 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003040 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
3041 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003042 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003043 dprintf(fd, " health: {\n");
3044 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3045 dprintf(fd, " base: %lldmcs (%lld)\n",
3046 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3047 (long long)mHealthBase.kernelTsUs);
3048 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3049 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3050 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3051 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003052 dprintf(fd, " lastPendingReads: \n");
3053 const auto control = mService.mIncFs->openMount(mHealthPath);
3054 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003055 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003056 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3057 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3058 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3059 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3060 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003061 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
Songchun Fan9471be52021-04-21 17:49:27 -07003062 (long long)(elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000000),
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003063 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003064 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003065 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003066 dprintf(fd, " dataLoaderParams: {\n");
3067 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3068 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3069 dprintf(fd, " className: %s\n", params.className.c_str());
3070 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3071 dprintf(fd, " }\n");
3072 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003073}
3074
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003075void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3076 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003077}
3078
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003079binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3080 bool enableReadLogs, int32_t* _aidl_return) {
3081 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3082 return binder::Status::ok();
3083}
3084
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003085FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3086 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3087}
3088
Songchun Fan3c82a302019-11-29 14:23:45 -08003089} // namespace android::incremental