blob: 9b427994a404853c0717a39a28f01a05f966e909 [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());
414 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700415 dprintf(fd, " flags: %d\n", int(mnt.flags));
416 if (mnt.startLoadingTs.time_since_epoch() == Clock::duration::zero()) {
417 dprintf(fd, " not loading\n");
418 } else {
419 dprintf(fd, " startLoading: %llds\n",
420 (long long)(elapsedMcs(mnt.startLoadingTs, Clock::now()) / 1000000));
421 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700422 if (mnt.dataLoaderStub) {
423 mnt.dataLoaderStub->onDump(fd);
424 } else {
425 dprintf(fd, " dataLoader: null\n");
426 }
427 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
428 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700429 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700430 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800431 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700432 }
433 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800434
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700435 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
436 for (auto&& [target, bind] : mnt.bindPoints) {
437 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
438 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
439 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
440 dprintf(fd, " kind: %s\n", toString(bind.kind));
441 }
442 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800443 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700444 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800445 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700446 dprintf(fd, "}\n");
447 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800448 for (auto&& [target, mountPairIt] : mBindsByPath) {
449 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700450 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
451 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
452 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
453 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800454 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700455 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800456}
457
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800458bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700459 if (!ifs.dataLoaderStub) {
460 return false;
461 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700462 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800463 return true;
464 }
465
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700466 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800467}
468
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700469void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800470 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700471 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800472 }
473
474 std::vector<IfsMountPtr> mounts;
475 {
476 std::lock_guard l(mLock);
477 mounts.reserve(mMounts.size());
478 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700479 std::unique_lock ll(ifs->lock);
480
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800481 if (ifs->mountId != id) {
482 continue;
483 }
484
485 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800486 mounts.push_back(ifs);
487 }
488 }
489 }
490
Alex Buynytskyy69941662020-04-11 21:40:37 -0700491 if (mounts.empty()) {
492 return;
493 }
494
Songchun Fan3c82a302019-11-29 14:23:45 -0800495 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700496 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800497 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700498 std::unique_lock l(ifs->lock);
499 if (ifs->dataLoaderStub) {
500 ifs->dataLoaderStub->requestStart();
501 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800502 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800503 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800504}
505
506auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
507 for (;;) {
508 if (mNextId == kMaxStorageId) {
509 mNextId = 0;
510 }
511 auto id = ++mNextId;
512 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
513 if (inserted) {
514 return it;
515 }
516 }
517}
518
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700519StorageId IncrementalService::createStorage(std::string_view mountPoint,
520 content::pm::DataLoaderParamsParcel dataLoaderParams,
521 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800522 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
523 if (!path::isAbsolute(mountPoint)) {
524 LOG(ERROR) << "path is not absolute: " << mountPoint;
525 return kInvalidStorageId;
526 }
527
528 auto mountNorm = path::normalize(mountPoint);
529 {
530 const auto id = findStorageId(mountNorm);
531 if (id != kInvalidStorageId) {
532 if (options & CreateOptions::OpenExisting) {
533 LOG(INFO) << "Opened existing storage " << id;
534 return id;
535 }
536 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
537 return kInvalidStorageId;
538 }
539 }
540
541 if (!(options & CreateOptions::CreateNew)) {
542 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
543 return kInvalidStorageId;
544 }
545
546 if (!path::isEmptyDir(mountNorm)) {
547 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
548 return kInvalidStorageId;
549 }
550 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
551 if (mountRoot.empty()) {
552 LOG(ERROR) << "Bad mount point";
553 return kInvalidStorageId;
554 }
555 // Make sure the code removes all crap it may create while still failing.
556 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
557 auto firstCleanupOnFailure =
558 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
559
560 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800561 const auto backing = path::join(mountRoot, constants().backing);
562 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800563 return kInvalidStorageId;
564 }
565
Songchun Fan3c82a302019-11-29 14:23:45 -0800566 IncFsMount::Control control;
567 {
568 std::lock_guard l(mMountOperationLock);
569 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800570
571 if (auto err = rmDirContent(backing.c_str())) {
572 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
573 return kInvalidStorageId;
574 }
575 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
576 return kInvalidStorageId;
577 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800578 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
579 return kInvalidStorageId;
580 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800581 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800582 if (!status.isOk()) {
583 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
584 return kInvalidStorageId;
585 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800586 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
587 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800588 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
589 return kInvalidStorageId;
590 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800591 int cmd = controlParcel.cmd.release().release();
592 int pendingReads = controlParcel.pendingReads.release().release();
593 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800594 int blocksWritten =
595 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
596 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800597 }
598
599 std::unique_lock l(mLock);
600 const auto mountIt = getStorageSlotLocked();
601 const auto mountId = mountIt->first;
602 l.unlock();
603
604 auto ifs =
605 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
606 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
607 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700608 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800609
610 auto secondCleanup = [this, &l](auto itPtr) {
611 if (!l.owns_lock()) {
612 l.lock();
613 }
614 mMounts.erase(*itPtr);
615 };
616 auto secondCleanupOnFailure =
617 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
618
619 const auto storageIt = ifs->makeStorage(ifs->mountId);
620 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800621 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800622 return kInvalidStorageId;
623 }
624
625 {
626 metadata::Mount m;
627 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700628 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700629 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
630 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
631 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800632 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800633 if (auto err =
634 mIncFs->makeFile(ifs->control,
635 path::join(ifs->root, constants().mount,
636 constants().infoMdName),
637 0777, idFromMetadata(metadata),
638 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800639 LOG(ERROR) << "Saving mount metadata failed: " << -err;
640 return kInvalidStorageId;
641 }
642 }
643
644 const auto bk =
645 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800646 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
647 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800648 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800649 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800650 return kInvalidStorageId;
651 }
652
653 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700654 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800655
Songchun Fan3c82a302019-11-29 14:23:45 -0800656 mountIt->second = std::move(ifs);
657 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700658
Songchun Fan3c82a302019-11-29 14:23:45 -0800659 LOG(INFO) << "created storage " << mountId;
660 return mountId;
661}
662
663StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
664 StorageId linkedStorage,
665 IncrementalService::CreateOptions options) {
666 if (!isValidMountTarget(mountPoint)) {
667 LOG(ERROR) << "Mount point is invalid or missing";
668 return kInvalidStorageId;
669 }
670
671 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700672 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800673 if (!ifs) {
674 LOG(ERROR) << "Ifs unavailable";
675 return kInvalidStorageId;
676 }
677
678 const auto mountIt = getStorageSlotLocked();
679 const auto storageId = mountIt->first;
680 const auto storageIt = ifs->makeStorage(storageId);
681 if (storageIt == ifs->storages.end()) {
682 LOG(ERROR) << "Can't create a new storage";
683 mMounts.erase(mountIt);
684 return kInvalidStorageId;
685 }
686
687 l.unlock();
688
689 const auto bk =
690 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800691 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
692 std::string(storageIt->second.name), path::normalize(mountPoint),
693 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800694 err < 0) {
695 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700696 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
697 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800698 return kInvalidStorageId;
699 }
700
701 mountIt->second = ifs;
702 return storageId;
703}
704
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700705bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700706 content::pm::DataLoaderParamsParcel dataLoaderParams,
707 DataLoaderStatusListener statusListener,
708 const StorageHealthCheckParams& healthCheckParams,
709 StorageHealthListener healthListener,
710 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800711 // Per Uid timeouts.
712 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700713 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800714 }
715
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700716 IfsMountPtr ifs;
717 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800718
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700719 // Re-initialize DataLoader.
720 {
721 ifs = getIfs(storageId);
722 if (!ifs) {
723 return false;
724 }
725
726 std::unique_lock l(ifs->lock);
727 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
728 }
729
730 if (dataLoaderStub) {
731 dataLoaderStub->cleanupResources();
732 dataLoaderStub = {};
733 }
734
735 {
736 std::unique_lock l(ifs->lock);
737 if (ifs->dataLoaderStub) {
738 LOG(INFO) << "Skipped data loader stub creation because it already exists";
739 return false;
740 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700741
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700742 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
743 healthCheckParams, std::move(healthListener));
744 CHECK(ifs->dataLoaderStub);
745 dataLoaderStub = ifs->dataLoaderStub;
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700746
747 // Disable long read timeouts for non-system dataloaders.
748 // To be re-enabled after installation is complete.
749 ifs->setReadTimeoutsRequested(dataLoaderStub->isSystemDataLoader() &&
750 getAlwaysEnableReadTimeoutsForSystemDataLoaders());
751 applyStorageParamsLocked(*ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700752 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800753
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700754 if (dataLoaderStub->isSystemDataLoader() &&
755 !getEnforceReadLogsMaxIntervalForSystemDataLoaders()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700756 // Readlogs from system dataloader (adb) can always be collected.
757 ifs->startLoadingTs = TimePoint::max();
758 } else {
759 // Assign time when installation wants the DL to start streaming.
760 const auto startLoadingTs = mClock->now();
761 ifs->startLoadingTs = startLoadingTs;
762 // Setup a callback to disable the readlogs after max interval.
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700763 addTimedJob(*mTimedQueue, storageId, getReadLogsMaxInterval(),
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700764 [this, storageId, startLoadingTs]() {
765 const auto ifs = getIfs(storageId);
766 if (!ifs) {
767 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
768 << storageId;
769 return;
770 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700771 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700772 if (ifs->startLoadingTs != startLoadingTs) {
773 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
774 "installation?): "
775 << storageId;
776 return;
777 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700778 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700779 });
780 }
781
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800782 return dataLoaderStub->requestStart();
783}
784
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700785void IncrementalService::onInstallationComplete(StorageId storage) {
786 IfsMountPtr ifs = getIfs(storage);
787 if (!ifs) {
788 return;
789 }
790
791 // Always enable long read timeouts after installation is complete.
792 std::unique_lock l(ifs->lock);
793 ifs->setReadTimeoutsRequested(true);
794 applyStorageParamsLocked(*ifs);
795}
796
Songchun Fan3c82a302019-11-29 14:23:45 -0800797IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
798 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700799 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800800}
801
802StorageId IncrementalService::findStorageId(std::string_view path) const {
803 std::lock_guard l(mLock);
804 auto it = findStorageLocked(path);
805 if (it == mBindsByPath.end()) {
806 return kInvalidStorageId;
807 }
808 return it->second->second.storage;
809}
810
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800811void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700812 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700813 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800814 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700815 return;
816 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700817
818 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800819 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700820 return;
821 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800822 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700823
824 const auto metadata = constants().readLogsDisabledMarkerName;
825 if (auto err = mIncFs->makeFile(ifs->control,
826 path::join(ifs->root, constants().mount,
827 constants().readLogsDisabledMarkerName),
828 0777, idFromMetadata(metadata), {})) {
829 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
830 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
831 return;
832 }
833
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700834 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700835}
836
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700837int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
838 const auto ifs = getIfs(storageId);
839 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700840 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700841 return -EINVAL;
842 }
843
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700844 std::string packageName;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700845
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700846 {
847 std::unique_lock l(ifs->lock);
848 if (!enableReadLogs) {
849 return disableReadLogsLocked(*ifs);
850 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700851
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700852 if (!ifs->readLogsAllowed()) {
853 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
854 return -EPERM;
855 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700856
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700857 if (!ifs->dataLoaderStub) {
858 // This should never happen - only DL can call enableReadLogs.
859 LOG(ERROR) << "enableReadLogs failed: invalid state";
860 return -EPERM;
861 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700862
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700863 // Check installation time.
864 const auto now = mClock->now();
865 const auto startLoadingTs = ifs->startLoadingTs;
866 if (startLoadingTs <= now && now - startLoadingTs > getReadLogsMaxInterval()) {
867 LOG(ERROR)
868 << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
869 << storageId;
870 return -EPERM;
871 }
872
873 packageName = ifs->dataLoaderStub->params().packageName;
874 ifs->setReadLogsRequested(true);
875 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700876
877 // Check loader usage stats permission and apop.
878 if (auto status =
879 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
880 !status.isOk()) {
881 LOG(ERROR) << " Permission: " << kLoaderUsageStats
882 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700883 return fromBinderStatus(status);
884 }
885
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700886 // Check multiuser permission.
887 if (auto status =
888 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
889 !status.isOk()) {
890 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
891 << " check failed: " << status.toString8();
892 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700893 }
894
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700895 {
896 std::unique_lock l(ifs->lock);
897 if (!ifs->readLogsRequested()) {
898 return 0;
899 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700900 if (auto status = applyStorageParamsLocked(*ifs); status != 0) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700901 return status;
902 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700903 }
904
905 registerAppOpsCallback(packageName);
906
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700907 return 0;
908}
909
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700910int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700911 ifs.setReadLogsRequested(false);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700912 return applyStorageParamsLocked(ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700913}
914
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700915int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700916 os::incremental::IncrementalFileSystemControlParcel control;
917 control.cmd.reset(dup(ifs.control.cmd()));
918 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700919 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700920 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700921 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700922 }
923
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700924 bool enableReadLogs = ifs.readLogsRequested();
925 bool enableReadTimeouts = ifs.readTimeoutsRequested();
926
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700927 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700928 auto status = mVold->setIncFsMountOptions(control, enableReadLogs, enableReadTimeouts);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800929 if (status.isOk()) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700930 // Store states.
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800931 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700932 ifs.setReadTimeoutsEnabled(enableReadTimeouts);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700933 } else {
934 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800935 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700936 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700937}
938
Songchun Fan3c82a302019-11-29 14:23:45 -0800939void IncrementalService::deleteStorage(StorageId storageId) {
940 const auto ifs = getIfs(storageId);
941 if (!ifs) {
942 return;
943 }
944 deleteStorage(*ifs);
945}
946
947void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
948 std::unique_lock l(ifs.lock);
949 deleteStorageLocked(ifs, std::move(l));
950}
951
952void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
953 std::unique_lock<std::mutex>&& ifsLock) {
954 const auto storages = std::move(ifs.storages);
955 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
956 const auto bindPoints = ifs.bindPoints;
957 ifsLock.unlock();
958
959 std::lock_guard l(mLock);
960 for (auto&& [id, _] : storages) {
961 if (id != ifs.mountId) {
962 mMounts.erase(id);
963 }
964 }
965 for (auto&& [path, _] : bindPoints) {
966 mBindsByPath.erase(path);
967 }
968 mMounts.erase(ifs.mountId);
969}
970
971StorageId IncrementalService::openStorage(std::string_view pathInMount) {
972 if (!path::isAbsolute(pathInMount)) {
973 return kInvalidStorageId;
974 }
975
976 return findStorageId(path::normalize(pathInMount));
977}
978
Songchun Fan3c82a302019-11-29 14:23:45 -0800979IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
980 std::lock_guard l(mLock);
981 return getIfsLocked(storage);
982}
983
984const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
985 auto it = mMounts.find(storage);
986 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700987 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700988 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800989 }
990 return it->second;
991}
992
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800993int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
994 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800995 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700996 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800997 return -EINVAL;
998 }
999
1000 const auto ifs = getIfs(storage);
1001 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001002 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001003 return -EINVAL;
1004 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001005
Songchun Fan3c82a302019-11-29 14:23:45 -08001006 std::unique_lock l(ifs->lock);
1007 const auto storageInfo = ifs->storages.find(storage);
1008 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001009 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -08001010 return -EINVAL;
1011 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001012 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001013 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001014 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001015 return -EINVAL;
1016 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001017 l.unlock();
1018 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001019 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
1020 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -08001021}
1022
1023int IncrementalService::unbind(StorageId storage, std::string_view target) {
1024 if (!path::isAbsolute(target)) {
1025 return -EINVAL;
1026 }
1027
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001028 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001029
1030 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
1031 // otherwise there's a chance to unmount something completely unrelated
1032 const auto norm = path::normalize(target);
1033 std::unique_lock l(mLock);
1034 const auto storageIt = mBindsByPath.find(norm);
1035 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
1036 return -EINVAL;
1037 }
1038 const auto bindIt = storageIt->second;
1039 const auto storageId = bindIt->second.storage;
1040 const auto ifs = getIfsLocked(storageId);
1041 if (!ifs) {
1042 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
1043 << " is missing";
1044 return -EFAULT;
1045 }
1046 mBindsByPath.erase(storageIt);
1047 l.unlock();
1048
1049 mVold->unmountIncFs(bindIt->first);
1050 std::unique_lock l2(ifs->lock);
1051 if (ifs->bindPoints.size() <= 1) {
1052 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -07001053 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001054 } else {
1055 const std::string savedFile = std::move(bindIt->second.savedFilename);
1056 ifs->bindPoints.erase(bindIt);
1057 l2.unlock();
1058 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001059 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001060 }
1061 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001062
Songchun Fan3c82a302019-11-29 14:23:45 -08001063 return 0;
1064}
1065
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001066std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001067 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001068 std::string_view path) const {
1069 if (!path::isAbsolute(path)) {
1070 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001071 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001072 auto normPath = path::normalize(path);
1073 if (path::startsWith(normPath, storageIt->second.name)) {
1074 return normPath;
1075 }
1076 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001077 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1078 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001079 return {};
1080 }
1081 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001082}
1083
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001084std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001085 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001086 std::unique_lock l(ifs.lock);
1087 const auto storageInfo = ifs.storages.find(storage);
1088 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001089 return {};
1090 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001091 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001092}
1093
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001094int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001095 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001096 const auto ifs = getIfs(storage);
1097 if (!ifs) {
1098 return -EINVAL;
1099 }
1100 if (data.size() > params.size) {
1101 LOG(ERROR) << "Bad data size - bigger than file size";
1102 return -EINVAL;
1103 }
1104 if (!data.empty() && data.size() != params.size) {
1105 // Writing a page is an irreversible operation, and it can't be updated with additional
1106 // data later. Check that the last written page is complete, or we may break the file.
1107 if (!isPageAligned(data.size())) {
1108 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001109 return -EINVAL;
1110 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001111 }
1112 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1113 if (normPath.empty()) {
1114 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1115 return -EINVAL;
1116 }
1117 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1118 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1119 return err;
1120 }
1121 if (params.size > 0) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001122 if (auto err = mIncFs->reserveSpace(ifs->control, id, params.size)) {
1123 if (err != -EOPNOTSUPP) {
1124 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1125 (void)mIncFs->unlink(ifs->control, normPath);
1126 return err;
1127 } else {
1128 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1129 "may run out of disk later";
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001130 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001131 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001132 if (!data.empty()) {
1133 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001134 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001135 return err;
1136 }
1137 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001138 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001139 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001140}
1141
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001142int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001143 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001144 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001145 if (normPath.empty()) {
1146 return -EINVAL;
1147 }
1148 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001149 }
1150 return -EINVAL;
1151}
1152
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001153int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001154 const auto ifs = getIfs(storageId);
1155 if (!ifs) {
1156 return -EINVAL;
1157 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001158 return makeDirs(*ifs, storageId, path, mode);
1159}
1160
1161int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1162 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001163 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1164 if (normPath.empty()) {
1165 return -EINVAL;
1166 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001167 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001168}
1169
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001170int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1171 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001172 std::unique_lock l(mLock);
1173 auto ifsSrc = getIfsLocked(sourceStorageId);
1174 if (!ifsSrc) {
1175 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001176 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001177 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1178 return -EINVAL;
1179 }
1180 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001181 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1182 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001183 if (normOldPath.empty() || normNewPath.empty()) {
1184 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1185 return -EINVAL;
1186 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001187 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1188 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1189 << " to " << newPath << "[" << normNewPath << "]";
1190 return err;
1191 }
1192 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001193}
1194
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001195int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001196 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001197 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001198 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001199 }
1200 return -EINVAL;
1201}
1202
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001203int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1204 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001205 std::string&& target, BindKind kind,
1206 std::unique_lock<std::mutex>& mainLock) {
1207 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001208 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001209 return -EINVAL;
1210 }
1211
1212 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001213 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001214 if (kind != BindKind::Temporary) {
1215 metadata::BindPoint bp;
1216 bp.set_storage_id(storage);
1217 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001218 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001219 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001220 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001221 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001222 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001223 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1224 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1225 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001226 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001227 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001228 return int(node);
1229 }
1230 }
1231
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001232 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1233 std::move(target), kind, mainLock);
1234 if (res) {
1235 mIncFs->unlink(ifs.control, metadataFullPath);
1236 }
1237 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001238}
1239
1240int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001241 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001242 std::string&& target, BindKind kind,
1243 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001244 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001245 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001246 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001247 if (!status.isOk()) {
1248 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1249 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1250 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1251 : status.serviceSpecificErrorCode() == 0
1252 ? -EFAULT
1253 : status.serviceSpecificErrorCode()
1254 : -EIO;
1255 }
1256 }
1257
1258 if (!mainLock.owns_lock()) {
1259 mainLock.lock();
1260 }
1261 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001262 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1263 std::move(target), kind);
1264 return 0;
1265}
1266
1267void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1268 std::string&& metadataName, std::string&& source,
1269 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001270 const auto [it, _] =
1271 ifs.bindPoints.insert_or_assign(target,
1272 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001273 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001274 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001275}
1276
1277RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1278 const auto ifs = getIfs(storage);
1279 if (!ifs) {
1280 return {};
1281 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001282 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001283 if (normPath.empty()) {
1284 return {};
1285 }
1286 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001287}
1288
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001289RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001290 const auto ifs = getIfs(storage);
1291 if (!ifs) {
1292 return {};
1293 }
1294 return mIncFs->getMetadata(ifs->control, node);
1295}
1296
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001297void IncrementalService::setUidReadTimeouts(StorageId storage,
1298 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001299 using microseconds = std::chrono::microseconds;
1300 using milliseconds = std::chrono::milliseconds;
1301
1302 auto maxPendingTimeUs = microseconds(0);
1303 for (const auto& timeouts : perUidReadTimeouts) {
1304 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1305 }
1306 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07001307 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001308 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1309 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001310 return;
1311 }
1312
1313 const auto ifs = getIfs(storage);
1314 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001315 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001316 return;
1317 }
1318
1319 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1320 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1321 return;
1322 }
1323
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001324 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1325 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1326 if (checkUidReadTimeouts(storageId, state, timeout)) {
1327 return true;
1328 }
1329 clearUidReadTimeouts(storageId);
1330 return false;
1331 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001332}
1333
1334void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1335 const auto ifs = getIfs(storage);
1336 if (!ifs) {
1337 return;
1338 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001339 mIncFs->setUidReadTimeouts(ifs->control, {});
1340}
1341
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001342bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1343 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001344 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001345 // Reached maximum timeout.
1346 return false;
1347 }
1348 if (state.error) {
1349 // Something is wrong, abort.
1350 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001351 }
1352
1353 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001354 if (state.fullyLoaded && !state.readLogsEnabled) {
1355 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001356 }
1357
1358 const auto timeLeft = timeLimit - Clock::now();
1359 if (timeLeft < Constants::progressUpdateInterval) {
1360 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001361 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001362 }
1363
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001364 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001365}
1366
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001367std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1368 std::unordered_set<std::string_view> mountedRootNames;
1369 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1370 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1371 for (auto [source, target] : binds) {
1372 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1373 LOG(INFO) << " " << path::join(root, source);
1374 }
1375
1376 // Ensure it's a kind of a mount that's managed by IncrementalService
1377 if (path::basename(root) != constants().mount ||
1378 path::basename(backingDir) != constants().backing) {
1379 return;
1380 }
1381 const auto expectedRoot = path::dirname(root);
1382 if (path::dirname(backingDir) != expectedRoot) {
1383 return;
1384 }
1385 if (path::dirname(expectedRoot) != mIncrementalDir) {
1386 return;
1387 }
1388 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1389 return;
1390 }
1391
1392 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1393
1394 // make sure we clean up the mount if it happens to be a bad one.
1395 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1396 auto cleanupFiles = makeCleanup([&]() {
1397 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1398 IncFsMount::cleanupFilesystem(expectedRoot);
1399 });
1400 auto cleanupMounts = makeCleanup([&]() {
1401 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1402 for (auto&& [_, target] : binds) {
1403 mVold->unmountIncFs(std::string(target));
1404 }
1405 mVold->unmountIncFs(std::string(root));
1406 });
1407
1408 auto control = mIncFs->openMount(root);
1409 if (!control) {
1410 LOG(INFO) << "failed to open mount " << root;
1411 return;
1412 }
1413
1414 auto mountRecord =
1415 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1416 path::join(root, constants().infoMdName));
1417 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1418 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1419 return;
1420 }
1421
1422 auto mountId = mountRecord.storage().id();
1423 mNextId = std::max(mNextId, mountId + 1);
1424
1425 DataLoaderParamsParcel dataLoaderParams;
1426 {
1427 const auto& loader = mountRecord.loader();
1428 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1429 dataLoaderParams.packageName = loader.package_name();
1430 dataLoaderParams.className = loader.class_name();
1431 dataLoaderParams.arguments = loader.arguments();
1432 }
1433
1434 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1435 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001436 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001437
Alex Buynytskyy04035452020-06-06 20:15:58 -07001438 // Check if marker file present.
1439 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001440 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001441 }
1442
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001443 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1444 auto d = openDir(root);
1445 while (auto e = ::readdir(d.get())) {
1446 if (e->d_type == DT_REG) {
1447 auto name = std::string_view(e->d_name);
1448 if (name.starts_with(constants().mountpointMdPrefix)) {
1449 permanentBindPoints
1450 .emplace_back(name,
1451 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1452 ifs->control,
1453 path::join(root,
1454 name)));
1455 if (permanentBindPoints.back().second.dest_path().empty() ||
1456 permanentBindPoints.back().second.source_subdir().empty()) {
1457 permanentBindPoints.pop_back();
1458 mIncFs->unlink(ifs->control, path::join(root, name));
1459 } else {
1460 LOG(INFO) << "Permanent bind record: '"
1461 << permanentBindPoints.back().second.source_subdir() << "'->'"
1462 << permanentBindPoints.back().second.dest_path() << "'";
1463 }
1464 }
1465 } else if (e->d_type == DT_DIR) {
1466 if (e->d_name == "."sv || e->d_name == ".."sv) {
1467 continue;
1468 }
1469 auto name = std::string_view(e->d_name);
1470 if (name.starts_with(constants().storagePrefix)) {
1471 int storageId;
1472 const auto res =
1473 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1474 name.data() + name.size(), storageId);
1475 if (res.ec != std::errc{} || *res.ptr != '_') {
1476 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1477 << "' for mount " << expectedRoot;
1478 continue;
1479 }
1480 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1481 if (!inserted) {
1482 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1483 << " for mount " << expectedRoot;
1484 continue;
1485 }
1486 ifs->storages.insert_or_assign(storageId,
1487 IncFsMount::Storage{path::join(root, name)});
1488 mNextId = std::max(mNextId, storageId + 1);
1489 }
1490 }
1491 }
1492
1493 if (ifs->storages.empty()) {
1494 LOG(WARNING) << "No valid storages in mount " << root;
1495 return;
1496 }
1497
1498 // now match the mounted directories with what we expect to have in the metadata
1499 {
1500 std::unique_lock l(mLock, std::defer_lock);
1501 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1502 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1503 [&, bindRecord = bindRecord](auto&& bind) {
1504 return bind.second == bindRecord.dest_path() &&
1505 path::join(root, bind.first) ==
1506 bindRecord.source_subdir();
1507 });
1508 if (mountedIt != binds.end()) {
1509 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1510 << " to mount " << mountedIt->first;
1511 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1512 std::move(*bindRecord.mutable_source_subdir()),
1513 std::move(*bindRecord.mutable_dest_path()),
1514 BindKind::Permanent);
1515 if (mountedIt != binds.end() - 1) {
1516 std::iter_swap(mountedIt, binds.end() - 1);
1517 }
1518 binds = binds.first(binds.size() - 1);
1519 } else {
1520 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1521 << ", mounting";
1522 // doesn't exist - try mounting back
1523 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1524 std::move(*bindRecord.mutable_source_subdir()),
1525 std::move(*bindRecord.mutable_dest_path()),
1526 BindKind::Permanent, l)) {
1527 mIncFs->unlink(ifs->control, metadataFile);
1528 }
1529 }
1530 }
1531 }
1532
1533 // if anything stays in |binds| those are probably temporary binds; system restarted since
1534 // they were mounted - so let's unmount them all.
1535 for (auto&& [source, target] : binds) {
1536 if (source.empty()) {
1537 continue;
1538 }
1539 mVold->unmountIncFs(std::string(target));
1540 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001541 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001542
1543 if (ifs->bindPoints.empty()) {
1544 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1545 deleteStorage(*ifs);
1546 return;
1547 }
1548
1549 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1550 CHECK(ifs->dataLoaderStub);
1551
1552 mountedRootNames.insert(path::basename(ifs->root));
1553
1554 // not locking here at all: we're still in the constructor, no other calls can happen
1555 mMounts[ifs->mountId] = std::move(ifs);
1556 });
1557
1558 return mountedRootNames;
1559}
1560
1561void IncrementalService::mountExistingImages(
1562 const std::unordered_set<std::string_view>& mountedRootNames) {
1563 auto dir = openDir(mIncrementalDir);
1564 if (!dir) {
1565 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1566 return;
1567 }
1568 while (auto entry = ::readdir(dir.get())) {
1569 if (entry->d_type != DT_DIR) {
1570 continue;
1571 }
1572 std::string_view name = entry->d_name;
1573 if (!name.starts_with(constants().mountKeyPrefix)) {
1574 continue;
1575 }
1576 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001577 continue;
1578 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001579 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001580 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001581 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001582 }
1583 }
1584}
1585
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001586bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001587 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001588 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001589
Songchun Fan3c82a302019-11-29 14:23:45 -08001590 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001591 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001592 if (!status.isOk()) {
1593 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1594 return false;
1595 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001596
1597 int cmd = controlParcel.cmd.release().release();
1598 int pendingReads = controlParcel.pendingReads.release().release();
1599 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001600 int blocksWritten =
1601 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1602 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001603
1604 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1605
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001606 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1607 path::join(mountTarget, constants().infoMdName));
1608 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001609 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1610 return false;
1611 }
1612
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001613 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001614 mNextId = std::max(mNextId, ifs->mountId + 1);
1615
Alex Buynytskyy04035452020-06-06 20:15:58 -07001616 // Check if marker file present.
1617 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001618 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001619 }
1620
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001621 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001622 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001623 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001624 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001625 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001626 dataLoaderParams.packageName = loader.package_name();
1627 dataLoaderParams.className = loader.class_name();
1628 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001629 }
1630
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001631 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001632 CHECK(ifs->dataLoaderStub);
1633
Songchun Fan3c82a302019-11-29 14:23:45 -08001634 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001635 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001636 while (auto e = ::readdir(d.get())) {
1637 if (e->d_type == DT_REG) {
1638 auto name = std::string_view(e->d_name);
1639 if (name.starts_with(constants().mountpointMdPrefix)) {
1640 bindPoints.emplace_back(name,
1641 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1642 ifs->control,
1643 path::join(mountTarget,
1644 name)));
1645 if (bindPoints.back().second.dest_path().empty() ||
1646 bindPoints.back().second.source_subdir().empty()) {
1647 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001648 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001649 }
1650 }
1651 } else if (e->d_type == DT_DIR) {
1652 if (e->d_name == "."sv || e->d_name == ".."sv) {
1653 continue;
1654 }
1655 auto name = std::string_view(e->d_name);
1656 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001657 int storageId;
1658 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1659 name.data() + name.size(), storageId);
1660 if (res.ec != std::errc{} || *res.ptr != '_') {
1661 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1662 << root;
1663 continue;
1664 }
1665 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001666 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001667 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001668 << " for mount " << root;
1669 continue;
1670 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001671 ifs->storages.insert_or_assign(storageId,
1672 IncFsMount::Storage{
1673 path::join(root, constants().mount, name)});
1674 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001675 }
1676 }
1677 }
1678
1679 if (ifs->storages.empty()) {
1680 LOG(WARNING) << "No valid storages in mount " << root;
1681 return false;
1682 }
1683
1684 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001685 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001686 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001687 for (auto&& bp : bindPoints) {
1688 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1689 std::move(*bp.second.mutable_source_subdir()),
1690 std::move(*bp.second.mutable_dest_path()),
1691 BindKind::Permanent, l);
1692 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001693 }
1694
1695 if (bindCount == 0) {
1696 LOG(WARNING) << "No valid bind points for mount " << root;
1697 deleteStorage(*ifs);
1698 return false;
1699 }
1700
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001701 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001702 mMounts[ifs->mountId] = std::move(ifs);
1703 return true;
1704}
1705
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001706void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001707 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001708 while (mRunning.load(std::memory_order_relaxed)) {
1709 mLooper->pollAll(kTimeoutMsecs);
1710 }
1711}
1712
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001713void IncrementalService::trimReservedSpaceV1(const IncFsMount& ifs) {
1714 mIncFs->forEachFile(ifs.control, [this](auto&& control, auto&& fileId) {
1715 if (mIncFs->isFileFullyLoaded(control, fileId) == incfs::LoadingState::Full) {
1716 mIncFs->reserveSpace(control, fileId, -1);
1717 }
1718 return true;
1719 });
1720}
1721
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001722void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001723 DataLoaderStatusListener&& statusListener,
1724 const StorageHealthCheckParams& healthCheckParams,
1725 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001726 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001727 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001728 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1729 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1730 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001731 if (ifs.control.blocksWritten() >= 0) {
1732 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1733 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001734 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001735
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001736 ifs.dataLoaderStub =
1737 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001738 std::move(statusListener), healthCheckParams,
1739 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001740
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001741 // pre-v2 IncFS doesn't do automatic reserved space trimming - need to run it manually
1742 if (!(mIncFs->features() & incfs::Features::v2)) {
1743 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1744 if (!state.fullyLoaded) {
1745 return true;
1746 }
1747
1748 const auto ifs = getIfs(storageId);
1749 if (!ifs) {
1750 return false;
1751 }
1752 trimReservedSpaceV1(*ifs);
1753 return false;
1754 });
1755 }
1756
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001757 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1758 if (!state.fullyLoaded || state.readLogsEnabled) {
1759 return true;
1760 }
1761
1762 DataLoaderStubPtr dataLoaderStub;
1763 {
1764 const auto ifs = getIfs(storageId);
1765 if (!ifs) {
1766 return false;
1767 }
1768
1769 std::unique_lock l(ifs->lock);
1770 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1771 }
1772
1773 if (dataLoaderStub) {
1774 dataLoaderStub->cleanupResources();
1775 }
1776
1777 return false;
1778 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001779}
1780
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001781template <class Duration>
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001782static constexpr auto castToMs(Duration d) {
1783 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1784}
1785
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001786// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001787// Lib files should be placed next to the APK file in the following matter:
1788// Example:
1789// /path/to/base.apk
1790// /path/to/lib/arm/first.so
1791// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001792bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1793 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001794 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001795 auto start = Clock::now();
1796
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001797 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001798 if (!ifs) {
1799 LOG(ERROR) << "Invalid storage " << storage;
1800 return false;
1801 }
1802
Songchun Fanc8975312020-07-13 12:14:37 -07001803 const auto targetLibPathRelativeToStorage =
1804 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1805 libDirRelativePath);
1806
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001807 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001808 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1809 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001810 << " errno: " << res;
1811 return false;
1812 }
1813
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001814 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001815 ZipArchiveHandle zipFileHandle;
1816 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001817 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1818 return false;
1819 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001820
1821 // Need a shared pointer: will be passing it into all unpacking jobs.
1822 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001823 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001824 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001825 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001826 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1827 return false;
1828 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001829 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001830 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1831
1832 auto openZipTs = Clock::now();
1833
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001834 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1835 incfs::FileId sourceId;
1836 if (mapFiles) {
1837 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1838 if (!incfs::isValidFileId(sourceId)) {
1839 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1840 << "', mapping disabled";
1841 mapFiles = false;
1842 }
1843 }
1844
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001845 std::vector<Job> jobQueue;
1846 ZipEntry entry;
1847 std::string_view fileName;
1848 while (!Next(cookie, &entry, &fileName)) {
1849 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001850 continue;
1851 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001852
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001853 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001854 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001855
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001856 if (!extractNativeLibs) {
1857 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001858 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001859 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1860 return false;
1861 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001862 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001863 LOG(WARNING) << "Library " << fileName
1864 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1865 << entry.offset;
1866 return false;
1867 }
1868 continue;
1869 }
1870
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001871 auto startFileTs = Clock::now();
1872
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001873 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001874 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001875 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001876 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001877 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001878 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001879 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1880 << "; skipping extraction, spent "
1881 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1882 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001883 continue;
1884 }
1885
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001886 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1887 incfs::NewMappedFileParams mappedFileParams = {
1888 .sourceId = sourceId,
1889 .sourceOffset = entry.offset,
1890 .size = entry.uncompressed_length,
1891 };
1892
1893 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1894 mappedFileParams);
1895 res == 0) {
1896 if (perfLoggingEnabled()) {
1897 auto doneTs = Clock::now();
1898 LOG(INFO) << "incfs: Mapped " << libName << ": "
1899 << elapsedMcs(startFileTs, doneTs) << "mcs";
1900 }
1901 continue;
1902 } else {
1903 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1904 << "; falling back to full extraction";
1905 }
1906 }
1907
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001908 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001909 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001910 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001911 .signature = {},
1912 // Metadata of the new lib file is its relative path
1913 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1914 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001915 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001916 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001917 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001918 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001919 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001920 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001921 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001922
1923 auto makeFileTs = Clock::now();
1924
Songchun Fanafaf6e92020-03-18 14:12:20 -07001925 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001926 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001927 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001928 LOG(INFO) << "incfs: Extracted " << libName
1929 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001930 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001931 continue;
1932 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001933
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001934 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1935 libFileId, libPath = std::move(targetLibPath),
1936 makeFileTs]() mutable {
1937 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001938 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001939
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001940 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001941 auto prepareJobTs = Clock::now();
1942 LOG(INFO) << "incfs: Processed " << libName << ": "
1943 << elapsedMcs(startFileTs, prepareJobTs)
1944 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1945 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001946 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001947 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001948
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001949 auto processedTs = Clock::now();
1950
1951 if (!jobQueue.empty()) {
1952 {
1953 std::lock_guard lock(mJobMutex);
1954 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001955 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001956 if (existingJobs.empty()) {
1957 existingJobs = std::move(jobQueue);
1958 } else {
1959 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1960 std::move_iterator(jobQueue.end()));
1961 }
1962 }
1963 }
1964 mJobCondition.notify_all();
1965 }
1966
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001967 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001968 auto end = Clock::now();
1969 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1970 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1971 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001972 << " make files: " << elapsedMcs(openZipTs, processedTs)
1973 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001974 }
1975
1976 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001977}
1978
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001979void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1980 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001981 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001982 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001983 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001984 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001985 return;
1986 }
1987
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001988 auto startedTs = Clock::now();
1989
1990 // Write extracted data to new file
1991 // NOTE: don't zero-initialize memory, it may take a while for nothing
1992 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1993 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001994 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001995 return;
1996 }
1997
1998 auto extractFileTs = Clock::now();
1999
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002000 if (setFileContent(ifs, libFileId, debugLibPath,
2001 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002002 return;
2003 }
2004
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002005 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002006 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002007 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
2008 << entry.compressed_length << " -> " << entry.uncompressed_length
2009 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002010 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
2011 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002012 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002013 }
2014}
2015
2016bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002017 struct WaitPrinter {
2018 const Clock::time_point startTs = Clock::now();
2019 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002020 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002021 const auto endTs = Clock::now();
2022 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
2023 << elapsedMcs(startTs, endTs) << "mcs";
2024 }
2025 }
2026 } waitPrinter;
2027
2028 MountId mount;
2029 {
2030 auto ifs = getIfs(storage);
2031 if (!ifs) {
2032 return true;
2033 }
2034 mount = ifs->mountId;
2035 }
2036
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002037 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002038 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002039 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002040 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002041 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002042 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002043}
2044
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002045int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
2046 std::string_view debugFilePath,
2047 std::span<const uint8_t> data) const {
2048 auto startTs = Clock::now();
2049
2050 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2051 if (!writeFd.ok()) {
2052 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2053 << " errno: " << writeFd.get();
2054 return writeFd.get();
2055 }
2056
2057 const auto dataLength = data.size();
2058
2059 auto openFileTs = Clock::now();
2060 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2061 std::vector<IncFsDataBlock> instructions(numBlocks);
2062 for (int i = 0; i < numBlocks; i++) {
2063 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2064 instructions[i] = IncFsDataBlock{
2065 .fileFd = writeFd.get(),
2066 .pageIndex = static_cast<IncFsBlockIndex>(i),
2067 .compression = INCFS_COMPRESSION_KIND_NONE,
2068 .kind = INCFS_BLOCK_KIND_DATA,
2069 .dataSize = static_cast<uint32_t>(blockSize),
2070 .data = reinterpret_cast<const char*>(data.data()),
2071 };
2072 data = data.subspan(blockSize);
2073 }
2074 auto prepareInstsTs = Clock::now();
2075
2076 size_t res = mIncFs->writeBlocks(instructions);
2077 if (res != instructions.size()) {
2078 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2079 return res;
2080 }
2081
2082 if (perfLoggingEnabled()) {
2083 auto endTs = Clock::now();
2084 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2085 << " bytes): " << elapsedMcs(startTs, endTs)
2086 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2087 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2088 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2089 }
2090
2091 return 0;
2092}
2093
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002094incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2095 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002096 std::unique_lock l(mLock);
2097 const auto ifs = getIfsLocked(storage);
2098 if (!ifs) {
2099 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002100 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002101 }
2102 const auto storageInfo = ifs->storages.find(storage);
2103 if (storageInfo == ifs->storages.end()) {
2104 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002105 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002106 }
2107 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002108 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002109}
2110
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002111incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2112 const auto ifs = getIfs(storage);
2113 if (!ifs) {
2114 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2115 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002116 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002117 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002118}
2119
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002120IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002121 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002122 std::unique_lock l(mLock);
2123 const auto ifs = getIfsLocked(storage);
2124 if (!ifs) {
2125 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002126 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002127 }
2128 const auto storageInfo = ifs->storages.find(storage);
2129 if (storageInfo == ifs->storages.end()) {
2130 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002131 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002132 }
2133 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002134 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002135}
2136
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002137IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002138 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002139 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2140 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002141 const auto [filledBlocksCount, totalBlocksCount] =
2142 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002143 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2144 filledBlocksCount == -ENOENT) {
2145 // a kind of a file that's not really being loaded, e.g. a mapped range
2146 // an older IncFS used to return ENOENT in this case, so handle it the same way
2147 return true;
2148 }
Songchun Fan374f7652020-08-20 08:40:29 -07002149 if (filledBlocksCount < 0) {
2150 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002151 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002152 error = filledBlocksCount;
2153 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002154 }
2155 totalBlocks += totalBlocksCount;
2156 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002157 return true;
2158 });
Songchun Fan374f7652020-08-20 08:40:29 -07002159
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002160 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002161}
2162
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002163bool IncrementalService::updateLoadingProgress(StorageId storage,
2164 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002165 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002166 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002167 // Failed to get progress from incfs, abort.
2168 return false;
2169 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002170 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2171 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002172 // Stop updating progress once it is fully loaded
2173 return true;
2174 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002175 addTimedJob(*mProgressUpdateJobQueue, storage,
2176 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002177 [storage, progressListener = std::move(progressListener), this]() mutable {
2178 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002179 });
2180 return true;
2181}
2182
2183bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002184 StorageId storage, StorageLoadingProgressListener progressListener) {
2185 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002186}
2187
2188bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2189 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2190}
2191
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002192bool IncrementalService::perfLoggingEnabled() {
2193 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2194 return enabled;
2195}
2196
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002197void IncrementalService::runJobProcessing() {
2198 for (;;) {
2199 std::unique_lock lock(mJobMutex);
2200 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2201 if (!mRunning) {
2202 return;
2203 }
2204
2205 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002206 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002207 auto queue = std::move(it->second);
2208 mJobQueue.erase(it);
2209 lock.unlock();
2210
2211 for (auto&& job : queue) {
2212 job();
2213 }
2214
2215 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002216 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002217 lock.unlock();
2218 mJobCondition.notify_all();
2219 }
2220}
2221
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002222void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002223 sp<IAppOpsCallback> listener;
2224 {
2225 std::unique_lock lock{mCallbacksLock};
2226 auto& cb = mCallbackRegistered[packageName];
2227 if (cb) {
2228 return;
2229 }
2230 cb = new AppOpsListener(*this, packageName);
2231 listener = cb;
2232 }
2233
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002234 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2235 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002236}
2237
2238bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2239 sp<IAppOpsCallback> listener;
2240 {
2241 std::unique_lock lock{mCallbacksLock};
2242 auto found = mCallbackRegistered.find(packageName);
2243 if (found == mCallbackRegistered.end()) {
2244 return false;
2245 }
2246 listener = found->second;
2247 mCallbackRegistered.erase(found);
2248 }
2249
2250 mAppOpsManager->stopWatchingMode(listener);
2251 return true;
2252}
2253
2254void IncrementalService::onAppOpChanged(const std::string& packageName) {
2255 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002256 return;
2257 }
2258
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002259 std::vector<IfsMountPtr> affected;
2260 {
2261 std::lock_guard l(mLock);
2262 affected.reserve(mMounts.size());
2263 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002264 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002265 if (ifs->mountId == id && ifs->dataLoaderStub &&
2266 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002267 affected.push_back(ifs);
2268 }
2269 }
2270 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002271 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002272 std::unique_lock ll(ifs->lock);
2273 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002274 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002275}
2276
Songchun Fana7098592020-09-03 11:45:53 -07002277bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2278 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002279 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002280 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002281 }
Songchun Fana7098592020-09-03 11:45:53 -07002282 timedQueue.addJob(id, after, std::move(what));
2283 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002284}
2285
Songchun Fana7098592020-09-03 11:45:53 -07002286bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002287 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002288 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002289 }
Songchun Fana7098592020-09-03 11:45:53 -07002290 timedQueue.removeJobs(id);
2291 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002292}
2293
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002294void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2295 bool wasEmpty;
2296 {
2297 std::lock_guard l(mIfsStateCallbacksLock);
2298 wasEmpty = mIfsStateCallbacks.empty();
2299 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2300 }
2301 if (wasEmpty) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002302 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002303 [this]() { processIfsStateCallbacks(); });
2304 }
2305}
2306
2307void IncrementalService::processIfsStateCallbacks() {
2308 StorageId storageId = kInvalidStorageId;
2309 std::vector<IfsStateCallback> local;
2310 while (true) {
2311 {
2312 std::lock_guard l(mIfsStateCallbacksLock);
2313 if (mIfsStateCallbacks.empty()) {
2314 return;
2315 }
2316 IfsStateCallbacks::iterator it;
2317 if (storageId == kInvalidStorageId) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002318 // First entry, initialize the |it|.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002319 it = mIfsStateCallbacks.begin();
2320 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002321 // Subsequent entries, update the |storageId|, and shift to the new one (not that
2322 // it guarantees much about updated items, but at least the loop will finish).
2323 it = mIfsStateCallbacks.lower_bound(storageId);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002324 if (it == mIfsStateCallbacks.end()) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002325 // Nothing else left, too bad.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002326 break;
2327 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002328 if (it->first != storageId) {
2329 local.clear(); // Was removed during processing, forget the old callbacks.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002330 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002331 // Put the 'surviving' callbacks back into the map and advance the position.
2332 auto& callbacks = it->second;
2333 if (callbacks.empty()) {
2334 std::swap(callbacks, local);
2335 } else {
2336 callbacks.insert(callbacks.end(), std::move_iterator(local.begin()),
2337 std::move_iterator(local.end()));
2338 local.clear();
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002339 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002340 if (callbacks.empty()) {
2341 it = mIfsStateCallbacks.erase(it);
2342 if (mIfsStateCallbacks.empty()) {
2343 return;
2344 }
2345 } else {
2346 ++it;
2347 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002348 }
2349 }
2350
2351 if (it == mIfsStateCallbacks.end()) {
2352 break;
2353 }
2354
2355 storageId = it->first;
2356 auto& callbacks = it->second;
2357 if (callbacks.empty()) {
2358 // Invalid case, one extra lookup should be ok.
2359 continue;
2360 }
2361 std::swap(callbacks, local);
2362 }
2363
2364 processIfsStateCallbacks(storageId, local);
2365 }
2366
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002367 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002368 [this]() { processIfsStateCallbacks(); });
2369}
2370
2371void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2372 std::vector<IfsStateCallback>& callbacks) {
2373 const auto state = isMountFullyLoaded(storageId);
2374 IfsState storageState = {};
2375 storageState.error = int(state) < 0;
2376 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2377 if (storageState.fullyLoaded) {
2378 const auto ifs = getIfs(storageId);
2379 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2380 }
2381
2382 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2383 if ((*cur)(storageId, storageState)) {
2384 ++cur;
2385 } else {
2386 cur = callbacks.erase(cur);
2387 }
2388 }
2389}
2390
2391void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2392 std::lock_guard l(mIfsStateCallbacksLock);
2393 mIfsStateCallbacks.erase(storageId);
2394}
2395
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002396void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
2397 const auto duration = getMillsSinceOldestPendingRead(storageId);
2398 if (duration >= 0) {
2399 const auto kMetricsMillisSinceOldestPendingRead =
2400 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2401 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2402 }
2403}
2404
2405long IncrementalService::getMillsSinceOldestPendingRead(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002406 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002407 if (!ifs) {
2408 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, invalid storageId: " << storageId;
2409 return -EINVAL;
2410 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002411 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002412 if (!ifs->dataLoaderStub) {
2413 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, no data loader: " << storageId;
2414 return -EINVAL;
2415 }
2416 return ifs->dataLoaderStub->elapsedMsSinceOldestPendingRead();
2417}
2418
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002419IncrementalService::DataLoaderStub::DataLoaderStub(
2420 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2421 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2422 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2423 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002424 : mService(service),
2425 mId(id),
2426 mParams(std::move(params)),
2427 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002428 mStatusListener(std::move(statusListener)),
2429 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002430 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002431 mHealthCheckParams(healthCheckParams) {
2432 if (mHealthListener && !isHealthParamsValid()) {
2433 mHealthListener = {};
2434 }
2435 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002436 // Disable advanced health check statuses.
2437 mHealthCheckParams.blockedTimeoutMs = -1;
2438 }
2439 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002440}
2441
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002442IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002443 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002444 cleanupResources();
2445 }
2446}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002447
2448void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002449 auto now = Clock::now();
2450 {
2451 std::unique_lock lock(mMutex);
2452 mHealthPath.clear();
2453 unregisterFromPendingReads();
2454 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002455 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002456 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002457 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002458
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002459 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002460
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002461 {
2462 std::unique_lock lock(mMutex);
2463 mParams = {};
2464 mControl = {};
2465 mHealthControl = {};
2466 mHealthListener = {};
2467 mStatusCondition.wait_until(lock, now + 60s, [this] {
2468 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2469 });
2470 mStatusListener = {};
2471 mId = kInvalidStorageId;
2472 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002473}
2474
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002475sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2476 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002477 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002478 if (!status.isOk()) {
2479 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2480 return {};
2481 }
2482 if (!dataloader) {
2483 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2484 return {};
2485 }
2486 return dataloader;
2487}
2488
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002489bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2490 return (params().packageName == Constants::systemPackage);
2491}
2492
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002493bool IncrementalService::DataLoaderStub::requestCreate() {
2494 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2495}
2496
2497bool IncrementalService::DataLoaderStub::requestStart() {
2498 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2499}
2500
2501bool IncrementalService::DataLoaderStub::requestDestroy() {
2502 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2503}
2504
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002505bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002506 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002507 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002508 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002509 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002510 return fsmStep();
2511}
2512
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002513void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002514 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002515 mTargetStatus = status;
2516 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002517 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002518 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002519}
2520
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002521std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002522 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002523
2524 const auto now = mService.mClock->now();
2525 const bool healthy = (mPreviousBindDelay == 0ms);
2526
2527 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2528 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2529 LOG(INFO) << "Binding still in progress. "
2530 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002531 : "Already unhealthy, don't do anything.")
2532 << " for storage " << mId;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002533 // Binding still in progress.
2534 if (!healthy) {
2535 // Already unhealthy, don't do anything.
2536 return {};
2537 }
2538 // The DL is healthy/freshly bound, ok to retry for a few times.
2539 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2540 // Still within grace period.
2541 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2542 // Retry interval passed, retrying.
2543 mCurrentStatusTs = now;
2544 mPreviousBindDelay = 0ms;
2545 return 0ms;
2546 }
2547 return {};
2548 }
2549 // fallthrough, mark as unhealthy, and retry with delay
2550 }
2551
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002552 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002553 mPreviousBindTs = now;
2554
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002555 const auto nonCrashingInterval =
2556 std::max(castToMs(now - previousBindTs - mPreviousBindDelay), 100ms);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002557 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2558 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2559 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002560 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002561 }
2562
2563 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2564 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2565
2566 const auto bindDelayMs =
2567 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2568 maxBindDelayMs)
2569 .count();
2570 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2571 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2572 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002573 return mPreviousBindDelay;
2574}
2575
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002576bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002577 const auto maybeBindDelay = needToBind();
2578 if (!maybeBindDelay) {
2579 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2580 return true;
2581 }
2582 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002583 if (bindDelay > 1s) {
2584 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002585 << bindDelay.count() / 1000 << "s"
2586 << " for storage " << mId;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002587 }
2588
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002589 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002590 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2591 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002592 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002593 const bool healthy = (bindDelay == 0ms);
2594 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2595 << (healthy ? ", retrying." : "");
2596
2597 // Internal error, retry for healthy/new DLs.
2598 // Let needToBind migrate it to unhealthy after too many retries.
2599 if (healthy) {
2600 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2601 [this]() { fsmStep(); })) {
2602 // Mark as binding so that we know it's not the DL's fault.
2603 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2604 return true;
2605 }
2606 }
2607
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002608 return false;
2609 }
2610 return true;
2611}
2612
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002613bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002614 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002615 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002616 return false;
2617 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002618 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002619 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002620 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002621 return false;
2622 }
2623 return true;
2624}
2625
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002626bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002627 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002628 if (!dataloader) {
2629 return false;
2630 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002631 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002632 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002633 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002634 return false;
2635 }
2636 return true;
2637}
2638
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002639bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002640 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002641}
2642
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002643bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002644 if (!isValid()) {
2645 return false;
2646 }
2647
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002648 int currentStatus;
2649 int targetStatus;
2650 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002651 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002652 currentStatus = mCurrentStatus;
2653 targetStatus = mTargetStatus;
2654 }
2655
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002656 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002657
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002658 if (currentStatus == targetStatus) {
2659 return true;
2660 }
2661
2662 switch (targetStatus) {
2663 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002664 switch (currentStatus) {
2665 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2666 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2667 return true;
2668 default:
2669 return destroy();
2670 }
2671 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002672 }
2673 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2674 switch (currentStatus) {
2675 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2676 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2677 return start();
2678 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002679 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002680 }
2681 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2682 switch (currentStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002683 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002684 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2685 // Before binding need to make sure we are unbound.
2686 // Otherwise we'll get stuck binding.
2687 return destroy();
2688 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002689 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002690 return bind();
2691 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002692 return create();
2693 }
2694 break;
2695 default:
2696 LOG(ERROR) << "Invalid target status: " << targetStatus
2697 << ", current status: " << currentStatus;
2698 break;
2699 }
2700 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002701}
2702
2703binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002704 if (!isValid()) {
2705 return binder::Status::
2706 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2707 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002708 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002709 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2710 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002711 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2712 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002713 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2714 newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002715 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2716 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2717 [this, newStatus]() { setCurrentStatus(newStatus); });
2718 return binder::Status::ok();
2719 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002720
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002721 setCurrentStatus(newStatus);
2722 return binder::Status::ok();
2723}
2724
2725void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002726 int oldStatus, oldTargetStatus, newTargetStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002727 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002728 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002729 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002730 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002731 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002732 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002733
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002734 oldStatus = mCurrentStatus;
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002735 oldTargetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002736 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002737
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002738 // Change the status.
2739 mCurrentStatus = newStatus;
2740 mCurrentStatusTs = mService.mClock->now();
2741
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002742 switch (mCurrentStatus) {
2743 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2744 // Unavailable, retry.
2745 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2746 break;
2747 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2748 // Unrecoverable, just unbind.
2749 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2750 break;
2751 default:
2752 break;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002753 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002754
2755 newTargetStatus = mTargetStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002756 }
2757
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002758 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002759 << newStatus << " (target " << oldTargetStatus << " -> " << newTargetStatus << ")";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002760
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002761 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002762 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002763 }
2764
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002765 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002766
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002767 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002768}
2769
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002770bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2771 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2772 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002773}
2774
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002775void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002776 int healthStatus) {
2777 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2778 if (healthListener) {
2779 healthListener->onHealthStatus(id(), healthStatus);
2780 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002781}
2782
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002783void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2784 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002785
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002786 int healthStatusToReport = -1;
2787 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002788
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002789 {
2790 std::unique_lock lock(mMutex);
2791 unregisterFromPendingReads();
2792
2793 healthListener = mHealthListener;
2794
2795 // Healthcheck depends on timestamp of the oldest pending read.
2796 // 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 -07002797 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2798 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002799 const auto now = Clock::now();
2800 const auto kernelTsUs = getOldestPendingReadTs();
2801 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002802 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2803 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002804 mHealthBase = {now, kernelTsUs};
2805 }
2806
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002807 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2808 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002809 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2810 registerForPendingReads();
2811 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2812 lock.unlock();
2813 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002814 return;
2815 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002816
2817 resetHealthControl();
2818
2819 // Always make sure the data loader is started.
2820 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2821
2822 // Skip any further processing if health check params are invalid.
2823 if (!isHealthParamsValid()) {
2824 LOG(DEBUG) << id()
2825 << ": Skip any further processing if health check params are invalid.";
2826 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2827 lock.unlock();
2828 onHealthStatus(healthListener, healthStatusToReport);
2829 // Triggering data loader start. This is a one-time action.
2830 fsmStep();
2831 return;
2832 }
2833
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002834 // Don't schedule timer job less than 500ms in advance.
2835 static constexpr auto kTolerance = 500ms;
2836
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002837 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2838 const auto unhealthyTimeout =
2839 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2840 const auto unhealthyMonitoring =
2841 std::max(1000ms,
2842 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2843
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002844 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002845
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002846 Milliseconds checkBackAfter;
2847 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002848 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002849 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002850 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002851 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002852 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002853 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002854 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2855 } else {
2856 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002857 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002858 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2859 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002860 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002861 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002862 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2863 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002864 }
2865
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002866 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002867 if (healthStatusToReport != -1) {
2868 onHealthStatus(healthListener, healthStatusToReport);
2869 }
2870
2871 fsmStep();
2872}
2873
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002874Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2875 BootClockTsUs kernelTsUs) {
2876 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2877 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2878 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2879}
2880
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002881const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2882 if (mHealthPath.empty()) {
2883 resetHealthControl();
2884 return mHealthControl;
2885 }
2886 if (mHealthControl.pendingReads() < 0) {
2887 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2888 }
2889 if (mHealthControl.pendingReads() < 0) {
2890 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2891 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2892 << mHealthControl.logs() << ")";
2893 }
2894 return mHealthControl;
2895}
2896
2897void IncrementalService::DataLoaderStub::resetHealthControl() {
2898 mHealthControl = {};
2899}
2900
2901BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2902 auto result = kMaxBootClockTsUs;
2903
2904 const auto& control = initializeHealthControl();
2905 if (control.pendingReads() < 0) {
2906 return result;
2907 }
2908
Songchun Fan6944f1e2020-11-06 15:24:24 -08002909 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002910 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002911 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002912 // Clear previous pending reads
2913 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002914 return result;
2915 }
2916
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07002917 LOG(DEBUG) << id() << ": pendingReads: fd(" << control.pendingReads() << "), count("
2918 << mLastPendingReads.size() << "), block: " << mLastPendingReads.front().block
2919 << ", time: " << mLastPendingReads.front().bootClockTsUs
2920 << ", uid: " << mLastPendingReads.front().uid;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002921
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002922 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002923}
2924
2925void IncrementalService::DataLoaderStub::registerForPendingReads() {
2926 const auto pendingReadsFd = mHealthControl.pendingReads();
2927 if (pendingReadsFd < 0) {
2928 return;
2929 }
2930
2931 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2932
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002933 mService.mLooper->addFd(
2934 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2935 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002936 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002937 self->updateHealthStatus(/*baseline=*/true);
2938 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002939 },
2940 this);
2941 mService.mLooper->wake();
2942}
2943
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002944BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2945 auto result = kMaxBootClockTsUs;
2946 for (auto&& pendingRead : mLastPendingReads) {
2947 result = std::min(result, pendingRead.bootClockTsUs);
2948 }
2949 return result;
2950}
2951
2952long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
2953 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
2954 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
2955 return 0;
2956 }
2957 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
2958}
2959
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002960void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002961 const auto pendingReadsFd = mHealthControl.pendingReads();
2962 if (pendingReadsFd < 0) {
2963 return;
2964 }
2965
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002966 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2967
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002968 mService.mLooper->removeFd(pendingReadsFd);
2969 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002970}
2971
Songchun Fan2570ec02020-10-08 17:22:33 -07002972void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002973 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002974 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002975 mHealthCheckParams = healthCheckParams;
2976 mHealthListener = std::move(healthListener);
2977 if (!mHealthListener) {
2978 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07002979 }
2980}
2981
Songchun Fan6944f1e2020-11-06 15:24:24 -08002982static std::string toHexString(const RawMetadata& metadata) {
2983 int n = metadata.size();
2984 std::string res(n * 2, '\0');
2985 // Same as incfs::toString(fileId)
2986 static constexpr char kHexChar[] = "0123456789abcdef";
2987 for (int i = 0; i < n; ++i) {
2988 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
2989 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
2990 }
2991 return res;
2992}
2993
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002994void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002995 dprintf(fd, " dataLoader: {\n");
2996 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002997 dprintf(fd, " currentStatusTs: %lldmcs\n",
2998 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002999 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
3000 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003001 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003002 dprintf(fd, " health: {\n");
3003 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3004 dprintf(fd, " base: %lldmcs (%lld)\n",
3005 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3006 (long long)mHealthBase.kernelTsUs);
3007 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3008 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3009 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3010 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003011 dprintf(fd, " lastPendingReads: \n");
3012 const auto control = mService.mIncFs->openMount(mHealthPath);
3013 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003014 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003015 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3016 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3017 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3018 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3019 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003020 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
3021 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
3022 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003023 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003024 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003025 dprintf(fd, " dataLoaderParams: {\n");
3026 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3027 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3028 dprintf(fd, " className: %s\n", params.className.c_str());
3029 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3030 dprintf(fd, " }\n");
3031 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003032}
3033
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003034void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3035 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003036}
3037
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003038binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3039 bool enableReadLogs, int32_t* _aidl_return) {
3040 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3041 return binder::Status::ok();
3042}
3043
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003044FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3045 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3046}
3047
Songchun Fan3c82a302019-11-29 14:23:45 -08003048} // namespace android::incremental