blob: 388f9329829d8b40b21ed114d30750661b7e193a [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
393void IncrementalService::onDump(int fd) {
394 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
395 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
396
397 std::unique_lock l(mLock);
398
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700399 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800400 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700401 std::unique_lock ll(ifs->lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700402 const IncFsMount& mnt = *ifs;
403 dprintf(fd, " [%d]: {\n", id);
404 if (id != mnt.mountId) {
405 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
406 } else {
407 dprintf(fd, " mountId: %d\n", mnt.mountId);
408 dprintf(fd, " root: %s\n", mnt.root.c_str());
409 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
410 if (mnt.dataLoaderStub) {
411 mnt.dataLoaderStub->onDump(fd);
412 } else {
413 dprintf(fd, " dataLoader: null\n");
414 }
415 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
416 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700417 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700418 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800419 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700420 }
421 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800422
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700423 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
424 for (auto&& [target, bind] : mnt.bindPoints) {
425 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
426 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
427 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
428 dprintf(fd, " kind: %s\n", toString(bind.kind));
429 }
430 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800431 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700432 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800433 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700434 dprintf(fd, "}\n");
435 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800436 for (auto&& [target, mountPairIt] : mBindsByPath) {
437 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700438 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
439 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
440 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
441 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800442 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700443 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800444}
445
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800446bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700447 if (!ifs.dataLoaderStub) {
448 return false;
449 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700450 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800451 return true;
452 }
453
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700454 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800455}
456
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700457void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800458 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700459 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800460 }
461
462 std::vector<IfsMountPtr> mounts;
463 {
464 std::lock_guard l(mLock);
465 mounts.reserve(mMounts.size());
466 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700467 std::unique_lock ll(ifs->lock);
468
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800469 if (ifs->mountId != id) {
470 continue;
471 }
472
473 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800474 mounts.push_back(ifs);
475 }
476 }
477 }
478
Alex Buynytskyy69941662020-04-11 21:40:37 -0700479 if (mounts.empty()) {
480 return;
481 }
482
Songchun Fan3c82a302019-11-29 14:23:45 -0800483 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700484 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800485 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700486 std::unique_lock l(ifs->lock);
487 if (ifs->dataLoaderStub) {
488 ifs->dataLoaderStub->requestStart();
489 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800490 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800491 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800492}
493
494auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
495 for (;;) {
496 if (mNextId == kMaxStorageId) {
497 mNextId = 0;
498 }
499 auto id = ++mNextId;
500 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
501 if (inserted) {
502 return it;
503 }
504 }
505}
506
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700507StorageId IncrementalService::createStorage(std::string_view mountPoint,
508 content::pm::DataLoaderParamsParcel dataLoaderParams,
509 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800510 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
511 if (!path::isAbsolute(mountPoint)) {
512 LOG(ERROR) << "path is not absolute: " << mountPoint;
513 return kInvalidStorageId;
514 }
515
516 auto mountNorm = path::normalize(mountPoint);
517 {
518 const auto id = findStorageId(mountNorm);
519 if (id != kInvalidStorageId) {
520 if (options & CreateOptions::OpenExisting) {
521 LOG(INFO) << "Opened existing storage " << id;
522 return id;
523 }
524 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
525 return kInvalidStorageId;
526 }
527 }
528
529 if (!(options & CreateOptions::CreateNew)) {
530 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
531 return kInvalidStorageId;
532 }
533
534 if (!path::isEmptyDir(mountNorm)) {
535 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
536 return kInvalidStorageId;
537 }
538 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
539 if (mountRoot.empty()) {
540 LOG(ERROR) << "Bad mount point";
541 return kInvalidStorageId;
542 }
543 // Make sure the code removes all crap it may create while still failing.
544 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
545 auto firstCleanupOnFailure =
546 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
547
548 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800549 const auto backing = path::join(mountRoot, constants().backing);
550 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800551 return kInvalidStorageId;
552 }
553
Songchun Fan3c82a302019-11-29 14:23:45 -0800554 IncFsMount::Control control;
555 {
556 std::lock_guard l(mMountOperationLock);
557 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800558
559 if (auto err = rmDirContent(backing.c_str())) {
560 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
561 return kInvalidStorageId;
562 }
563 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
564 return kInvalidStorageId;
565 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800566 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
567 return kInvalidStorageId;
568 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800569 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800570 if (!status.isOk()) {
571 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
572 return kInvalidStorageId;
573 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800574 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
575 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800576 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
577 return kInvalidStorageId;
578 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800579 int cmd = controlParcel.cmd.release().release();
580 int pendingReads = controlParcel.pendingReads.release().release();
581 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800582 int blocksWritten =
583 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
584 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800585 }
586
587 std::unique_lock l(mLock);
588 const auto mountIt = getStorageSlotLocked();
589 const auto mountId = mountIt->first;
590 l.unlock();
591
592 auto ifs =
593 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
594 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
595 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700596 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800597
598 auto secondCleanup = [this, &l](auto itPtr) {
599 if (!l.owns_lock()) {
600 l.lock();
601 }
602 mMounts.erase(*itPtr);
603 };
604 auto secondCleanupOnFailure =
605 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
606
607 const auto storageIt = ifs->makeStorage(ifs->mountId);
608 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800609 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800610 return kInvalidStorageId;
611 }
612
613 {
614 metadata::Mount m;
615 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700616 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700617 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
618 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
619 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800620 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800621 if (auto err =
622 mIncFs->makeFile(ifs->control,
623 path::join(ifs->root, constants().mount,
624 constants().infoMdName),
625 0777, idFromMetadata(metadata),
626 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800627 LOG(ERROR) << "Saving mount metadata failed: " << -err;
628 return kInvalidStorageId;
629 }
630 }
631
632 const auto bk =
633 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800634 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
635 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800636 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800637 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800638 return kInvalidStorageId;
639 }
640
641 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700642 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800643
Songchun Fan3c82a302019-11-29 14:23:45 -0800644 mountIt->second = std::move(ifs);
645 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700646
Songchun Fan3c82a302019-11-29 14:23:45 -0800647 LOG(INFO) << "created storage " << mountId;
648 return mountId;
649}
650
651StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
652 StorageId linkedStorage,
653 IncrementalService::CreateOptions options) {
654 if (!isValidMountTarget(mountPoint)) {
655 LOG(ERROR) << "Mount point is invalid or missing";
656 return kInvalidStorageId;
657 }
658
659 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700660 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800661 if (!ifs) {
662 LOG(ERROR) << "Ifs unavailable";
663 return kInvalidStorageId;
664 }
665
666 const auto mountIt = getStorageSlotLocked();
667 const auto storageId = mountIt->first;
668 const auto storageIt = ifs->makeStorage(storageId);
669 if (storageIt == ifs->storages.end()) {
670 LOG(ERROR) << "Can't create a new storage";
671 mMounts.erase(mountIt);
672 return kInvalidStorageId;
673 }
674
675 l.unlock();
676
677 const auto bk =
678 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800679 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
680 std::string(storageIt->second.name), path::normalize(mountPoint),
681 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800682 err < 0) {
683 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700684 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
685 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800686 return kInvalidStorageId;
687 }
688
689 mountIt->second = ifs;
690 return storageId;
691}
692
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700693bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700694 content::pm::DataLoaderParamsParcel dataLoaderParams,
695 DataLoaderStatusListener statusListener,
696 const StorageHealthCheckParams& healthCheckParams,
697 StorageHealthListener healthListener,
698 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800699 // Per Uid timeouts.
700 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700701 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800702 }
703
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700704 IfsMountPtr ifs;
705 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800706
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700707 // Re-initialize DataLoader.
708 {
709 ifs = getIfs(storageId);
710 if (!ifs) {
711 return false;
712 }
713
714 std::unique_lock l(ifs->lock);
715 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
716 }
717
718 if (dataLoaderStub) {
719 dataLoaderStub->cleanupResources();
720 dataLoaderStub = {};
721 }
722
723 {
724 std::unique_lock l(ifs->lock);
725 if (ifs->dataLoaderStub) {
726 LOG(INFO) << "Skipped data loader stub creation because it already exists";
727 return false;
728 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700729
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700730 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
731 healthCheckParams, std::move(healthListener));
732 CHECK(ifs->dataLoaderStub);
733 dataLoaderStub = ifs->dataLoaderStub;
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700734
735 // Disable long read timeouts for non-system dataloaders.
736 // To be re-enabled after installation is complete.
737 ifs->setReadTimeoutsRequested(dataLoaderStub->isSystemDataLoader() &&
738 getAlwaysEnableReadTimeoutsForSystemDataLoaders());
739 applyStorageParamsLocked(*ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700740 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800741
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700742 if (dataLoaderStub->isSystemDataLoader() &&
743 !getEnforceReadLogsMaxIntervalForSystemDataLoaders()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700744 // Readlogs from system dataloader (adb) can always be collected.
745 ifs->startLoadingTs = TimePoint::max();
746 } else {
747 // Assign time when installation wants the DL to start streaming.
748 const auto startLoadingTs = mClock->now();
749 ifs->startLoadingTs = startLoadingTs;
750 // Setup a callback to disable the readlogs after max interval.
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700751 addTimedJob(*mTimedQueue, storageId, getReadLogsMaxInterval(),
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700752 [this, storageId, startLoadingTs]() {
753 const auto ifs = getIfs(storageId);
754 if (!ifs) {
755 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
756 << storageId;
757 return;
758 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700759 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700760 if (ifs->startLoadingTs != startLoadingTs) {
761 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
762 "installation?): "
763 << storageId;
764 return;
765 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700766 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700767 });
768 }
769
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800770 return dataLoaderStub->requestStart();
771}
772
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700773void IncrementalService::onInstallationComplete(StorageId storage) {
774 IfsMountPtr ifs = getIfs(storage);
775 if (!ifs) {
776 return;
777 }
778
779 // Always enable long read timeouts after installation is complete.
780 std::unique_lock l(ifs->lock);
781 ifs->setReadTimeoutsRequested(true);
782 applyStorageParamsLocked(*ifs);
783}
784
Songchun Fan3c82a302019-11-29 14:23:45 -0800785IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
786 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700787 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800788}
789
790StorageId IncrementalService::findStorageId(std::string_view path) const {
791 std::lock_guard l(mLock);
792 auto it = findStorageLocked(path);
793 if (it == mBindsByPath.end()) {
794 return kInvalidStorageId;
795 }
796 return it->second->second.storage;
797}
798
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800799void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700800 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700801 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800802 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700803 return;
804 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700805
806 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800807 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700808 return;
809 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800810 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700811
812 const auto metadata = constants().readLogsDisabledMarkerName;
813 if (auto err = mIncFs->makeFile(ifs->control,
814 path::join(ifs->root, constants().mount,
815 constants().readLogsDisabledMarkerName),
816 0777, idFromMetadata(metadata), {})) {
817 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
818 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
819 return;
820 }
821
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700822 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700823}
824
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700825int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
826 const auto ifs = getIfs(storageId);
827 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700828 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700829 return -EINVAL;
830 }
831
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700832 std::string packageName;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700833
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700834 {
835 std::unique_lock l(ifs->lock);
836 if (!enableReadLogs) {
837 return disableReadLogsLocked(*ifs);
838 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700839
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700840 if (!ifs->readLogsAllowed()) {
841 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
842 return -EPERM;
843 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700844
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700845 if (!ifs->dataLoaderStub) {
846 // This should never happen - only DL can call enableReadLogs.
847 LOG(ERROR) << "enableReadLogs failed: invalid state";
848 return -EPERM;
849 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700850
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700851 // Check installation time.
852 const auto now = mClock->now();
853 const auto startLoadingTs = ifs->startLoadingTs;
854 if (startLoadingTs <= now && now - startLoadingTs > getReadLogsMaxInterval()) {
855 LOG(ERROR)
856 << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
857 << storageId;
858 return -EPERM;
859 }
860
861 packageName = ifs->dataLoaderStub->params().packageName;
862 ifs->setReadLogsRequested(true);
863 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700864
865 // Check loader usage stats permission and apop.
866 if (auto status =
867 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
868 !status.isOk()) {
869 LOG(ERROR) << " Permission: " << kLoaderUsageStats
870 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700871 return fromBinderStatus(status);
872 }
873
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700874 // Check multiuser permission.
875 if (auto status =
876 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
877 !status.isOk()) {
878 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
879 << " check failed: " << status.toString8();
880 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700881 }
882
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700883 {
884 std::unique_lock l(ifs->lock);
885 if (!ifs->readLogsRequested()) {
886 return 0;
887 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700888 if (auto status = applyStorageParamsLocked(*ifs); status != 0) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700889 return status;
890 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700891 }
892
893 registerAppOpsCallback(packageName);
894
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700895 return 0;
896}
897
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700898int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700899 ifs.setReadLogsRequested(false);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700900 return applyStorageParamsLocked(ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700901}
902
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700903int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700904 os::incremental::IncrementalFileSystemControlParcel control;
905 control.cmd.reset(dup(ifs.control.cmd()));
906 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700907 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700908 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700909 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700910 }
911
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700912 bool enableReadLogs = ifs.readLogsRequested();
913 bool enableReadTimeouts = ifs.readTimeoutsRequested();
914
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700915 std::lock_guard l(mMountOperationLock);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700916 auto status = mVold->setIncFsMountOptions(control, enableReadLogs, enableReadTimeouts);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800917 if (status.isOk()) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700918 // Store states.
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800919 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700920 ifs.setReadTimeoutsEnabled(enableReadTimeouts);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700921 } else {
922 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800923 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700924 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700925}
926
Songchun Fan3c82a302019-11-29 14:23:45 -0800927void IncrementalService::deleteStorage(StorageId storageId) {
928 const auto ifs = getIfs(storageId);
929 if (!ifs) {
930 return;
931 }
932 deleteStorage(*ifs);
933}
934
935void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
936 std::unique_lock l(ifs.lock);
937 deleteStorageLocked(ifs, std::move(l));
938}
939
940void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
941 std::unique_lock<std::mutex>&& ifsLock) {
942 const auto storages = std::move(ifs.storages);
943 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
944 const auto bindPoints = ifs.bindPoints;
945 ifsLock.unlock();
946
947 std::lock_guard l(mLock);
948 for (auto&& [id, _] : storages) {
949 if (id != ifs.mountId) {
950 mMounts.erase(id);
951 }
952 }
953 for (auto&& [path, _] : bindPoints) {
954 mBindsByPath.erase(path);
955 }
956 mMounts.erase(ifs.mountId);
957}
958
959StorageId IncrementalService::openStorage(std::string_view pathInMount) {
960 if (!path::isAbsolute(pathInMount)) {
961 return kInvalidStorageId;
962 }
963
964 return findStorageId(path::normalize(pathInMount));
965}
966
Songchun Fan3c82a302019-11-29 14:23:45 -0800967IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
968 std::lock_guard l(mLock);
969 return getIfsLocked(storage);
970}
971
972const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
973 auto it = mMounts.find(storage);
974 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700975 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700976 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800977 }
978 return it->second;
979}
980
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800981int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
982 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800983 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700984 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800985 return -EINVAL;
986 }
987
988 const auto ifs = getIfs(storage);
989 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700990 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800991 return -EINVAL;
992 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800993
Songchun Fan3c82a302019-11-29 14:23:45 -0800994 std::unique_lock l(ifs->lock);
995 const auto storageInfo = ifs->storages.find(storage);
996 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700997 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800998 return -EINVAL;
999 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001000 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001001 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001002 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001003 return -EINVAL;
1004 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001005 l.unlock();
1006 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001007 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
1008 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -08001009}
1010
1011int IncrementalService::unbind(StorageId storage, std::string_view target) {
1012 if (!path::isAbsolute(target)) {
1013 return -EINVAL;
1014 }
1015
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001016 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001017
1018 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
1019 // otherwise there's a chance to unmount something completely unrelated
1020 const auto norm = path::normalize(target);
1021 std::unique_lock l(mLock);
1022 const auto storageIt = mBindsByPath.find(norm);
1023 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
1024 return -EINVAL;
1025 }
1026 const auto bindIt = storageIt->second;
1027 const auto storageId = bindIt->second.storage;
1028 const auto ifs = getIfsLocked(storageId);
1029 if (!ifs) {
1030 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
1031 << " is missing";
1032 return -EFAULT;
1033 }
1034 mBindsByPath.erase(storageIt);
1035 l.unlock();
1036
1037 mVold->unmountIncFs(bindIt->first);
1038 std::unique_lock l2(ifs->lock);
1039 if (ifs->bindPoints.size() <= 1) {
1040 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -07001041 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001042 } else {
1043 const std::string savedFile = std::move(bindIt->second.savedFilename);
1044 ifs->bindPoints.erase(bindIt);
1045 l2.unlock();
1046 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001047 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001048 }
1049 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001050
Songchun Fan3c82a302019-11-29 14:23:45 -08001051 return 0;
1052}
1053
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001054std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001055 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001056 std::string_view path) const {
1057 if (!path::isAbsolute(path)) {
1058 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001059 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001060 auto normPath = path::normalize(path);
1061 if (path::startsWith(normPath, storageIt->second.name)) {
1062 return normPath;
1063 }
1064 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001065 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1066 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001067 return {};
1068 }
1069 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001070}
1071
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001072std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001073 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001074 std::unique_lock l(ifs.lock);
1075 const auto storageInfo = ifs.storages.find(storage);
1076 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001077 return {};
1078 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001079 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001080}
1081
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001082int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001083 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001084 const auto ifs = getIfs(storage);
1085 if (!ifs) {
1086 return -EINVAL;
1087 }
1088 if (data.size() > params.size) {
1089 LOG(ERROR) << "Bad data size - bigger than file size";
1090 return -EINVAL;
1091 }
1092 if (!data.empty() && data.size() != params.size) {
1093 // Writing a page is an irreversible operation, and it can't be updated with additional
1094 // data later. Check that the last written page is complete, or we may break the file.
1095 if (!isPageAligned(data.size())) {
1096 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001097 return -EINVAL;
1098 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001099 }
1100 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1101 if (normPath.empty()) {
1102 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1103 return -EINVAL;
1104 }
1105 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
1106 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
1107 return err;
1108 }
1109 if (params.size > 0) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001110 if (auto err = mIncFs->reserveSpace(ifs->control, id, params.size)) {
1111 if (err != -EOPNOTSUPP) {
1112 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1113 (void)mIncFs->unlink(ifs->control, normPath);
1114 return err;
1115 } else {
1116 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1117 "may run out of disk later";
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001118 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001119 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001120 if (!data.empty()) {
1121 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001122 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001123 return err;
1124 }
1125 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001126 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001127 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001128}
1129
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001130int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001131 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001132 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001133 if (normPath.empty()) {
1134 return -EINVAL;
1135 }
1136 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001137 }
1138 return -EINVAL;
1139}
1140
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001141int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001142 const auto ifs = getIfs(storageId);
1143 if (!ifs) {
1144 return -EINVAL;
1145 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001146 return makeDirs(*ifs, storageId, path, mode);
1147}
1148
1149int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1150 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001151 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1152 if (normPath.empty()) {
1153 return -EINVAL;
1154 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001155 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001156}
1157
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001158int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1159 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001160 std::unique_lock l(mLock);
1161 auto ifsSrc = getIfsLocked(sourceStorageId);
1162 if (!ifsSrc) {
1163 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001164 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001165 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1166 return -EINVAL;
1167 }
1168 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001169 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1170 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001171 if (normOldPath.empty() || normNewPath.empty()) {
1172 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1173 return -EINVAL;
1174 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001175 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1176 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1177 << " to " << newPath << "[" << normNewPath << "]";
1178 return err;
1179 }
1180 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001181}
1182
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001183int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001184 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001185 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001186 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001187 }
1188 return -EINVAL;
1189}
1190
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001191int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1192 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001193 std::string&& target, BindKind kind,
1194 std::unique_lock<std::mutex>& mainLock) {
1195 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001196 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001197 return -EINVAL;
1198 }
1199
1200 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001201 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001202 if (kind != BindKind::Temporary) {
1203 metadata::BindPoint bp;
1204 bp.set_storage_id(storage);
1205 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001206 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001207 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001208 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001209 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001210 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001211 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1212 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1213 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001214 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001215 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001216 return int(node);
1217 }
1218 }
1219
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001220 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1221 std::move(target), kind, mainLock);
1222 if (res) {
1223 mIncFs->unlink(ifs.control, metadataFullPath);
1224 }
1225 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001226}
1227
1228int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001229 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001230 std::string&& target, BindKind kind,
1231 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001232 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001233 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001234 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001235 if (!status.isOk()) {
1236 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1237 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1238 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1239 : status.serviceSpecificErrorCode() == 0
1240 ? -EFAULT
1241 : status.serviceSpecificErrorCode()
1242 : -EIO;
1243 }
1244 }
1245
1246 if (!mainLock.owns_lock()) {
1247 mainLock.lock();
1248 }
1249 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001250 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1251 std::move(target), kind);
1252 return 0;
1253}
1254
1255void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1256 std::string&& metadataName, std::string&& source,
1257 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001258 const auto [it, _] =
1259 ifs.bindPoints.insert_or_assign(target,
1260 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001261 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001262 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001263}
1264
1265RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1266 const auto ifs = getIfs(storage);
1267 if (!ifs) {
1268 return {};
1269 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001270 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001271 if (normPath.empty()) {
1272 return {};
1273 }
1274 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001275}
1276
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001277RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001278 const auto ifs = getIfs(storage);
1279 if (!ifs) {
1280 return {};
1281 }
1282 return mIncFs->getMetadata(ifs->control, node);
1283}
1284
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001285void IncrementalService::setUidReadTimeouts(StorageId storage,
1286 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001287 using microseconds = std::chrono::microseconds;
1288 using milliseconds = std::chrono::milliseconds;
1289
1290 auto maxPendingTimeUs = microseconds(0);
1291 for (const auto& timeouts : perUidReadTimeouts) {
1292 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1293 }
1294 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07001295 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001296 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1297 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001298 return;
1299 }
1300
1301 const auto ifs = getIfs(storage);
1302 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001303 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001304 return;
1305 }
1306
1307 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1308 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1309 return;
1310 }
1311
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001312 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1313 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1314 if (checkUidReadTimeouts(storageId, state, timeout)) {
1315 return true;
1316 }
1317 clearUidReadTimeouts(storageId);
1318 return false;
1319 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001320}
1321
1322void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1323 const auto ifs = getIfs(storage);
1324 if (!ifs) {
1325 return;
1326 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001327 mIncFs->setUidReadTimeouts(ifs->control, {});
1328}
1329
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001330bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1331 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001332 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001333 // Reached maximum timeout.
1334 return false;
1335 }
1336 if (state.error) {
1337 // Something is wrong, abort.
1338 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001339 }
1340
1341 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001342 if (state.fullyLoaded && !state.readLogsEnabled) {
1343 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001344 }
1345
1346 const auto timeLeft = timeLimit - Clock::now();
1347 if (timeLeft < Constants::progressUpdateInterval) {
1348 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001349 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001350 }
1351
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001352 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001353}
1354
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001355std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1356 std::unordered_set<std::string_view> mountedRootNames;
1357 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1358 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1359 for (auto [source, target] : binds) {
1360 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1361 LOG(INFO) << " " << path::join(root, source);
1362 }
1363
1364 // Ensure it's a kind of a mount that's managed by IncrementalService
1365 if (path::basename(root) != constants().mount ||
1366 path::basename(backingDir) != constants().backing) {
1367 return;
1368 }
1369 const auto expectedRoot = path::dirname(root);
1370 if (path::dirname(backingDir) != expectedRoot) {
1371 return;
1372 }
1373 if (path::dirname(expectedRoot) != mIncrementalDir) {
1374 return;
1375 }
1376 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1377 return;
1378 }
1379
1380 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1381
1382 // make sure we clean up the mount if it happens to be a bad one.
1383 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1384 auto cleanupFiles = makeCleanup([&]() {
1385 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1386 IncFsMount::cleanupFilesystem(expectedRoot);
1387 });
1388 auto cleanupMounts = makeCleanup([&]() {
1389 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1390 for (auto&& [_, target] : binds) {
1391 mVold->unmountIncFs(std::string(target));
1392 }
1393 mVold->unmountIncFs(std::string(root));
1394 });
1395
1396 auto control = mIncFs->openMount(root);
1397 if (!control) {
1398 LOG(INFO) << "failed to open mount " << root;
1399 return;
1400 }
1401
1402 auto mountRecord =
1403 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1404 path::join(root, constants().infoMdName));
1405 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1406 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1407 return;
1408 }
1409
1410 auto mountId = mountRecord.storage().id();
1411 mNextId = std::max(mNextId, mountId + 1);
1412
1413 DataLoaderParamsParcel dataLoaderParams;
1414 {
1415 const auto& loader = mountRecord.loader();
1416 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1417 dataLoaderParams.packageName = loader.package_name();
1418 dataLoaderParams.className = loader.class_name();
1419 dataLoaderParams.arguments = loader.arguments();
1420 }
1421
1422 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1423 std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001424 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001425
Alex Buynytskyy04035452020-06-06 20:15:58 -07001426 // Check if marker file present.
1427 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001428 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001429 }
1430
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001431 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1432 auto d = openDir(root);
1433 while (auto e = ::readdir(d.get())) {
1434 if (e->d_type == DT_REG) {
1435 auto name = std::string_view(e->d_name);
1436 if (name.starts_with(constants().mountpointMdPrefix)) {
1437 permanentBindPoints
1438 .emplace_back(name,
1439 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1440 ifs->control,
1441 path::join(root,
1442 name)));
1443 if (permanentBindPoints.back().second.dest_path().empty() ||
1444 permanentBindPoints.back().second.source_subdir().empty()) {
1445 permanentBindPoints.pop_back();
1446 mIncFs->unlink(ifs->control, path::join(root, name));
1447 } else {
1448 LOG(INFO) << "Permanent bind record: '"
1449 << permanentBindPoints.back().second.source_subdir() << "'->'"
1450 << permanentBindPoints.back().second.dest_path() << "'";
1451 }
1452 }
1453 } else if (e->d_type == DT_DIR) {
1454 if (e->d_name == "."sv || e->d_name == ".."sv) {
1455 continue;
1456 }
1457 auto name = std::string_view(e->d_name);
1458 if (name.starts_with(constants().storagePrefix)) {
1459 int storageId;
1460 const auto res =
1461 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1462 name.data() + name.size(), storageId);
1463 if (res.ec != std::errc{} || *res.ptr != '_') {
1464 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1465 << "' for mount " << expectedRoot;
1466 continue;
1467 }
1468 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1469 if (!inserted) {
1470 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1471 << " for mount " << expectedRoot;
1472 continue;
1473 }
1474 ifs->storages.insert_or_assign(storageId,
1475 IncFsMount::Storage{path::join(root, name)});
1476 mNextId = std::max(mNextId, storageId + 1);
1477 }
1478 }
1479 }
1480
1481 if (ifs->storages.empty()) {
1482 LOG(WARNING) << "No valid storages in mount " << root;
1483 return;
1484 }
1485
1486 // now match the mounted directories with what we expect to have in the metadata
1487 {
1488 std::unique_lock l(mLock, std::defer_lock);
1489 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1490 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1491 [&, bindRecord = bindRecord](auto&& bind) {
1492 return bind.second == bindRecord.dest_path() &&
1493 path::join(root, bind.first) ==
1494 bindRecord.source_subdir();
1495 });
1496 if (mountedIt != binds.end()) {
1497 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1498 << " to mount " << mountedIt->first;
1499 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1500 std::move(*bindRecord.mutable_source_subdir()),
1501 std::move(*bindRecord.mutable_dest_path()),
1502 BindKind::Permanent);
1503 if (mountedIt != binds.end() - 1) {
1504 std::iter_swap(mountedIt, binds.end() - 1);
1505 }
1506 binds = binds.first(binds.size() - 1);
1507 } else {
1508 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1509 << ", mounting";
1510 // doesn't exist - try mounting back
1511 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1512 std::move(*bindRecord.mutable_source_subdir()),
1513 std::move(*bindRecord.mutable_dest_path()),
1514 BindKind::Permanent, l)) {
1515 mIncFs->unlink(ifs->control, metadataFile);
1516 }
1517 }
1518 }
1519 }
1520
1521 // if anything stays in |binds| those are probably temporary binds; system restarted since
1522 // they were mounted - so let's unmount them all.
1523 for (auto&& [source, target] : binds) {
1524 if (source.empty()) {
1525 continue;
1526 }
1527 mVold->unmountIncFs(std::string(target));
1528 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001529 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001530
1531 if (ifs->bindPoints.empty()) {
1532 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1533 deleteStorage(*ifs);
1534 return;
1535 }
1536
1537 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1538 CHECK(ifs->dataLoaderStub);
1539
1540 mountedRootNames.insert(path::basename(ifs->root));
1541
1542 // not locking here at all: we're still in the constructor, no other calls can happen
1543 mMounts[ifs->mountId] = std::move(ifs);
1544 });
1545
1546 return mountedRootNames;
1547}
1548
1549void IncrementalService::mountExistingImages(
1550 const std::unordered_set<std::string_view>& mountedRootNames) {
1551 auto dir = openDir(mIncrementalDir);
1552 if (!dir) {
1553 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1554 return;
1555 }
1556 while (auto entry = ::readdir(dir.get())) {
1557 if (entry->d_type != DT_DIR) {
1558 continue;
1559 }
1560 std::string_view name = entry->d_name;
1561 if (!name.starts_with(constants().mountKeyPrefix)) {
1562 continue;
1563 }
1564 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001565 continue;
1566 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001567 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001568 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001569 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001570 }
1571 }
1572}
1573
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001574bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001575 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001576 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001577
Songchun Fan3c82a302019-11-29 14:23:45 -08001578 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001579 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001580 if (!status.isOk()) {
1581 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1582 return false;
1583 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001584
1585 int cmd = controlParcel.cmd.release().release();
1586 int pendingReads = controlParcel.pendingReads.release().release();
1587 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001588 int blocksWritten =
1589 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1590 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001591
1592 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1593
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001594 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1595 path::join(mountTarget, constants().infoMdName));
1596 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001597 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1598 return false;
1599 }
1600
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001601 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001602 mNextId = std::max(mNextId, ifs->mountId + 1);
1603
Alex Buynytskyy04035452020-06-06 20:15:58 -07001604 // Check if marker file present.
1605 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001606 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001607 }
1608
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001609 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001610 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001611 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001612 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001613 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001614 dataLoaderParams.packageName = loader.package_name();
1615 dataLoaderParams.className = loader.class_name();
1616 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001617 }
1618
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001619 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001620 CHECK(ifs->dataLoaderStub);
1621
Songchun Fan3c82a302019-11-29 14:23:45 -08001622 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001623 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001624 while (auto e = ::readdir(d.get())) {
1625 if (e->d_type == DT_REG) {
1626 auto name = std::string_view(e->d_name);
1627 if (name.starts_with(constants().mountpointMdPrefix)) {
1628 bindPoints.emplace_back(name,
1629 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1630 ifs->control,
1631 path::join(mountTarget,
1632 name)));
1633 if (bindPoints.back().second.dest_path().empty() ||
1634 bindPoints.back().second.source_subdir().empty()) {
1635 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001636 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001637 }
1638 }
1639 } else if (e->d_type == DT_DIR) {
1640 if (e->d_name == "."sv || e->d_name == ".."sv) {
1641 continue;
1642 }
1643 auto name = std::string_view(e->d_name);
1644 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001645 int storageId;
1646 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1647 name.data() + name.size(), storageId);
1648 if (res.ec != std::errc{} || *res.ptr != '_') {
1649 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1650 << root;
1651 continue;
1652 }
1653 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001654 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001655 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001656 << " for mount " << root;
1657 continue;
1658 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001659 ifs->storages.insert_or_assign(storageId,
1660 IncFsMount::Storage{
1661 path::join(root, constants().mount, name)});
1662 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001663 }
1664 }
1665 }
1666
1667 if (ifs->storages.empty()) {
1668 LOG(WARNING) << "No valid storages in mount " << root;
1669 return false;
1670 }
1671
1672 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001673 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001674 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001675 for (auto&& bp : bindPoints) {
1676 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1677 std::move(*bp.second.mutable_source_subdir()),
1678 std::move(*bp.second.mutable_dest_path()),
1679 BindKind::Permanent, l);
1680 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001681 }
1682
1683 if (bindCount == 0) {
1684 LOG(WARNING) << "No valid bind points for mount " << root;
1685 deleteStorage(*ifs);
1686 return false;
1687 }
1688
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001689 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001690 mMounts[ifs->mountId] = std::move(ifs);
1691 return true;
1692}
1693
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001694void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001695 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001696 while (mRunning.load(std::memory_order_relaxed)) {
1697 mLooper->pollAll(kTimeoutMsecs);
1698 }
1699}
1700
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001701void IncrementalService::trimReservedSpaceV1(const IncFsMount& ifs) {
1702 mIncFs->forEachFile(ifs.control, [this](auto&& control, auto&& fileId) {
1703 if (mIncFs->isFileFullyLoaded(control, fileId) == incfs::LoadingState::Full) {
1704 mIncFs->reserveSpace(control, fileId, -1);
1705 }
1706 return true;
1707 });
1708}
1709
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001710void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001711 DataLoaderStatusListener&& statusListener,
1712 const StorageHealthCheckParams& healthCheckParams,
1713 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001714 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001715 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001716 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1717 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1718 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001719 if (ifs.control.blocksWritten() >= 0) {
1720 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1721 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001722 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001723
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001724 ifs.dataLoaderStub =
1725 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001726 std::move(statusListener), healthCheckParams,
1727 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001728
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001729 // pre-v2 IncFS doesn't do automatic reserved space trimming - need to run it manually
1730 if (!(mIncFs->features() & incfs::Features::v2)) {
1731 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1732 if (!state.fullyLoaded) {
1733 return true;
1734 }
1735
1736 const auto ifs = getIfs(storageId);
1737 if (!ifs) {
1738 return false;
1739 }
1740 trimReservedSpaceV1(*ifs);
1741 return false;
1742 });
1743 }
1744
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001745 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1746 if (!state.fullyLoaded || state.readLogsEnabled) {
1747 return true;
1748 }
1749
1750 DataLoaderStubPtr dataLoaderStub;
1751 {
1752 const auto ifs = getIfs(storageId);
1753 if (!ifs) {
1754 return false;
1755 }
1756
1757 std::unique_lock l(ifs->lock);
1758 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1759 }
1760
1761 if (dataLoaderStub) {
1762 dataLoaderStub->cleanupResources();
1763 }
1764
1765 return false;
1766 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001767}
1768
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001769template <class Duration>
1770static long elapsedMcs(Duration start, Duration end) {
1771 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1772}
1773
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001774template <class Duration>
1775static constexpr auto castToMs(Duration d) {
1776 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1777}
1778
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001779// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001780// Lib files should be placed next to the APK file in the following matter:
1781// Example:
1782// /path/to/base.apk
1783// /path/to/lib/arm/first.so
1784// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001785bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1786 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001787 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001788 auto start = Clock::now();
1789
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001790 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001791 if (!ifs) {
1792 LOG(ERROR) << "Invalid storage " << storage;
1793 return false;
1794 }
1795
Songchun Fanc8975312020-07-13 12:14:37 -07001796 const auto targetLibPathRelativeToStorage =
1797 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1798 libDirRelativePath);
1799
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001800 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001801 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1802 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001803 << " errno: " << res;
1804 return false;
1805 }
1806
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001807 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001808 ZipArchiveHandle zipFileHandle;
1809 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001810 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1811 return false;
1812 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001813
1814 // Need a shared pointer: will be passing it into all unpacking jobs.
1815 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001816 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001817 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001818 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001819 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1820 return false;
1821 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001822 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001823 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1824
1825 auto openZipTs = Clock::now();
1826
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001827 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1828 incfs::FileId sourceId;
1829 if (mapFiles) {
1830 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1831 if (!incfs::isValidFileId(sourceId)) {
1832 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1833 << "', mapping disabled";
1834 mapFiles = false;
1835 }
1836 }
1837
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001838 std::vector<Job> jobQueue;
1839 ZipEntry entry;
1840 std::string_view fileName;
1841 while (!Next(cookie, &entry, &fileName)) {
1842 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001843 continue;
1844 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001845
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001846 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001847 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001848
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001849 if (!extractNativeLibs) {
1850 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001851 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001852 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1853 return false;
1854 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001855 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001856 LOG(WARNING) << "Library " << fileName
1857 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1858 << entry.offset;
1859 return false;
1860 }
1861 continue;
1862 }
1863
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001864 auto startFileTs = Clock::now();
1865
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001866 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001867 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001868 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001869 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001870 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001871 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001872 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1873 << "; skipping extraction, spent "
1874 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1875 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001876 continue;
1877 }
1878
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001879 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1880 incfs::NewMappedFileParams mappedFileParams = {
1881 .sourceId = sourceId,
1882 .sourceOffset = entry.offset,
1883 .size = entry.uncompressed_length,
1884 };
1885
1886 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1887 mappedFileParams);
1888 res == 0) {
1889 if (perfLoggingEnabled()) {
1890 auto doneTs = Clock::now();
1891 LOG(INFO) << "incfs: Mapped " << libName << ": "
1892 << elapsedMcs(startFileTs, doneTs) << "mcs";
1893 }
1894 continue;
1895 } else {
1896 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1897 << "; falling back to full extraction";
1898 }
1899 }
1900
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001901 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001902 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001903 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001904 .signature = {},
1905 // Metadata of the new lib file is its relative path
1906 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1907 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001908 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001909 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001910 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001911 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001912 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001913 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001914 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001915
1916 auto makeFileTs = Clock::now();
1917
Songchun Fanafaf6e92020-03-18 14:12:20 -07001918 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001919 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001920 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001921 LOG(INFO) << "incfs: Extracted " << libName
1922 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001923 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001924 continue;
1925 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001926
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001927 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1928 libFileId, libPath = std::move(targetLibPath),
1929 makeFileTs]() mutable {
1930 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001931 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001932
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001933 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001934 auto prepareJobTs = Clock::now();
1935 LOG(INFO) << "incfs: Processed " << libName << ": "
1936 << elapsedMcs(startFileTs, prepareJobTs)
1937 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1938 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001939 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001940 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001941
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001942 auto processedTs = Clock::now();
1943
1944 if (!jobQueue.empty()) {
1945 {
1946 std::lock_guard lock(mJobMutex);
1947 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001948 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001949 if (existingJobs.empty()) {
1950 existingJobs = std::move(jobQueue);
1951 } else {
1952 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1953 std::move_iterator(jobQueue.end()));
1954 }
1955 }
1956 }
1957 mJobCondition.notify_all();
1958 }
1959
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001960 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001961 auto end = Clock::now();
1962 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1963 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1964 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001965 << " make files: " << elapsedMcs(openZipTs, processedTs)
1966 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001967 }
1968
1969 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001970}
1971
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001972void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1973 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001974 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001975 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001976 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001977 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001978 return;
1979 }
1980
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001981 auto startedTs = Clock::now();
1982
1983 // Write extracted data to new file
1984 // NOTE: don't zero-initialize memory, it may take a while for nothing
1985 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1986 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001987 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001988 return;
1989 }
1990
1991 auto extractFileTs = Clock::now();
1992
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001993 if (setFileContent(ifs, libFileId, debugLibPath,
1994 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001995 return;
1996 }
1997
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001998 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001999 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002000 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
2001 << entry.compressed_length << " -> " << entry.uncompressed_length
2002 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002003 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
2004 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002005 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002006 }
2007}
2008
2009bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002010 struct WaitPrinter {
2011 const Clock::time_point startTs = Clock::now();
2012 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002013 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002014 const auto endTs = Clock::now();
2015 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
2016 << elapsedMcs(startTs, endTs) << "mcs";
2017 }
2018 }
2019 } waitPrinter;
2020
2021 MountId mount;
2022 {
2023 auto ifs = getIfs(storage);
2024 if (!ifs) {
2025 return true;
2026 }
2027 mount = ifs->mountId;
2028 }
2029
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002030 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002031 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002032 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002033 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002034 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002035 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002036}
2037
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002038int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
2039 std::string_view debugFilePath,
2040 std::span<const uint8_t> data) const {
2041 auto startTs = Clock::now();
2042
2043 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2044 if (!writeFd.ok()) {
2045 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2046 << " errno: " << writeFd.get();
2047 return writeFd.get();
2048 }
2049
2050 const auto dataLength = data.size();
2051
2052 auto openFileTs = Clock::now();
2053 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2054 std::vector<IncFsDataBlock> instructions(numBlocks);
2055 for (int i = 0; i < numBlocks; i++) {
2056 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2057 instructions[i] = IncFsDataBlock{
2058 .fileFd = writeFd.get(),
2059 .pageIndex = static_cast<IncFsBlockIndex>(i),
2060 .compression = INCFS_COMPRESSION_KIND_NONE,
2061 .kind = INCFS_BLOCK_KIND_DATA,
2062 .dataSize = static_cast<uint32_t>(blockSize),
2063 .data = reinterpret_cast<const char*>(data.data()),
2064 };
2065 data = data.subspan(blockSize);
2066 }
2067 auto prepareInstsTs = Clock::now();
2068
2069 size_t res = mIncFs->writeBlocks(instructions);
2070 if (res != instructions.size()) {
2071 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2072 return res;
2073 }
2074
2075 if (perfLoggingEnabled()) {
2076 auto endTs = Clock::now();
2077 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2078 << " bytes): " << elapsedMcs(startTs, endTs)
2079 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2080 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2081 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2082 }
2083
2084 return 0;
2085}
2086
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002087incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2088 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002089 std::unique_lock l(mLock);
2090 const auto ifs = getIfsLocked(storage);
2091 if (!ifs) {
2092 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002093 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002094 }
2095 const auto storageInfo = ifs->storages.find(storage);
2096 if (storageInfo == ifs->storages.end()) {
2097 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002098 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002099 }
2100 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002101 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002102}
2103
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002104incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2105 const auto ifs = getIfs(storage);
2106 if (!ifs) {
2107 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2108 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002109 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002110 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002111}
2112
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002113IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002114 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002115 std::unique_lock l(mLock);
2116 const auto ifs = getIfsLocked(storage);
2117 if (!ifs) {
2118 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002119 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002120 }
2121 const auto storageInfo = ifs->storages.find(storage);
2122 if (storageInfo == ifs->storages.end()) {
2123 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002124 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002125 }
2126 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002127 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002128}
2129
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002130IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002131 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002132 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2133 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002134 const auto [filledBlocksCount, totalBlocksCount] =
2135 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002136 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2137 filledBlocksCount == -ENOENT) {
2138 // a kind of a file that's not really being loaded, e.g. a mapped range
2139 // an older IncFS used to return ENOENT in this case, so handle it the same way
2140 return true;
2141 }
Songchun Fan374f7652020-08-20 08:40:29 -07002142 if (filledBlocksCount < 0) {
2143 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002144 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002145 error = filledBlocksCount;
2146 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002147 }
2148 totalBlocks += totalBlocksCount;
2149 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002150 return true;
2151 });
Songchun Fan374f7652020-08-20 08:40:29 -07002152
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002153 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002154}
2155
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002156bool IncrementalService::updateLoadingProgress(StorageId storage,
2157 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002158 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002159 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002160 // Failed to get progress from incfs, abort.
2161 return false;
2162 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002163 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2164 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002165 // Stop updating progress once it is fully loaded
2166 return true;
2167 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002168 addTimedJob(*mProgressUpdateJobQueue, storage,
2169 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002170 [storage, progressListener = std::move(progressListener), this]() mutable {
2171 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002172 });
2173 return true;
2174}
2175
2176bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002177 StorageId storage, StorageLoadingProgressListener progressListener) {
2178 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002179}
2180
2181bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2182 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2183}
2184
Songchun Fan2570ec02020-10-08 17:22:33 -07002185bool IncrementalService::registerStorageHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002186 StorageId storage, const StorageHealthCheckParams& healthCheckParams,
2187 StorageHealthListener healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002188 DataLoaderStubPtr dataLoaderStub;
2189 {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002190 const auto& ifs = getIfs(storage);
Songchun Fan2570ec02020-10-08 17:22:33 -07002191 if (!ifs) {
2192 return false;
2193 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002194 std::unique_lock l(ifs->lock);
Songchun Fan2570ec02020-10-08 17:22:33 -07002195 dataLoaderStub = ifs->dataLoaderStub;
2196 if (!dataLoaderStub) {
2197 return false;
2198 }
2199 }
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002200 dataLoaderStub->setHealthListener(healthCheckParams, std::move(healthListener));
Songchun Fan2570ec02020-10-08 17:22:33 -07002201 return true;
2202}
2203
2204void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002205 registerStorageHealthListener(storage, {}, {});
Songchun Fan2570ec02020-10-08 17:22:33 -07002206}
2207
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002208bool IncrementalService::perfLoggingEnabled() {
2209 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2210 return enabled;
2211}
2212
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002213void IncrementalService::runJobProcessing() {
2214 for (;;) {
2215 std::unique_lock lock(mJobMutex);
2216 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2217 if (!mRunning) {
2218 return;
2219 }
2220
2221 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002222 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002223 auto queue = std::move(it->second);
2224 mJobQueue.erase(it);
2225 lock.unlock();
2226
2227 for (auto&& job : queue) {
2228 job();
2229 }
2230
2231 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002232 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002233 lock.unlock();
2234 mJobCondition.notify_all();
2235 }
2236}
2237
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002238void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002239 sp<IAppOpsCallback> listener;
2240 {
2241 std::unique_lock lock{mCallbacksLock};
2242 auto& cb = mCallbackRegistered[packageName];
2243 if (cb) {
2244 return;
2245 }
2246 cb = new AppOpsListener(*this, packageName);
2247 listener = cb;
2248 }
2249
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002250 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2251 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002252}
2253
2254bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2255 sp<IAppOpsCallback> listener;
2256 {
2257 std::unique_lock lock{mCallbacksLock};
2258 auto found = mCallbackRegistered.find(packageName);
2259 if (found == mCallbackRegistered.end()) {
2260 return false;
2261 }
2262 listener = found->second;
2263 mCallbackRegistered.erase(found);
2264 }
2265
2266 mAppOpsManager->stopWatchingMode(listener);
2267 return true;
2268}
2269
2270void IncrementalService::onAppOpChanged(const std::string& packageName) {
2271 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002272 return;
2273 }
2274
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002275 std::vector<IfsMountPtr> affected;
2276 {
2277 std::lock_guard l(mLock);
2278 affected.reserve(mMounts.size());
2279 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002280 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002281 if (ifs->mountId == id && ifs->dataLoaderStub &&
2282 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002283 affected.push_back(ifs);
2284 }
2285 }
2286 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002287 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002288 std::unique_lock ll(ifs->lock);
2289 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002290 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002291}
2292
Songchun Fana7098592020-09-03 11:45:53 -07002293bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2294 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002295 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002296 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002297 }
Songchun Fana7098592020-09-03 11:45:53 -07002298 timedQueue.addJob(id, after, std::move(what));
2299 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002300}
2301
Songchun Fana7098592020-09-03 11:45:53 -07002302bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002303 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002304 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002305 }
Songchun Fana7098592020-09-03 11:45:53 -07002306 timedQueue.removeJobs(id);
2307 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002308}
2309
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002310void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2311 bool wasEmpty;
2312 {
2313 std::lock_guard l(mIfsStateCallbacksLock);
2314 wasEmpty = mIfsStateCallbacks.empty();
2315 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2316 }
2317 if (wasEmpty) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002318 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002319 [this]() { processIfsStateCallbacks(); });
2320 }
2321}
2322
2323void IncrementalService::processIfsStateCallbacks() {
2324 StorageId storageId = kInvalidStorageId;
2325 std::vector<IfsStateCallback> local;
2326 while (true) {
2327 {
2328 std::lock_guard l(mIfsStateCallbacksLock);
2329 if (mIfsStateCallbacks.empty()) {
2330 return;
2331 }
2332 IfsStateCallbacks::iterator it;
2333 if (storageId == kInvalidStorageId) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002334 // First entry, initialize the |it|.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002335 it = mIfsStateCallbacks.begin();
2336 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002337 // Subsequent entries, update the |storageId|, and shift to the new one (not that
2338 // it guarantees much about updated items, but at least the loop will finish).
2339 it = mIfsStateCallbacks.lower_bound(storageId);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002340 if (it == mIfsStateCallbacks.end()) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002341 // Nothing else left, too bad.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002342 break;
2343 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002344 if (it->first != storageId) {
2345 local.clear(); // Was removed during processing, forget the old callbacks.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002346 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002347 // Put the 'surviving' callbacks back into the map and advance the position.
2348 auto& callbacks = it->second;
2349 if (callbacks.empty()) {
2350 std::swap(callbacks, local);
2351 } else {
2352 callbacks.insert(callbacks.end(), std::move_iterator(local.begin()),
2353 std::move_iterator(local.end()));
2354 local.clear();
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002355 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002356 if (callbacks.empty()) {
2357 it = mIfsStateCallbacks.erase(it);
2358 if (mIfsStateCallbacks.empty()) {
2359 return;
2360 }
2361 } else {
2362 ++it;
2363 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002364 }
2365 }
2366
2367 if (it == mIfsStateCallbacks.end()) {
2368 break;
2369 }
2370
2371 storageId = it->first;
2372 auto& callbacks = it->second;
2373 if (callbacks.empty()) {
2374 // Invalid case, one extra lookup should be ok.
2375 continue;
2376 }
2377 std::swap(callbacks, local);
2378 }
2379
2380 processIfsStateCallbacks(storageId, local);
2381 }
2382
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002383 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002384 [this]() { processIfsStateCallbacks(); });
2385}
2386
2387void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2388 std::vector<IfsStateCallback>& callbacks) {
2389 const auto state = isMountFullyLoaded(storageId);
2390 IfsState storageState = {};
2391 storageState.error = int(state) < 0;
2392 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2393 if (storageState.fullyLoaded) {
2394 const auto ifs = getIfs(storageId);
2395 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2396 }
2397
2398 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2399 if ((*cur)(storageId, storageState)) {
2400 ++cur;
2401 } else {
2402 cur = callbacks.erase(cur);
2403 }
2404 }
2405}
2406
2407void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2408 std::lock_guard l(mIfsStateCallbacksLock);
2409 mIfsStateCallbacks.erase(storageId);
2410}
2411
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002412void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
2413 const auto duration = getMillsSinceOldestPendingRead(storageId);
2414 if (duration >= 0) {
2415 const auto kMetricsMillisSinceOldestPendingRead =
2416 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
2417 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.data()), duration);
2418 }
2419}
2420
2421long IncrementalService::getMillsSinceOldestPendingRead(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002422 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002423 if (!ifs) {
2424 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, invalid storageId: " << storageId;
2425 return -EINVAL;
2426 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002427 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002428 if (!ifs->dataLoaderStub) {
2429 LOG(ERROR) << "getMillsSinceOldestPendingRead failed, no data loader: " << storageId;
2430 return -EINVAL;
2431 }
2432 return ifs->dataLoaderStub->elapsedMsSinceOldestPendingRead();
2433}
2434
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002435IncrementalService::DataLoaderStub::DataLoaderStub(
2436 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2437 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2438 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2439 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002440 : mService(service),
2441 mId(id),
2442 mParams(std::move(params)),
2443 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002444 mStatusListener(std::move(statusListener)),
2445 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002446 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002447 mHealthCheckParams(healthCheckParams) {
2448 if (mHealthListener && !isHealthParamsValid()) {
2449 mHealthListener = {};
2450 }
2451 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002452 // Disable advanced health check statuses.
2453 mHealthCheckParams.blockedTimeoutMs = -1;
2454 }
2455 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002456}
2457
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002458IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002459 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002460 cleanupResources();
2461 }
2462}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002463
2464void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002465 auto now = Clock::now();
2466 {
2467 std::unique_lock lock(mMutex);
2468 mHealthPath.clear();
2469 unregisterFromPendingReads();
2470 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002471 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002472 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002473 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002474
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002475 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002476
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002477 {
2478 std::unique_lock lock(mMutex);
2479 mParams = {};
2480 mControl = {};
2481 mHealthControl = {};
2482 mHealthListener = {};
2483 mStatusCondition.wait_until(lock, now + 60s, [this] {
2484 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2485 });
2486 mStatusListener = {};
2487 mId = kInvalidStorageId;
2488 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002489}
2490
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002491sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2492 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002493 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002494 if (!status.isOk()) {
2495 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2496 return {};
2497 }
2498 if (!dataloader) {
2499 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2500 return {};
2501 }
2502 return dataloader;
2503}
2504
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002505bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2506 return (params().packageName == Constants::systemPackage);
2507}
2508
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002509bool IncrementalService::DataLoaderStub::requestCreate() {
2510 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2511}
2512
2513bool IncrementalService::DataLoaderStub::requestStart() {
2514 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2515}
2516
2517bool IncrementalService::DataLoaderStub::requestDestroy() {
2518 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2519}
2520
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002521bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002522 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002523 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002524 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002525 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002526 return fsmStep();
2527}
2528
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002529void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002530 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002531 mTargetStatus = status;
2532 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002533 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002534 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002535}
2536
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002537std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002538 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002539
2540 const auto now = mService.mClock->now();
2541 const bool healthy = (mPreviousBindDelay == 0ms);
2542
2543 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2544 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2545 LOG(INFO) << "Binding still in progress. "
2546 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002547 : "Already unhealthy, don't do anything.")
2548 << " for storage " << mId;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002549 // Binding still in progress.
2550 if (!healthy) {
2551 // Already unhealthy, don't do anything.
2552 return {};
2553 }
2554 // The DL is healthy/freshly bound, ok to retry for a few times.
2555 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2556 // Still within grace period.
2557 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2558 // Retry interval passed, retrying.
2559 mCurrentStatusTs = now;
2560 mPreviousBindDelay = 0ms;
2561 return 0ms;
2562 }
2563 return {};
2564 }
2565 // fallthrough, mark as unhealthy, and retry with delay
2566 }
2567
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002568 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002569 mPreviousBindTs = now;
2570
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002571 const auto nonCrashingInterval =
2572 std::max(castToMs(now - previousBindTs - mPreviousBindDelay), 100ms);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002573 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2574 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2575 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002576 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002577 }
2578
2579 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2580 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2581
2582 const auto bindDelayMs =
2583 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2584 maxBindDelayMs)
2585 .count();
2586 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
2587 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - bindDelayJitterRangeMs;
2588 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002589 return mPreviousBindDelay;
2590}
2591
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002592bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002593 const auto maybeBindDelay = needToBind();
2594 if (!maybeBindDelay) {
2595 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2596 return true;
2597 }
2598 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002599 if (bindDelay > 1s) {
2600 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002601 << bindDelay.count() / 1000 << "s"
2602 << " for storage " << mId;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002603 }
2604
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002605 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002606 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2607 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002608 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002609 const bool healthy = (bindDelay == 0ms);
2610 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2611 << (healthy ? ", retrying." : "");
2612
2613 // Internal error, retry for healthy/new DLs.
2614 // Let needToBind migrate it to unhealthy after too many retries.
2615 if (healthy) {
2616 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2617 [this]() { fsmStep(); })) {
2618 // Mark as binding so that we know it's not the DL's fault.
2619 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2620 return true;
2621 }
2622 }
2623
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002624 return false;
2625 }
2626 return true;
2627}
2628
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002629bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002630 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002631 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002632 return false;
2633 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002634 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002635 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002636 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002637 return false;
2638 }
2639 return true;
2640}
2641
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002642bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002643 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002644 if (!dataloader) {
2645 return false;
2646 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002647 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002648 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002649 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002650 return false;
2651 }
2652 return true;
2653}
2654
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002655bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002656 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002657}
2658
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002659bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002660 if (!isValid()) {
2661 return false;
2662 }
2663
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002664 int currentStatus;
2665 int targetStatus;
2666 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002667 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002668 currentStatus = mCurrentStatus;
2669 targetStatus = mTargetStatus;
2670 }
2671
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002672 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002673
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002674 if (currentStatus == targetStatus) {
2675 return true;
2676 }
2677
2678 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002679 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2680 // Do nothing, this is a reset state.
2681 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002682 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002683 switch (currentStatus) {
2684 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
2685 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2686 return true;
2687 default:
2688 return destroy();
2689 }
2690 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002691 }
2692 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2693 switch (currentStatus) {
2694 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2695 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2696 return start();
2697 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002698 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002699 }
2700 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2701 switch (currentStatus) {
2702 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002703 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002704 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002705 return bind();
2706 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002707 return create();
2708 }
2709 break;
2710 default:
2711 LOG(ERROR) << "Invalid target status: " << targetStatus
2712 << ", current status: " << currentStatus;
2713 break;
2714 }
2715 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002716}
2717
2718binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002719 if (!isValid()) {
2720 return binder::Status::
2721 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2722 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002723 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002724 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2725 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002726 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2727 }
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002728 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
2729 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2730 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2731 [this, newStatus]() { setCurrentStatus(newStatus); });
2732 return binder::Status::ok();
2733 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002734
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002735 setCurrentStatus(newStatus);
2736 return binder::Status::ok();
2737}
2738
2739void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002740 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002741 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002742 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002743 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002744 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002745 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002746 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002747
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002748 oldStatus = mCurrentStatus;
2749 targetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002750 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002751
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002752 // Change the status.
2753 mCurrentStatus = newStatus;
2754 mCurrentStatusTs = mService.mClock->now();
2755
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002756 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2757 mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002758 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2759 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002760 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002761 }
2762
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002763 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002764 << newStatus << " (target " << targetStatus << ")";
2765
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002766 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002767 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002768 }
2769
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002770 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002771
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002772 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002773}
2774
Songchun Fan33093982020-09-10 13:12:39 -07002775binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2776 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002777 if (!isValid()) {
2778 return binder::Status::
2779 fromServiceSpecificError(-EINVAL,
2780 "reportStreamHealth came to invalid DataLoaderStub");
2781 }
2782 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002783 LOG(ERROR) << "reportStreamHealth: mount ID mismatch: expected " << id()
2784 << ", but got: " << mountId;
Songchun Fan2570ec02020-10-08 17:22:33 -07002785 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2786 }
2787 {
2788 std::lock_guard lock(mMutex);
2789 mStreamStatus = newStatus;
2790 }
Songchun Fan33093982020-09-10 13:12:39 -07002791 return binder::Status::ok();
2792}
2793
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002794bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2795 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2796 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002797}
2798
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002799void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002800 int healthStatus) {
2801 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2802 if (healthListener) {
2803 healthListener->onHealthStatus(id(), healthStatus);
2804 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002805}
2806
Songchun Fan2570ec02020-10-08 17:22:33 -07002807static int adjustHealthStatus(int healthStatus, int streamStatus) {
2808 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2809 // everything is good; no need to change status
2810 return healthStatus;
2811 }
2812 int newHeathStatus = healthStatus;
2813 switch (streamStatus) {
2814 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2815 // storage is limited and storage not healthy
2816 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2817 break;
2818 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2819 // fall through
2820 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2821 // fall through
2822 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2823 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2824 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2825 }
2826 // pending/blocked status due to transportation issues is not regarded as unhealthy
2827 break;
2828 default:
2829 break;
2830 }
2831 return newHeathStatus;
2832}
2833
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002834void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2835 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002836
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002837 int healthStatusToReport = -1;
2838 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002839
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002840 {
2841 std::unique_lock lock(mMutex);
2842 unregisterFromPendingReads();
2843
2844 healthListener = mHealthListener;
2845
2846 // Healthcheck depends on timestamp of the oldest pending read.
2847 // 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 -07002848 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2849 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002850 const auto now = Clock::now();
2851 const auto kernelTsUs = getOldestPendingReadTs();
2852 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002853 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2854 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002855 mHealthBase = {now, kernelTsUs};
2856 }
2857
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002858 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2859 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002860 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2861 registerForPendingReads();
2862 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2863 lock.unlock();
2864 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002865 return;
2866 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002867
2868 resetHealthControl();
2869
2870 // Always make sure the data loader is started.
2871 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2872
2873 // Skip any further processing if health check params are invalid.
2874 if (!isHealthParamsValid()) {
2875 LOG(DEBUG) << id()
2876 << ": Skip any further processing if health check params are invalid.";
2877 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2878 lock.unlock();
2879 onHealthStatus(healthListener, healthStatusToReport);
2880 // Triggering data loader start. This is a one-time action.
2881 fsmStep();
2882 return;
2883 }
2884
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002885 // Don't schedule timer job less than 500ms in advance.
2886 static constexpr auto kTolerance = 500ms;
2887
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002888 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2889 const auto unhealthyTimeout =
2890 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2891 const auto unhealthyMonitoring =
2892 std::max(1000ms,
2893 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2894
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002895 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002896
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002897 Milliseconds checkBackAfter;
2898 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002899 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002900 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002901 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002902 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002903 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002904 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002905 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2906 } else {
2907 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002908 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002909 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2910 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002911 // Adjust health status based on stream status
2912 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002913 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002914 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002915 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2916 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002917 }
2918
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002919 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002920 if (healthStatusToReport != -1) {
2921 onHealthStatus(healthListener, healthStatusToReport);
2922 }
2923
2924 fsmStep();
2925}
2926
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002927Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2928 BootClockTsUs kernelTsUs) {
2929 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2930 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2931 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2932}
2933
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002934const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2935 if (mHealthPath.empty()) {
2936 resetHealthControl();
2937 return mHealthControl;
2938 }
2939 if (mHealthControl.pendingReads() < 0) {
2940 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2941 }
2942 if (mHealthControl.pendingReads() < 0) {
2943 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2944 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2945 << mHealthControl.logs() << ")";
2946 }
2947 return mHealthControl;
2948}
2949
2950void IncrementalService::DataLoaderStub::resetHealthControl() {
2951 mHealthControl = {};
2952}
2953
2954BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2955 auto result = kMaxBootClockTsUs;
2956
2957 const auto& control = initializeHealthControl();
2958 if (control.pendingReads() < 0) {
2959 return result;
2960 }
2961
Songchun Fan6944f1e2020-11-06 15:24:24 -08002962 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002963 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08002964 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002965 // Clear previous pending reads
2966 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002967 return result;
2968 }
2969
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07002970 LOG(DEBUG) << id() << ": pendingReads: fd(" << control.pendingReads() << "), count("
2971 << mLastPendingReads.size() << "), block: " << mLastPendingReads.front().block
2972 << ", time: " << mLastPendingReads.front().bootClockTsUs
2973 << ", uid: " << mLastPendingReads.front().uid;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002974
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002975 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002976}
2977
2978void IncrementalService::DataLoaderStub::registerForPendingReads() {
2979 const auto pendingReadsFd = mHealthControl.pendingReads();
2980 if (pendingReadsFd < 0) {
2981 return;
2982 }
2983
2984 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2985
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002986 mService.mLooper->addFd(
2987 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2988 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002989 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002990 self->updateHealthStatus(/*baseline=*/true);
2991 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002992 },
2993 this);
2994 mService.mLooper->wake();
2995}
2996
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002997BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
2998 auto result = kMaxBootClockTsUs;
2999 for (auto&& pendingRead : mLastPendingReads) {
3000 result = std::min(result, pendingRead.bootClockTsUs);
3001 }
3002 return result;
3003}
3004
3005long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
3006 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
3007 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
3008 return 0;
3009 }
3010 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
3011}
3012
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07003013void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003014 const auto pendingReadsFd = mHealthControl.pendingReads();
3015 if (pendingReadsFd < 0) {
3016 return;
3017 }
3018
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003019 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
3020
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003021 mService.mLooper->removeFd(pendingReadsFd);
3022 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003023}
3024
Songchun Fan2570ec02020-10-08 17:22:33 -07003025void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003026 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07003027 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003028 mHealthCheckParams = healthCheckParams;
3029 mHealthListener = std::move(healthListener);
3030 if (!mHealthListener) {
3031 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07003032 }
3033}
3034
Songchun Fan6944f1e2020-11-06 15:24:24 -08003035static std::string toHexString(const RawMetadata& metadata) {
3036 int n = metadata.size();
3037 std::string res(n * 2, '\0');
3038 // Same as incfs::toString(fileId)
3039 static constexpr char kHexChar[] = "0123456789abcdef";
3040 for (int i = 0; i < n; ++i) {
3041 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
3042 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
3043 }
3044 return res;
3045}
3046
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003047void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003048 dprintf(fd, " dataLoader: {\n");
3049 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08003050 dprintf(fd, " currentStatusTs: %lldmcs\n",
3051 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003052 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
3053 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003054 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003055 dprintf(fd, " health: {\n");
3056 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3057 dprintf(fd, " base: %lldmcs (%lld)\n",
3058 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3059 (long long)mHealthBase.kernelTsUs);
3060 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3061 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3062 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3063 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003064 dprintf(fd, " lastPendingReads: \n");
3065 const auto control = mService.mIncFs->openMount(mHealthPath);
3066 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003067 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003068 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3069 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3070 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3071 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3072 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003073 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
3074 (long long)(elapsedMcs(mPreviousBindTs, Clock::now()) / 1000000),
3075 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003076 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003077 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003078 dprintf(fd, " dataLoaderParams: {\n");
3079 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3080 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3081 dprintf(fd, " className: %s\n", params.className.c_str());
3082 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3083 dprintf(fd, " }\n");
3084 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003085}
3086
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003087void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3088 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003089}
3090
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003091binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3092 bool enableReadLogs, int32_t* _aidl_return) {
3093 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3094 return binder::Status::ok();
3095}
3096
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003097FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3098 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3099}
3100
Songchun Fan3c82a302019-11-29 14:23:45 -08003101} // namespace android::incremental