blob: 757c9dec06ed6adf1f63af59fe3e3c112bbc2f8c [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;
Alex Buynytskyy4bafd4d2021-06-08 16:35:39 -070092
93 // How long should we wait till dataLoader reports destroyed.
94 static constexpr auto destroyTimeout = 60s;
95
96 static constexpr auto anyStatus = INT_MIN;
Songchun Fan3c82a302019-11-29 14:23:45 -080097};
98
99static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700100 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -0800101 return c;
102}
103
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -0700104static bool isPageAligned(IncFsSize s) {
105 return (s & (Constants::blockSize - 1)) == 0;
106}
107
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700108static bool getAlwaysEnableReadTimeoutsForSystemDataLoaders() {
109 return android::base::
110 GetBoolProperty("debug.incremental.always_enable_read_timeouts_for_system_dataloaders",
111 true);
112}
113
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700114static bool getEnforceReadLogsMaxIntervalForSystemDataLoaders() {
115 return android::base::GetBoolProperty("debug.incremental.enforce_readlogs_max_interval_for_"
116 "system_dataloaders",
117 false);
118}
119
120static Seconds getReadLogsMaxInterval() {
121 constexpr int limit = duration_cast<Seconds>(Constants::readLogsMaxInterval).count();
122 int readlogs_max_interval_secs =
123 std::min(limit,
124 android::base::GetIntProperty<
125 int>("debug.incremental.readlogs_max_interval_sec", limit));
126 return Seconds{readlogs_max_interval_secs};
127}
128
Songchun Fan3c82a302019-11-29 14:23:45 -0800129template <base::LogSeverity level = base::ERROR>
130bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
131 auto cstr = path::c_str(name);
132 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800133 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800134 PLOG(level) << "Can't create directory '" << name << '\'';
135 return false;
136 }
137 struct stat st;
138 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
139 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
140 return false;
141 }
142 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800143 if (::chmod(cstr, mode)) {
144 PLOG(level) << "Changing permission failed for '" << name << '\'';
145 return false;
146 }
147
Songchun Fan3c82a302019-11-29 14:23:45 -0800148 return true;
149}
150
151static std::string toMountKey(std::string_view path) {
152 if (path.empty()) {
153 return "@none";
154 }
155 if (path == "/"sv) {
156 return "@root";
157 }
158 if (path::isAbsolute(path)) {
159 path.remove_prefix(1);
160 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700161 if (path.size() > 16) {
162 path = path.substr(0, 16);
163 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800164 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700165 std::replace_if(
166 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
167 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800168}
169
170static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
171 std::string_view path) {
172 auto mountKey = toMountKey(path);
173 const auto prefixSize = mountKey.size();
174 for (int counter = 0; counter < 1000;
175 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
176 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800177 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800178 return {mountKey, mountRoot};
179 }
180 }
181 return {};
182}
183
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700184template <class Map>
185typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
186 const auto nextIt = map.upper_bound(path);
187 if (nextIt == map.begin()) {
188 return map.end();
189 }
190 const auto suspectIt = std::prev(nextIt);
191 if (!path::startsWith(path, suspectIt->first)) {
192 return map.end();
193 }
194 return suspectIt;
195}
196
197static base::unique_fd dup(base::borrowed_fd fd) {
198 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
199 return base::unique_fd(res);
200}
201
Songchun Fan3c82a302019-11-29 14:23:45 -0800202template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700203static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800204 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800205 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800206 ProtoMessage message;
207 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
208}
209
210static bool isValidMountTarget(std::string_view path) {
211 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
212}
213
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700214std::string makeUniqueName(std::string_view prefix) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800215 static constexpr auto uuidStringSize = 36;
216
217 uuid_t guid;
218 uuid_generate(guid);
219
220 std::string name;
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700221 const auto prefixSize = prefix.size();
Songchun Fan3c82a302019-11-29 14:23:45 -0800222 name.reserve(prefixSize + uuidStringSize);
223
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700224 name = prefix;
Songchun Fan3c82a302019-11-29 14:23:45 -0800225 name.resize(prefixSize + uuidStringSize);
226 uuid_unparse(guid, name.data() + prefixSize);
227
228 return name;
229}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700230
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700231std::string makeBindMdName() {
232 return makeUniqueName(constants().mountpointMdPrefix);
233}
234
Alex Buynytskyy04035452020-06-06 20:15:58 -0700235static bool checkReadLogsDisabledMarker(std::string_view root) {
236 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
237 struct stat st;
238 return (::stat(markerPath, &st) == 0);
239}
240
Songchun Fan3c82a302019-11-29 14:23:45 -0800241} // namespace
242
243IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700244 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700245 dataLoaderStub->cleanupResources();
246 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700247 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700248 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800249 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
250 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700251 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800252 incrementalService.mVold->unmountIncFs(target);
253 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700254 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800255 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
256 cleanupFilesystem(root);
257}
258
259auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800260 std::string name;
261 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
262 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
263 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800264 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
265 constants().storagePrefix.data(), id, no);
266 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800267 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800268 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800269 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
270 } else if (err != EEXIST) {
271 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
272 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800273 }
274 }
275 nextStorageDirNo = 0;
276 return storages.end();
277}
278
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700279template <class Func>
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700280static auto makeCleanup(Func&& f) requires(!std::is_lvalue_reference_v<Func>) {
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -0700281 // ok to move a 'forwarding' reference here as lvalues are disabled anyway
282 auto deleter = [f = std::move(f)](auto) { // NOLINT
283 f();
284 };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700285 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700286 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
287}
288
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700289static auto openDir(const char* dir) {
290 struct DirCloser {
291 void operator()(DIR* d) const noexcept { ::closedir(d); }
292 };
293 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700294}
295
296static auto openDir(std::string_view dir) {
297 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800298}
299
300static int rmDirContent(const char* path) {
301 auto dir = openDir(path);
302 if (!dir) {
303 return -EINVAL;
304 }
305 while (auto entry = ::readdir(dir.get())) {
306 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
307 continue;
308 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700309 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800310 if (entry->d_type == DT_DIR) {
311 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
312 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
313 return err;
314 }
315 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
316 PLOG(WARNING) << "Failed to rmdir " << fullPath;
317 return err;
318 }
319 } else {
320 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
321 PLOG(WARNING) << "Failed to delete " << fullPath;
322 return err;
323 }
324 }
325 }
326 return 0;
327}
328
Songchun Fan3c82a302019-11-29 14:23:45 -0800329void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800330 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800331 ::rmdir(path::join(root, constants().backing).c_str());
332 ::rmdir(path::join(root, constants().mount).c_str());
333 ::rmdir(path::c_str(root));
334}
335
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700336void IncrementalService::IncFsMount::setFlag(StorageFlags flag, bool value) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700337 if (value) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700338 flags |= flag;
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700339 } else {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700340 flags &= ~flag;
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700341 }
342}
343
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800344IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800345 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800346 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800347 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700348 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700349 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700350 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700351 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700352 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700353 mFs(sm.getFs()),
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800354 mClock(sm.getClock()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800355 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700356 CHECK(mVold) << "Vold service is unavailable";
357 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
358 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
359 CHECK(mJni) << "JNI is unavailable";
360 CHECK(mLooper) << "Looper is unavailable";
361 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700362 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700363 CHECK(mFs) << "Fs is unavailable";
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800364 CHECK(mClock) << "Clock is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700365
366 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700367 mJobProcessor = std::thread([this]() {
368 mJni->initializeForCurrentThread();
369 runJobProcessing();
370 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700371 mCmdLooperThread = std::thread([this]() {
372 mJni->initializeForCurrentThread();
373 runCmdLooper();
374 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700375
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700376 const auto mountedRootNames = adoptMountedInstances();
377 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800378}
379
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700380IncrementalService::~IncrementalService() {
381 {
382 std::lock_guard lock(mJobMutex);
383 mRunning = false;
384 }
385 mJobCondition.notify_all();
386 mJobProcessor.join();
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -0700387 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700388 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700389 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700390 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700391 // Ensure that mounts are destroyed while the service is still valid.
392 mBindsByPath.clear();
393 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700394}
Songchun Fan3c82a302019-11-29 14:23:45 -0800395
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700396static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800397 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800398 case IncrementalService::BindKind::Temporary:
399 return "Temporary";
400 case IncrementalService::BindKind::Permanent:
401 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800402 }
403}
404
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700405template <class Duration>
Songchun Fan0dc77722021-05-03 17:13:52 -0700406static int64_t elapsedMcs(Duration start, Duration end) {
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700407 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
408}
409
Songchun Fan0dc77722021-05-03 17:13:52 -0700410int64_t IncrementalService::elapsedUsSinceMonoTs(uint64_t monoTsUs) {
411 const auto now = mClock->now();
412 const auto nowUs = static_cast<uint64_t>(
413 duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count());
Songchun Fand48a25e2021-04-30 09:50:58 -0700414 return nowUs - monoTsUs;
415}
416
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800417void IncrementalService::onDump(int fd) {
418 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -0700419 dprintf(fd, "IncFs features: 0x%x\n", int(mIncFs->features()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800420 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
421
422 std::unique_lock l(mLock);
423
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700424 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800425 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700426 std::unique_lock ll(ifs->lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700427 const IncFsMount& mnt = *ifs;
428 dprintf(fd, " [%d]: {\n", id);
429 if (id != mnt.mountId) {
430 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
431 } else {
432 dprintf(fd, " mountId: %d\n", mnt.mountId);
433 dprintf(fd, " root: %s\n", mnt.root.c_str());
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700434 const auto& metricsInstanceName = ifs->metricsKey;
Songchun Fanf949c372021-04-27 11:26:25 -0700435 dprintf(fd, " metrics instance name: %s\n", path::c_str(metricsInstanceName).get());
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700436 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyyf2af4d82021-04-07 16:58:15 -0700437 dprintf(fd, " flags: %d\n", int(mnt.flags));
438 if (mnt.startLoadingTs.time_since_epoch() == Clock::duration::zero()) {
439 dprintf(fd, " not loading\n");
440 } else {
441 dprintf(fd, " startLoading: %llds\n",
442 (long long)(elapsedMcs(mnt.startLoadingTs, Clock::now()) / 1000000));
443 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700444 if (mnt.dataLoaderStub) {
445 mnt.dataLoaderStub->onDump(fd);
446 } else {
447 dprintf(fd, " dataLoader: null\n");
448 }
449 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
450 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700451 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700452 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()).getProgress() *
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800453 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700454 }
455 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800456
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700457 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
458 for (auto&& [target, bind] : mnt.bindPoints) {
459 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
460 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
461 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
462 dprintf(fd, " kind: %s\n", toString(bind.kind));
463 }
464 dprintf(fd, " }\n");
Songchun Fanf949c372021-04-27 11:26:25 -0700465
466 dprintf(fd, " incfsMetrics: {\n");
467 const auto incfsMetrics = mIncFs->getMetrics(metricsInstanceName);
468 if (incfsMetrics) {
469 dprintf(fd, " readsDelayedMin: %d\n", incfsMetrics.value().readsDelayedMin);
470 dprintf(fd, " readsDelayedMinUs: %lld\n",
471 (long long)incfsMetrics.value().readsDelayedMinUs);
472 dprintf(fd, " readsDelayedPending: %d\n",
473 incfsMetrics.value().readsDelayedPending);
474 dprintf(fd, " readsDelayedPendingUs: %lld\n",
475 (long long)incfsMetrics.value().readsDelayedPendingUs);
476 dprintf(fd, " readsFailedHashVerification: %d\n",
477 incfsMetrics.value().readsFailedHashVerification);
478 dprintf(fd, " readsFailedOther: %d\n", incfsMetrics.value().readsFailedOther);
479 dprintf(fd, " readsFailedTimedOut: %d\n",
480 incfsMetrics.value().readsFailedTimedOut);
481 } else {
482 dprintf(fd, " Metrics not available. Errno: %d\n", errno);
483 }
484 dprintf(fd, " }\n");
Songchun Fand48a25e2021-04-30 09:50:58 -0700485
486 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
487 const auto errorNo = errno;
488 dprintf(fd, " lastReadError: {\n");
489 if (lastReadError) {
490 if (lastReadError->timestampUs == 0) {
491 dprintf(fd, " No read errors.\n");
492 } else {
493 dprintf(fd, " fileId: %s\n",
494 IncFsWrapper::toString(lastReadError->id).c_str());
495 dprintf(fd, " time: %llu microseconds ago\n",
496 (unsigned long long)elapsedUsSinceMonoTs(lastReadError->timestampUs));
497 dprintf(fd, " blockIndex: %d\n", lastReadError->block);
498 dprintf(fd, " errno: %d\n", lastReadError->errorNo);
499 }
500 } else {
501 dprintf(fd, " Info not available. Errno: %d\n", errorNo);
502 }
503 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800504 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700505 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800506 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700507 dprintf(fd, "}\n");
508 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800509 for (auto&& [target, mountPairIt] : mBindsByPath) {
510 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700511 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
512 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
513 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
514 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800515 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700516 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800517}
518
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800519bool IncrementalService::needStartDataLoaderLocked(IncFsMount& ifs) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700520 if (!ifs.dataLoaderStub) {
521 return false;
522 }
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700523 if (ifs.dataLoaderStub->isSystemDataLoader()) {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800524 return true;
525 }
526
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700527 return mIncFs->isEverythingFullyLoaded(ifs.control) == incfs::LoadingState::MissingBlocks;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800528}
529
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700530void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800531 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700532 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800533 }
534
535 std::vector<IfsMountPtr> mounts;
536 {
537 std::lock_guard l(mLock);
538 mounts.reserve(mMounts.size());
539 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700540 std::unique_lock ll(ifs->lock);
541
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -0800542 if (ifs->mountId != id) {
543 continue;
544 }
545
546 if (needStartDataLoaderLocked(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800547 mounts.push_back(ifs);
548 }
549 }
550 }
551
Alex Buynytskyy69941662020-04-11 21:40:37 -0700552 if (mounts.empty()) {
553 return;
554 }
555
Songchun Fan3c82a302019-11-29 14:23:45 -0800556 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700557 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800558 for (auto&& ifs : mounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700559 std::unique_lock l(ifs->lock);
560 if (ifs->dataLoaderStub) {
561 ifs->dataLoaderStub->requestStart();
562 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800563 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800564 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800565}
566
567auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
568 for (;;) {
569 if (mNextId == kMaxStorageId) {
570 mNextId = 0;
571 }
572 auto id = ++mNextId;
573 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
574 if (inserted) {
575 return it;
576 }
577 }
578}
579
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700580StorageId IncrementalService::createStorage(std::string_view mountPoint,
581 content::pm::DataLoaderParamsParcel dataLoaderParams,
582 CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800583 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
584 if (!path::isAbsolute(mountPoint)) {
585 LOG(ERROR) << "path is not absolute: " << mountPoint;
586 return kInvalidStorageId;
587 }
588
589 auto mountNorm = path::normalize(mountPoint);
590 {
591 const auto id = findStorageId(mountNorm);
592 if (id != kInvalidStorageId) {
593 if (options & CreateOptions::OpenExisting) {
594 LOG(INFO) << "Opened existing storage " << id;
595 return id;
596 }
597 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
598 return kInvalidStorageId;
599 }
600 }
601
602 if (!(options & CreateOptions::CreateNew)) {
603 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
604 return kInvalidStorageId;
605 }
606
607 if (!path::isEmptyDir(mountNorm)) {
608 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
609 return kInvalidStorageId;
610 }
611 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
612 if (mountRoot.empty()) {
613 LOG(ERROR) << "Bad mount point";
614 return kInvalidStorageId;
615 }
616 // Make sure the code removes all crap it may create while still failing.
617 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
618 auto firstCleanupOnFailure =
619 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
620
621 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800622 const auto backing = path::join(mountRoot, constants().backing);
623 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800624 return kInvalidStorageId;
625 }
626
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700627 std::string metricsKey;
Songchun Fan3c82a302019-11-29 14:23:45 -0800628 IncFsMount::Control control;
629 {
630 std::lock_guard l(mMountOperationLock);
631 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800632
633 if (auto err = rmDirContent(backing.c_str())) {
634 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
635 return kInvalidStorageId;
636 }
637 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
638 return kInvalidStorageId;
639 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800640 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
641 return kInvalidStorageId;
642 }
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700643 metricsKey = makeUniqueName(mountKey);
644 auto status = mVold->mountIncFs(backing, mountTarget, 0, metricsKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800645 if (!status.isOk()) {
646 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
647 return kInvalidStorageId;
648 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800649 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
650 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800651 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
652 return kInvalidStorageId;
653 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800654 int cmd = controlParcel.cmd.release().release();
655 int pendingReads = controlParcel.pendingReads.release().release();
656 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800657 int blocksWritten =
658 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
659 control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -0800660 }
661
662 std::unique_lock l(mLock);
663 const auto mountIt = getStorageSlotLocked();
664 const auto mountId = mountIt->first;
665 l.unlock();
666
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -0700667 auto ifs = std::make_shared<IncFsMount>(std::move(mountRoot), std::move(metricsKey), mountId,
668 std::move(control), *this);
Songchun Fan3c82a302019-11-29 14:23:45 -0800669 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
670 // is the removal of the |ifs|.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700671 (void)firstCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800672
673 auto secondCleanup = [this, &l](auto itPtr) {
674 if (!l.owns_lock()) {
675 l.lock();
676 }
677 mMounts.erase(*itPtr);
678 };
679 auto secondCleanupOnFailure =
680 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
681
682 const auto storageIt = ifs->makeStorage(ifs->mountId);
683 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800684 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800685 return kInvalidStorageId;
686 }
687
688 {
689 metadata::Mount m;
690 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700691 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700692 m.mutable_loader()->set_package_name(std::move(dataLoaderParams.packageName));
693 m.mutable_loader()->set_class_name(std::move(dataLoaderParams.className));
694 m.mutable_loader()->set_arguments(std::move(dataLoaderParams.arguments));
Songchun Fan3c82a302019-11-29 14:23:45 -0800695 const auto metadata = m.SerializeAsString();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800696 if (auto err =
697 mIncFs->makeFile(ifs->control,
698 path::join(ifs->root, constants().mount,
699 constants().infoMdName),
700 0777, idFromMetadata(metadata),
701 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800702 LOG(ERROR) << "Saving mount metadata failed: " << -err;
703 return kInvalidStorageId;
704 }
705 }
706
707 const auto bk =
708 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800709 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
710 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800711 err < 0) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800712 LOG(ERROR) << "Adding bind mount failed: " << -err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800713 return kInvalidStorageId;
714 }
715
716 // Done here as well, all data structures are in good state.
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -0700717 (void)secondCleanupOnFailure.release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800718
Songchun Fan3c82a302019-11-29 14:23:45 -0800719 mountIt->second = std::move(ifs);
720 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700721
Songchun Fan3c82a302019-11-29 14:23:45 -0800722 LOG(INFO) << "created storage " << mountId;
723 return mountId;
724}
725
726StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
727 StorageId linkedStorage,
728 IncrementalService::CreateOptions options) {
729 if (!isValidMountTarget(mountPoint)) {
730 LOG(ERROR) << "Mount point is invalid or missing";
731 return kInvalidStorageId;
732 }
733
734 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700735 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800736 if (!ifs) {
737 LOG(ERROR) << "Ifs unavailable";
738 return kInvalidStorageId;
739 }
740
741 const auto mountIt = getStorageSlotLocked();
742 const auto storageId = mountIt->first;
743 const auto storageIt = ifs->makeStorage(storageId);
744 if (storageIt == ifs->storages.end()) {
745 LOG(ERROR) << "Can't create a new storage";
746 mMounts.erase(mountIt);
747 return kInvalidStorageId;
748 }
749
750 l.unlock();
751
752 const auto bk =
753 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800754 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
755 std::string(storageIt->second.name), path::normalize(mountPoint),
756 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800757 err < 0) {
758 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700759 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
760 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800761 return kInvalidStorageId;
762 }
763
764 mountIt->second = ifs;
765 return storageId;
766}
767
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700768bool IncrementalService::startLoading(StorageId storageId,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700769 content::pm::DataLoaderParamsParcel dataLoaderParams,
770 DataLoaderStatusListener statusListener,
771 const StorageHealthCheckParams& healthCheckParams,
772 StorageHealthListener healthListener,
773 std::vector<PerUidReadTimeouts> perUidReadTimeouts) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800774 // Per Uid timeouts.
775 if (!perUidReadTimeouts.empty()) {
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -0700776 setUidReadTimeouts(storageId, std::move(perUidReadTimeouts));
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800777 }
778
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700779 IfsMountPtr ifs;
780 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800781
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700782 // Re-initialize DataLoader.
783 {
784 ifs = getIfs(storageId);
785 if (!ifs) {
786 return false;
787 }
788
789 std::unique_lock l(ifs->lock);
790 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
791 }
792
793 if (dataLoaderStub) {
794 dataLoaderStub->cleanupResources();
795 dataLoaderStub = {};
796 }
797
798 {
799 std::unique_lock l(ifs->lock);
800 if (ifs->dataLoaderStub) {
801 LOG(INFO) << "Skipped data loader stub creation because it already exists";
802 return false;
803 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700804
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700805 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams), std::move(statusListener),
806 healthCheckParams, std::move(healthListener));
807 CHECK(ifs->dataLoaderStub);
808 dataLoaderStub = ifs->dataLoaderStub;
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700809
810 // Disable long read timeouts for non-system dataloaders.
811 // To be re-enabled after installation is complete.
812 ifs->setReadTimeoutsRequested(dataLoaderStub->isSystemDataLoader() &&
813 getAlwaysEnableReadTimeoutsForSystemDataLoaders());
814 applyStorageParamsLocked(*ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700815 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800816
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700817 if (dataLoaderStub->isSystemDataLoader() &&
818 !getEnforceReadLogsMaxIntervalForSystemDataLoaders()) {
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700819 // Readlogs from system dataloader (adb) can always be collected.
820 ifs->startLoadingTs = TimePoint::max();
821 } else {
822 // Assign time when installation wants the DL to start streaming.
823 const auto startLoadingTs = mClock->now();
824 ifs->startLoadingTs = startLoadingTs;
825 // Setup a callback to disable the readlogs after max interval.
Alex Buynytskyybcb2fe0c2021-03-23 13:02:24 -0700826 addTimedJob(*mTimedQueue, storageId, getReadLogsMaxInterval(),
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700827 [this, storageId, startLoadingTs]() {
828 const auto ifs = getIfs(storageId);
829 if (!ifs) {
830 LOG(WARNING) << "Can't disable the readlogs, invalid storageId: "
831 << storageId;
832 return;
833 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700834 std::unique_lock l(ifs->lock);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700835 if (ifs->startLoadingTs != startLoadingTs) {
836 LOG(INFO) << "Can't disable the readlogs, timestamp mismatch (new "
837 "installation?): "
838 << storageId;
839 return;
840 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700841 disableReadLogsLocked(*ifs);
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -0700842 });
843 }
844
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800845 return dataLoaderStub->requestStart();
846}
847
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700848void IncrementalService::onInstallationComplete(StorageId storage) {
849 IfsMountPtr ifs = getIfs(storage);
850 if (!ifs) {
851 return;
852 }
853
854 // Always enable long read timeouts after installation is complete.
855 std::unique_lock l(ifs->lock);
856 ifs->setReadTimeoutsRequested(true);
857 applyStorageParamsLocked(*ifs);
858}
859
Songchun Fan3c82a302019-11-29 14:23:45 -0800860IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
861 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700862 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800863}
864
865StorageId IncrementalService::findStorageId(std::string_view path) const {
866 std::lock_guard l(mLock);
867 auto it = findStorageLocked(path);
868 if (it == mBindsByPath.end()) {
869 return kInvalidStorageId;
870 }
871 return it->second->second.storage;
872}
873
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800874void IncrementalService::disallowReadLogs(StorageId storageId) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700875 const auto ifs = getIfs(storageId);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700876 if (!ifs) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800877 LOG(ERROR) << "disallowReadLogs failed, invalid storageId: " << storageId;
Alex Buynytskyy04035452020-06-06 20:15:58 -0700878 return;
879 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700880
881 std::unique_lock l(ifs->lock);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800882 if (!ifs->readLogsAllowed()) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700883 return;
884 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800885 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -0700886
887 const auto metadata = constants().readLogsDisabledMarkerName;
888 if (auto err = mIncFs->makeFile(ifs->control,
889 path::join(ifs->root, constants().mount,
890 constants().readLogsDisabledMarkerName),
891 0777, idFromMetadata(metadata), {})) {
892 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
893 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
894 return;
895 }
896
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700897 disableReadLogsLocked(*ifs);
Alex Buynytskyy04035452020-06-06 20:15:58 -0700898}
899
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700900int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
901 const auto ifs = getIfs(storageId);
902 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700903 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700904 return -EINVAL;
905 }
906
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700907 std::string packageName;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700908
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700909 {
910 std::unique_lock l(ifs->lock);
911 if (!enableReadLogs) {
912 return disableReadLogsLocked(*ifs);
913 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700914
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700915 if (!ifs->readLogsAllowed()) {
916 LOG(ERROR) << "enableReadLogs failed, readlogs disallowed for storageId: " << storageId;
917 return -EPERM;
918 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700919
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700920 if (!ifs->dataLoaderStub) {
921 // This should never happen - only DL can call enableReadLogs.
922 LOG(ERROR) << "enableReadLogs failed: invalid state";
923 return -EPERM;
924 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700925
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700926 // Check installation time.
927 const auto now = mClock->now();
928 const auto startLoadingTs = ifs->startLoadingTs;
929 if (startLoadingTs <= now && now - startLoadingTs > getReadLogsMaxInterval()) {
930 LOG(ERROR)
931 << "enableReadLogs failed, readlogs can't be enabled at this time, storageId: "
932 << storageId;
933 return -EPERM;
934 }
935
936 packageName = ifs->dataLoaderStub->params().packageName;
937 ifs->setReadLogsRequested(true);
938 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700939
940 // Check loader usage stats permission and apop.
941 if (auto status =
942 mAppOpsManager->checkPermission(kLoaderUsageStats, kOpUsage, packageName.c_str());
943 !status.isOk()) {
944 LOG(ERROR) << " Permission: " << kLoaderUsageStats
945 << " check failed: " << status.toString8();
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700946 return fromBinderStatus(status);
947 }
948
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700949 // Check multiuser permission.
950 if (auto status =
951 mAppOpsManager->checkPermission(kInteractAcrossUsers, nullptr, packageName.c_str());
952 !status.isOk()) {
953 LOG(ERROR) << " Permission: " << kInteractAcrossUsers
954 << " check failed: " << status.toString8();
955 return fromBinderStatus(status);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700956 }
957
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700958 {
959 std::unique_lock l(ifs->lock);
960 if (!ifs->readLogsRequested()) {
961 return 0;
962 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700963 if (auto status = applyStorageParamsLocked(*ifs); status != 0) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700964 return status;
965 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700966 }
967
968 registerAppOpsCallback(packageName);
969
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700970 return 0;
971}
972
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700973int IncrementalService::disableReadLogsLocked(IncFsMount& ifs) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -0700974 ifs.setReadLogsRequested(false);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700975 return applyStorageParamsLocked(ifs);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700976}
977
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700978int IncrementalService::applyStorageParamsLocked(IncFsMount& ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700979 os::incremental::IncrementalFileSystemControlParcel control;
980 control.cmd.reset(dup(ifs.control.cmd()));
981 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700982 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700983 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700984 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700985 }
986
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700987 bool enableReadLogs = ifs.readLogsRequested();
988 bool enableReadTimeouts = ifs.readTimeoutsRequested();
989
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700990 std::lock_guard l(mMountOperationLock);
Songchun Fanf6c65bb2021-05-10 16:17:30 -0700991 auto status = mVold->setIncFsMountOptions(control, enableReadLogs, enableReadTimeouts,
992 ifs.metricsKey);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800993 if (status.isOk()) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700994 // Store states.
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800995 ifs.setReadLogsEnabled(enableReadLogs);
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700996 ifs.setReadTimeoutsEnabled(enableReadTimeouts);
Alex Buynytskyycb163f92021-03-18 21:21:27 -0700997 } else {
998 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800999 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001000 return status.isOk() ? 0 : fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -07001001}
1002
Songchun Fan3c82a302019-11-29 14:23:45 -08001003void IncrementalService::deleteStorage(StorageId storageId) {
1004 const auto ifs = getIfs(storageId);
1005 if (!ifs) {
1006 return;
1007 }
1008 deleteStorage(*ifs);
1009}
1010
1011void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
1012 std::unique_lock l(ifs.lock);
1013 deleteStorageLocked(ifs, std::move(l));
1014}
1015
1016void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
1017 std::unique_lock<std::mutex>&& ifsLock) {
1018 const auto storages = std::move(ifs.storages);
1019 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
1020 const auto bindPoints = ifs.bindPoints;
1021 ifsLock.unlock();
1022
1023 std::lock_guard l(mLock);
1024 for (auto&& [id, _] : storages) {
1025 if (id != ifs.mountId) {
1026 mMounts.erase(id);
1027 }
1028 }
1029 for (auto&& [path, _] : bindPoints) {
1030 mBindsByPath.erase(path);
1031 }
1032 mMounts.erase(ifs.mountId);
1033}
1034
1035StorageId IncrementalService::openStorage(std::string_view pathInMount) {
1036 if (!path::isAbsolute(pathInMount)) {
1037 return kInvalidStorageId;
1038 }
1039
1040 return findStorageId(path::normalize(pathInMount));
1041}
1042
Songchun Fan3c82a302019-11-29 14:23:45 -08001043IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
1044 std::lock_guard l(mLock);
1045 return getIfsLocked(storage);
1046}
1047
1048const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
1049 auto it = mMounts.find(storage);
1050 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001051 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -07001052 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -08001053 }
1054 return it->second;
1055}
1056
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001057int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
1058 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001059 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001060 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001061 return -EINVAL;
1062 }
1063
1064 const auto ifs = getIfs(storage);
1065 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001066 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001067 return -EINVAL;
1068 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001069
Songchun Fan3c82a302019-11-29 14:23:45 -08001070 std::unique_lock l(ifs->lock);
1071 const auto storageInfo = ifs->storages.find(storage);
1072 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001073 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -08001074 return -EINVAL;
1075 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001076 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001077 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001078 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001079 return -EINVAL;
1080 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001081 l.unlock();
1082 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001083 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
1084 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -08001085}
1086
1087int IncrementalService::unbind(StorageId storage, std::string_view target) {
1088 if (!path::isAbsolute(target)) {
1089 return -EINVAL;
1090 }
1091
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001092 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -08001093
1094 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
1095 // otherwise there's a chance to unmount something completely unrelated
1096 const auto norm = path::normalize(target);
1097 std::unique_lock l(mLock);
1098 const auto storageIt = mBindsByPath.find(norm);
1099 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
1100 return -EINVAL;
1101 }
1102 const auto bindIt = storageIt->second;
1103 const auto storageId = bindIt->second.storage;
1104 const auto ifs = getIfsLocked(storageId);
1105 if (!ifs) {
1106 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
1107 << " is missing";
1108 return -EFAULT;
1109 }
1110 mBindsByPath.erase(storageIt);
1111 l.unlock();
1112
1113 mVold->unmountIncFs(bindIt->first);
1114 std::unique_lock l2(ifs->lock);
1115 if (ifs->bindPoints.size() <= 1) {
1116 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -07001117 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -08001118 } else {
1119 const std::string savedFile = std::move(bindIt->second.savedFilename);
1120 ifs->bindPoints.erase(bindIt);
1121 l2.unlock();
1122 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001123 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -08001124 }
1125 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001126
Songchun Fan3c82a302019-11-29 14:23:45 -08001127 return 0;
1128}
1129
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001130std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001131 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001132 std::string_view path) const {
1133 if (!path::isAbsolute(path)) {
1134 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001135 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001136 auto normPath = path::normalize(path);
1137 if (path::startsWith(normPath, storageIt->second.name)) {
1138 return normPath;
1139 }
1140 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001141 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
1142 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001143 return {};
1144 }
1145 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001146}
1147
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001148std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001149 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001150 std::unique_lock l(ifs.lock);
1151 const auto storageInfo = ifs.storages.find(storage);
1152 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001153 return {};
1154 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001155 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001156}
1157
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001158int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001159 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001160 const auto ifs = getIfs(storage);
1161 if (!ifs) {
1162 return -EINVAL;
1163 }
1164 if (data.size() > params.size) {
1165 LOG(ERROR) << "Bad data size - bigger than file size";
1166 return -EINVAL;
1167 }
1168 if (!data.empty() && data.size() != params.size) {
1169 // Writing a page is an irreversible operation, and it can't be updated with additional
1170 // data later. Check that the last written page is complete, or we may break the file.
1171 if (!isPageAligned(data.size())) {
1172 LOG(ERROR) << "Bad data size - tried to write half a page?";
Songchun Fan54c6aed2020-01-31 16:52:41 -08001173 return -EINVAL;
1174 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001175 }
1176 const std::string normPath = normalizePathToStorage(*ifs, storage, path);
1177 if (normPath.empty()) {
1178 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
1179 return -EINVAL;
1180 }
1181 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy98a3c8f2021-05-12 13:25:38 -07001182 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile [" << normPath
1183 << "]: " << err;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001184 return err;
1185 }
1186 if (params.size > 0) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001187 if (auto err = mIncFs->reserveSpace(ifs->control, id, params.size)) {
1188 if (err != -EOPNOTSUPP) {
1189 LOG(ERROR) << "Failed to reserve space for a new file: " << err;
1190 (void)mIncFs->unlink(ifs->control, normPath);
1191 return err;
1192 } else {
1193 LOG(WARNING) << "Reserving space for backing file isn't supported, "
1194 "may run out of disk later";
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001195 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001196 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001197 if (!data.empty()) {
1198 if (auto err = setFileContent(ifs, id, path, data); err) {
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001199 (void)mIncFs->unlink(ifs->control, normPath);
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001200 return err;
1201 }
1202 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001203 }
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001204 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001205}
1206
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001207int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001208 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001209 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001210 if (normPath.empty()) {
1211 return -EINVAL;
1212 }
1213 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001214 }
1215 return -EINVAL;
1216}
1217
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001218int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001219 const auto ifs = getIfs(storageId);
1220 if (!ifs) {
1221 return -EINVAL;
1222 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001223 return makeDirs(*ifs, storageId, path, mode);
1224}
1225
1226int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
1227 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -08001228 std::string normPath = normalizePathToStorage(ifs, storageId, path);
1229 if (normPath.empty()) {
1230 return -EINVAL;
1231 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001232 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -08001233}
1234
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001235int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
1236 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001237 std::unique_lock l(mLock);
1238 auto ifsSrc = getIfsLocked(sourceStorageId);
1239 if (!ifsSrc) {
1240 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -08001241 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001242 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
1243 return -EINVAL;
1244 }
1245 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001246 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
1247 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001248 if (normOldPath.empty() || normNewPath.empty()) {
1249 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
1250 return -EINVAL;
1251 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001252 if (auto err = mIncFs->link(ifsSrc->control, normOldPath, normNewPath); err < 0) {
1253 PLOG(ERROR) << "Failed to link " << oldPath << "[" << normOldPath << "]"
1254 << " to " << newPath << "[" << normNewPath << "]";
1255 return err;
1256 }
1257 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -08001258}
1259
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001260int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001261 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001262 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -08001263 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001264 }
1265 return -EINVAL;
1266}
1267
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001268int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
1269 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001270 std::string&& target, BindKind kind,
1271 std::unique_lock<std::mutex>& mainLock) {
1272 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001273 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -08001274 return -EINVAL;
1275 }
1276
1277 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001278 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -08001279 if (kind != BindKind::Temporary) {
1280 metadata::BindPoint bp;
1281 bp.set_storage_id(storage);
1282 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -08001283 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -08001284 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -08001285 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -08001286 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -08001287 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001288 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
1289 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
1290 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001291 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001292 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -08001293 return int(node);
1294 }
1295 }
1296
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001297 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
1298 std::move(target), kind, mainLock);
1299 if (res) {
1300 mIncFs->unlink(ifs.control, metadataFullPath);
1301 }
1302 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -08001303}
1304
1305int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001306 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -08001307 std::string&& target, BindKind kind,
1308 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001309 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001310 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001311 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -08001312 if (!status.isOk()) {
1313 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
1314 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
1315 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
1316 : status.serviceSpecificErrorCode() == 0
1317 ? -EFAULT
1318 : status.serviceSpecificErrorCode()
1319 : -EIO;
1320 }
1321 }
1322
1323 if (!mainLock.owns_lock()) {
1324 mainLock.lock();
1325 }
1326 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001327 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1328 std::move(target), kind);
1329 return 0;
1330}
1331
1332void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1333 std::string&& metadataName, std::string&& source,
1334 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001335 const auto [it, _] =
1336 ifs.bindPoints.insert_or_assign(target,
1337 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001338 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001339 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001340}
1341
1342RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1343 const auto ifs = getIfs(storage);
1344 if (!ifs) {
1345 return {};
1346 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001347 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001348 if (normPath.empty()) {
1349 return {};
1350 }
1351 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001352}
1353
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001354RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001355 const auto ifs = getIfs(storage);
1356 if (!ifs) {
1357 return {};
1358 }
1359 return mIncFs->getMetadata(ifs->control, node);
1360}
1361
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001362void IncrementalService::setUidReadTimeouts(StorageId storage,
1363 std::vector<PerUidReadTimeouts>&& perUidReadTimeouts) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001364 using microseconds = std::chrono::microseconds;
1365 using milliseconds = std::chrono::milliseconds;
1366
1367 auto maxPendingTimeUs = microseconds(0);
1368 for (const auto& timeouts : perUidReadTimeouts) {
1369 maxPendingTimeUs = std::max(maxPendingTimeUs, microseconds(timeouts.maxPendingTimeUs));
1370 }
1371 if (maxPendingTimeUs < Constants::minPerUidTimeout) {
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07001372 LOG(ERROR) << "Skip setting read timeouts (maxPendingTime < Constants::minPerUidTimeout): "
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001373 << duration_cast<milliseconds>(maxPendingTimeUs).count() << "ms < "
1374 << Constants::minPerUidTimeout.count() << "ms";
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001375 return;
1376 }
1377
1378 const auto ifs = getIfs(storage);
1379 if (!ifs) {
Alex Buynytskyy07694ed2021-01-27 06:58:55 -08001380 LOG(ERROR) << "Setting read timeouts failed: invalid storage id: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001381 return;
1382 }
1383
1384 if (auto err = mIncFs->setUidReadTimeouts(ifs->control, perUidReadTimeouts); err < 0) {
1385 LOG(ERROR) << "Setting read timeouts failed: " << -err;
1386 return;
1387 }
1388
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001389 const auto timeout = Clock::now() + maxPendingTimeUs - Constants::perUidTimeoutOffset;
1390 addIfsStateCallback(storage, [this, timeout](StorageId storageId, IfsState state) -> bool {
1391 if (checkUidReadTimeouts(storageId, state, timeout)) {
1392 return true;
1393 }
1394 clearUidReadTimeouts(storageId);
1395 return false;
1396 });
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001397}
1398
1399void IncrementalService::clearUidReadTimeouts(StorageId storage) {
1400 const auto ifs = getIfs(storage);
1401 if (!ifs) {
1402 return;
1403 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001404 mIncFs->setUidReadTimeouts(ifs->control, {});
1405}
1406
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001407bool IncrementalService::checkUidReadTimeouts(StorageId storage, IfsState state,
1408 Clock::time_point timeLimit) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001409 if (Clock::now() >= timeLimit) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001410 // Reached maximum timeout.
1411 return false;
1412 }
1413 if (state.error) {
1414 // Something is wrong, abort.
1415 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001416 }
1417
1418 // Still loading?
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001419 if (state.fullyLoaded && !state.readLogsEnabled) {
1420 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001421 }
1422
1423 const auto timeLeft = timeLimit - Clock::now();
1424 if (timeLeft < Constants::progressUpdateInterval) {
1425 // Don't bother.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001426 return false;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001427 }
1428
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001429 return true;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001430}
1431
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001432std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1433 std::unordered_set<std::string_view> mountedRootNames;
1434 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1435 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1436 for (auto [source, target] : binds) {
1437 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1438 LOG(INFO) << " " << path::join(root, source);
1439 }
1440
1441 // Ensure it's a kind of a mount that's managed by IncrementalService
1442 if (path::basename(root) != constants().mount ||
1443 path::basename(backingDir) != constants().backing) {
1444 return;
1445 }
1446 const auto expectedRoot = path::dirname(root);
1447 if (path::dirname(backingDir) != expectedRoot) {
1448 return;
1449 }
1450 if (path::dirname(expectedRoot) != mIncrementalDir) {
1451 return;
1452 }
1453 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1454 return;
1455 }
1456
1457 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1458
1459 // make sure we clean up the mount if it happens to be a bad one.
1460 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1461 auto cleanupFiles = makeCleanup([&]() {
1462 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1463 IncFsMount::cleanupFilesystem(expectedRoot);
1464 });
1465 auto cleanupMounts = makeCleanup([&]() {
1466 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1467 for (auto&& [_, target] : binds) {
1468 mVold->unmountIncFs(std::string(target));
1469 }
1470 mVold->unmountIncFs(std::string(root));
1471 });
1472
1473 auto control = mIncFs->openMount(root);
1474 if (!control) {
1475 LOG(INFO) << "failed to open mount " << root;
1476 return;
1477 }
1478
1479 auto mountRecord =
1480 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1481 path::join(root, constants().infoMdName));
1482 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1483 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1484 return;
1485 }
1486
1487 auto mountId = mountRecord.storage().id();
1488 mNextId = std::max(mNextId, mountId + 1);
1489
1490 DataLoaderParamsParcel dataLoaderParams;
1491 {
1492 const auto& loader = mountRecord.loader();
1493 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1494 dataLoaderParams.packageName = loader.package_name();
1495 dataLoaderParams.className = loader.class_name();
1496 dataLoaderParams.arguments = loader.arguments();
1497 }
1498
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001499 // Not way to obtain a real sysfs key at this point - metrics will stop working after "soft"
1500 // reboot.
1501 std::string metricsKey{};
1502 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), std::move(metricsKey),
1503 mountId, std::move(control), *this);
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001504 (void)cleanupFiles.release(); // ifs will take care of that now
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001505
Alex Buynytskyy04035452020-06-06 20:15:58 -07001506 // Check if marker file present.
1507 if (checkReadLogsDisabledMarker(root)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001508 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001509 }
1510
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001511 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1512 auto d = openDir(root);
1513 while (auto e = ::readdir(d.get())) {
1514 if (e->d_type == DT_REG) {
1515 auto name = std::string_view(e->d_name);
1516 if (name.starts_with(constants().mountpointMdPrefix)) {
1517 permanentBindPoints
1518 .emplace_back(name,
1519 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1520 ifs->control,
1521 path::join(root,
1522 name)));
1523 if (permanentBindPoints.back().second.dest_path().empty() ||
1524 permanentBindPoints.back().second.source_subdir().empty()) {
1525 permanentBindPoints.pop_back();
1526 mIncFs->unlink(ifs->control, path::join(root, name));
1527 } else {
1528 LOG(INFO) << "Permanent bind record: '"
1529 << permanentBindPoints.back().second.source_subdir() << "'->'"
1530 << permanentBindPoints.back().second.dest_path() << "'";
1531 }
1532 }
1533 } else if (e->d_type == DT_DIR) {
1534 if (e->d_name == "."sv || e->d_name == ".."sv) {
1535 continue;
1536 }
1537 auto name = std::string_view(e->d_name);
1538 if (name.starts_with(constants().storagePrefix)) {
1539 int storageId;
1540 const auto res =
1541 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1542 name.data() + name.size(), storageId);
1543 if (res.ec != std::errc{} || *res.ptr != '_') {
1544 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1545 << "' for mount " << expectedRoot;
1546 continue;
1547 }
1548 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1549 if (!inserted) {
1550 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1551 << " for mount " << expectedRoot;
1552 continue;
1553 }
1554 ifs->storages.insert_or_assign(storageId,
1555 IncFsMount::Storage{path::join(root, name)});
1556 mNextId = std::max(mNextId, storageId + 1);
1557 }
1558 }
1559 }
1560
1561 if (ifs->storages.empty()) {
1562 LOG(WARNING) << "No valid storages in mount " << root;
1563 return;
1564 }
1565
1566 // now match the mounted directories with what we expect to have in the metadata
1567 {
1568 std::unique_lock l(mLock, std::defer_lock);
1569 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1570 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1571 [&, bindRecord = bindRecord](auto&& bind) {
1572 return bind.second == bindRecord.dest_path() &&
1573 path::join(root, bind.first) ==
1574 bindRecord.source_subdir();
1575 });
1576 if (mountedIt != binds.end()) {
1577 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1578 << " to mount " << mountedIt->first;
1579 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1580 std::move(*bindRecord.mutable_source_subdir()),
1581 std::move(*bindRecord.mutable_dest_path()),
1582 BindKind::Permanent);
1583 if (mountedIt != binds.end() - 1) {
1584 std::iter_swap(mountedIt, binds.end() - 1);
1585 }
1586 binds = binds.first(binds.size() - 1);
1587 } else {
1588 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1589 << ", mounting";
1590 // doesn't exist - try mounting back
1591 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1592 std::move(*bindRecord.mutable_source_subdir()),
1593 std::move(*bindRecord.mutable_dest_path()),
1594 BindKind::Permanent, l)) {
1595 mIncFs->unlink(ifs->control, metadataFile);
1596 }
1597 }
1598 }
1599 }
1600
1601 // if anything stays in |binds| those are probably temporary binds; system restarted since
1602 // they were mounted - so let's unmount them all.
1603 for (auto&& [source, target] : binds) {
1604 if (source.empty()) {
1605 continue;
1606 }
1607 mVold->unmountIncFs(std::string(target));
1608 }
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07001609 (void)cleanupMounts.release(); // ifs now manages everything
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001610
1611 if (ifs->bindPoints.empty()) {
1612 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1613 deleteStorage(*ifs);
1614 return;
1615 }
1616
1617 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1618 CHECK(ifs->dataLoaderStub);
1619
1620 mountedRootNames.insert(path::basename(ifs->root));
1621
1622 // not locking here at all: we're still in the constructor, no other calls can happen
1623 mMounts[ifs->mountId] = std::move(ifs);
1624 });
1625
1626 return mountedRootNames;
1627}
1628
1629void IncrementalService::mountExistingImages(
1630 const std::unordered_set<std::string_view>& mountedRootNames) {
1631 auto dir = openDir(mIncrementalDir);
1632 if (!dir) {
1633 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1634 return;
1635 }
1636 while (auto entry = ::readdir(dir.get())) {
1637 if (entry->d_type != DT_DIR) {
1638 continue;
1639 }
1640 std::string_view name = entry->d_name;
1641 if (!name.starts_with(constants().mountKeyPrefix)) {
1642 continue;
1643 }
1644 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001645 continue;
1646 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001647 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001648 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001649 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001650 }
1651 }
1652}
1653
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001654bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001655 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001656 const auto backing = path::join(root, constants().backing);
Songchun Fanf949c372021-04-27 11:26:25 -07001657 std::string mountKey(path::basename(path::dirname(mountTarget)));
Songchun Fan3c82a302019-11-29 14:23:45 -08001658
Songchun Fan3c82a302019-11-29 14:23:45 -08001659 IncrementalFileSystemControlParcel controlParcel;
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001660 auto metricsKey = makeUniqueName(mountKey);
1661 auto status = mVold->mountIncFs(backing, mountTarget, 0, metricsKey, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001662 if (!status.isOk()) {
1663 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1664 return false;
1665 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001666
1667 int cmd = controlParcel.cmd.release().release();
1668 int pendingReads = controlParcel.pendingReads.release().release();
1669 int logs = controlParcel.log.release().release();
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001670 int blocksWritten =
1671 controlParcel.blocksWritten ? controlParcel.blocksWritten->release().release() : -1;
1672 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs, blocksWritten);
Songchun Fan3c82a302019-11-29 14:23:45 -08001673
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07001674 auto ifs = std::make_shared<IncFsMount>(std::string(root), std::move(metricsKey), -1,
1675 std::move(control), *this);
Songchun Fan3c82a302019-11-29 14:23:45 -08001676
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001677 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1678 path::join(mountTarget, constants().infoMdName));
1679 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001680 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1681 return false;
1682 }
1683
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001684 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001685 mNextId = std::max(mNextId, ifs->mountId + 1);
1686
Alex Buynytskyy04035452020-06-06 20:15:58 -07001687 // Check if marker file present.
1688 if (checkReadLogsDisabledMarker(mountTarget)) {
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08001689 ifs->disallowReadLogs();
Alex Buynytskyy04035452020-06-06 20:15:58 -07001690 }
1691
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001692 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001693 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001694 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001695 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001696 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001697 dataLoaderParams.packageName = loader.package_name();
1698 dataLoaderParams.className = loader.class_name();
1699 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001700 }
1701
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001702 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001703 CHECK(ifs->dataLoaderStub);
1704
Songchun Fan3c82a302019-11-29 14:23:45 -08001705 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001706 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001707 while (auto e = ::readdir(d.get())) {
1708 if (e->d_type == DT_REG) {
1709 auto name = std::string_view(e->d_name);
1710 if (name.starts_with(constants().mountpointMdPrefix)) {
1711 bindPoints.emplace_back(name,
1712 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1713 ifs->control,
1714 path::join(mountTarget,
1715 name)));
1716 if (bindPoints.back().second.dest_path().empty() ||
1717 bindPoints.back().second.source_subdir().empty()) {
1718 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001719 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001720 }
1721 }
1722 } else if (e->d_type == DT_DIR) {
1723 if (e->d_name == "."sv || e->d_name == ".."sv) {
1724 continue;
1725 }
1726 auto name = std::string_view(e->d_name);
1727 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001728 int storageId;
1729 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1730 name.data() + name.size(), storageId);
1731 if (res.ec != std::errc{} || *res.ptr != '_') {
1732 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1733 << root;
1734 continue;
1735 }
1736 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001737 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001738 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001739 << " for mount " << root;
1740 continue;
1741 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001742 ifs->storages.insert_or_assign(storageId,
1743 IncFsMount::Storage{
1744 path::join(root, constants().mount, name)});
1745 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001746 }
1747 }
1748 }
1749
1750 if (ifs->storages.empty()) {
1751 LOG(WARNING) << "No valid storages in mount " << root;
1752 return false;
1753 }
1754
1755 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001756 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001757 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001758 for (auto&& bp : bindPoints) {
1759 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1760 std::move(*bp.second.mutable_source_subdir()),
1761 std::move(*bp.second.mutable_dest_path()),
1762 BindKind::Permanent, l);
1763 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001764 }
1765
1766 if (bindCount == 0) {
1767 LOG(WARNING) << "No valid bind points for mount " << root;
1768 deleteStorage(*ifs);
1769 return false;
1770 }
1771
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001772 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001773 mMounts[ifs->mountId] = std::move(ifs);
1774 return true;
1775}
1776
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001777void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001778 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001779 while (mRunning.load(std::memory_order_relaxed)) {
1780 mLooper->pollAll(kTimeoutMsecs);
1781 }
1782}
1783
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001784void IncrementalService::trimReservedSpaceV1(const IncFsMount& ifs) {
1785 mIncFs->forEachFile(ifs.control, [this](auto&& control, auto&& fileId) {
1786 if (mIncFs->isFileFullyLoaded(control, fileId) == incfs::LoadingState::Full) {
1787 mIncFs->reserveSpace(control, fileId, -1);
1788 }
1789 return true;
1790 });
1791}
1792
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001793void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001794 DataLoaderStatusListener&& statusListener,
1795 const StorageHealthCheckParams& healthCheckParams,
1796 StorageHealthListener&& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001797 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001798 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001799 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1800 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1801 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -08001802 if (ifs.control.blocksWritten() >= 0) {
1803 fsControlParcel.incremental->blocksWritten.emplace(dup(ifs.control.blocksWritten()));
1804 }
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001805 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001806
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001807 ifs.dataLoaderStub =
1808 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07001809 std::move(statusListener), healthCheckParams,
1810 std::move(healthListener), path::join(ifs.root, constants().mount));
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001811
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -07001812 // pre-v2 IncFS doesn't do automatic reserved space trimming - need to run it manually
1813 if (!(mIncFs->features() & incfs::Features::v2)) {
1814 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1815 if (!state.fullyLoaded) {
1816 return true;
1817 }
1818
1819 const auto ifs = getIfs(storageId);
1820 if (!ifs) {
1821 return false;
1822 }
1823 trimReservedSpaceV1(*ifs);
1824 return false;
1825 });
1826 }
1827
Alex Buynytskyycb163f92021-03-18 21:21:27 -07001828 addIfsStateCallback(ifs.mountId, [this](StorageId storageId, IfsState state) -> bool {
1829 if (!state.fullyLoaded || state.readLogsEnabled) {
1830 return true;
1831 }
1832
1833 DataLoaderStubPtr dataLoaderStub;
1834 {
1835 const auto ifs = getIfs(storageId);
1836 if (!ifs) {
1837 return false;
1838 }
1839
1840 std::unique_lock l(ifs->lock);
1841 dataLoaderStub = std::exchange(ifs->dataLoaderStub, nullptr);
1842 }
1843
1844 if (dataLoaderStub) {
1845 dataLoaderStub->cleanupResources();
1846 }
1847
1848 return false;
1849 });
Songchun Fan3c82a302019-11-29 14:23:45 -08001850}
1851
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001852template <class Duration>
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08001853static constexpr auto castToMs(Duration d) {
1854 return std::chrono::duration_cast<std::chrono::milliseconds>(d);
1855}
1856
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001857// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001858// Lib files should be placed next to the APK file in the following matter:
1859// Example:
1860// /path/to/base.apk
1861// /path/to/lib/arm/first.so
1862// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001863bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1864 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001865 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001866 auto start = Clock::now();
1867
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001868 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001869 if (!ifs) {
1870 LOG(ERROR) << "Invalid storage " << storage;
1871 return false;
1872 }
1873
Songchun Fanc8975312020-07-13 12:14:37 -07001874 const auto targetLibPathRelativeToStorage =
1875 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1876 libDirRelativePath);
1877
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001878 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001879 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1880 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001881 << " errno: " << res;
1882 return false;
1883 }
1884
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001885 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001886 ZipArchiveHandle zipFileHandle;
1887 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001888 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1889 return false;
1890 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001891
1892 // Need a shared pointer: will be passing it into all unpacking jobs.
1893 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001894 void* cookie = nullptr;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001895 const auto libFilePrefix = path::join(constants().libDir, abi) += "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001896 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001897 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1898 return false;
1899 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001900 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001901 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1902
1903 auto openZipTs = Clock::now();
1904
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001905 auto mapFiles = (mIncFs->features() & incfs::Features::v2);
1906 incfs::FileId sourceId;
1907 if (mapFiles) {
1908 sourceId = mIncFs->getFileId(ifs->control, apkFullPath);
1909 if (!incfs::isValidFileId(sourceId)) {
1910 LOG(WARNING) << "Error getting IncFS file ID for apk path '" << apkFullPath
1911 << "', mapping disabled";
1912 mapFiles = false;
1913 }
1914 }
1915
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001916 std::vector<Job> jobQueue;
1917 ZipEntry entry;
1918 std::string_view fileName;
1919 while (!Next(cookie, &entry, &fileName)) {
1920 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001921 continue;
1922 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001923
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001924 const auto entryUncompressed = entry.method == kCompressStored;
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -07001925 const auto entryPageAligned = isPageAligned(entry.offset);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001926
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001927 if (!extractNativeLibs) {
1928 // ensure the file is properly aligned and unpacked
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001929 if (!entryUncompressed) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001930 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1931 return false;
1932 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001933 if (!entryPageAligned) {
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001934 LOG(WARNING) << "Library " << fileName
1935 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1936 << entry.offset;
1937 return false;
1938 }
1939 continue;
1940 }
1941
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001942 auto startFileTs = Clock::now();
1943
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001944 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001945 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001946 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001947 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001948 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001949 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001950 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1951 << "; skipping extraction, spent "
1952 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1953 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001954 continue;
1955 }
1956
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001957 if (mapFiles && entryUncompressed && entryPageAligned && entry.uncompressed_length > 0) {
1958 incfs::NewMappedFileParams mappedFileParams = {
1959 .sourceId = sourceId,
1960 .sourceOffset = entry.offset,
1961 .size = entry.uncompressed_length,
1962 };
1963
1964 if (auto res = mIncFs->makeMappedFile(ifs->control, targetLibPathAbsolute, 0755,
1965 mappedFileParams);
1966 res == 0) {
1967 if (perfLoggingEnabled()) {
1968 auto doneTs = Clock::now();
1969 LOG(INFO) << "incfs: Mapped " << libName << ": "
1970 << elapsedMcs(startFileTs, doneTs) << "mcs";
1971 }
1972 continue;
1973 } else {
1974 LOG(WARNING) << "Failed to map file for: '" << targetLibPath << "' errno: " << res
1975 << "; falling back to full extraction";
1976 }
1977 }
1978
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001979 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001980 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001981 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001982 .signature = {},
1983 // Metadata of the new lib file is its relative path
1984 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1985 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001986 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -08001987 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0755, libFileId,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001988 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001989 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001990 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001991 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001992 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001993
1994 auto makeFileTs = Clock::now();
1995
Songchun Fanafaf6e92020-03-18 14:12:20 -07001996 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001997 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001998 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001999 LOG(INFO) << "incfs: Extracted " << libName
2000 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002001 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07002002 continue;
2003 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002004
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002005 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
2006 libFileId, libPath = std::move(targetLibPath),
2007 makeFileTs]() mutable {
2008 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002009 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002010
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002011 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002012 auto prepareJobTs = Clock::now();
2013 LOG(INFO) << "incfs: Processed " << libName << ": "
2014 << elapsedMcs(startFileTs, prepareJobTs)
2015 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
2016 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002017 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002018 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002019
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002020 auto processedTs = Clock::now();
2021
2022 if (!jobQueue.empty()) {
2023 {
2024 std::lock_guard lock(mJobMutex);
2025 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002026 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002027 if (existingJobs.empty()) {
2028 existingJobs = std::move(jobQueue);
2029 } else {
2030 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
2031 std::move_iterator(jobQueue.end()));
2032 }
2033 }
2034 }
2035 mJobCondition.notify_all();
2036 }
2037
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002038 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002039 auto end = Clock::now();
2040 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
2041 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
2042 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002043 << " make files: " << elapsedMcs(openZipTs, processedTs)
2044 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07002045 }
2046
2047 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08002048}
2049
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002050void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
2051 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002052 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002053 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002054 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002055 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07002056 return;
2057 }
2058
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002059 auto startedTs = Clock::now();
2060
2061 // Write extracted data to new file
2062 // NOTE: don't zero-initialize memory, it may take a while for nothing
2063 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
2064 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002065 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002066 return;
2067 }
2068
2069 auto extractFileTs = Clock::now();
2070
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002071 if (setFileContent(ifs, libFileId, debugLibPath,
2072 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002073 return;
2074 }
2075
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002076 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002077 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002078 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
2079 << entry.compressed_length << " -> " << entry.uncompressed_length
2080 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002081 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
2082 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002083 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002084 }
2085}
2086
2087bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002088 struct WaitPrinter {
2089 const Clock::time_point startTs = Clock::now();
2090 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002091 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002092 const auto endTs = Clock::now();
2093 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
2094 << elapsedMcs(startTs, endTs) << "mcs";
2095 }
2096 }
2097 } waitPrinter;
2098
2099 MountId mount;
2100 {
2101 auto ifs = getIfs(storage);
2102 if (!ifs) {
2103 return true;
2104 }
2105 mount = ifs->mountId;
2106 }
2107
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002108 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002109 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002110 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002111 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002112 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002113 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002114}
2115
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07002116int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
2117 std::string_view debugFilePath,
2118 std::span<const uint8_t> data) const {
2119 auto startTs = Clock::now();
2120
2121 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
2122 if (!writeFd.ok()) {
2123 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
2124 << " errno: " << writeFd.get();
2125 return writeFd.get();
2126 }
2127
2128 const auto dataLength = data.size();
2129
2130 auto openFileTs = Clock::now();
2131 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
2132 std::vector<IncFsDataBlock> instructions(numBlocks);
2133 for (int i = 0; i < numBlocks; i++) {
2134 const auto blockSize = std::min<long>(constants().blockSize, data.size());
2135 instructions[i] = IncFsDataBlock{
2136 .fileFd = writeFd.get(),
2137 .pageIndex = static_cast<IncFsBlockIndex>(i),
2138 .compression = INCFS_COMPRESSION_KIND_NONE,
2139 .kind = INCFS_BLOCK_KIND_DATA,
2140 .dataSize = static_cast<uint32_t>(blockSize),
2141 .data = reinterpret_cast<const char*>(data.data()),
2142 };
2143 data = data.subspan(blockSize);
2144 }
2145 auto prepareInstsTs = Clock::now();
2146
2147 size_t res = mIncFs->writeBlocks(instructions);
2148 if (res != instructions.size()) {
2149 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
2150 return res;
2151 }
2152
2153 if (perfLoggingEnabled()) {
2154 auto endTs = Clock::now();
2155 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
2156 << " bytes): " << elapsedMcs(startTs, endTs)
2157 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
2158 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
2159 << " write: " << elapsedMcs(prepareInstsTs, endTs);
2160 }
2161
2162 return 0;
2163}
2164
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002165incfs::LoadingState IncrementalService::isFileFullyLoaded(StorageId storage,
2166 std::string_view filePath) const {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002167 std::unique_lock l(mLock);
2168 const auto ifs = getIfsLocked(storage);
2169 if (!ifs) {
2170 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002171 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002172 }
2173 const auto storageInfo = ifs->storages.find(storage);
2174 if (storageInfo == ifs->storages.end()) {
2175 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002176 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002177 }
2178 l.unlock();
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002179 return mIncFs->isFileFullyLoaded(ifs->control, filePath);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002180}
2181
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002182incfs::LoadingState IncrementalService::isMountFullyLoaded(StorageId storage) const {
2183 const auto ifs = getIfs(storage);
2184 if (!ifs) {
2185 LOG(ERROR) << "isMountFullyLoaded failed, invalid storageId: " << storage;
2186 return incfs::LoadingState(-EINVAL);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002187 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -07002188 return mIncFs->isEverythingFullyLoaded(ifs->control);
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07002189}
2190
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002191IncrementalService::LoadingProgress IncrementalService::getLoadingProgress(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002192 StorageId storage) const {
Songchun Fan374f7652020-08-20 08:40:29 -07002193 std::unique_lock l(mLock);
2194 const auto ifs = getIfsLocked(storage);
2195 if (!ifs) {
2196 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002197 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002198 }
2199 const auto storageInfo = ifs->storages.find(storage);
2200 if (storageInfo == ifs->storages.end()) {
2201 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002202 return {-EINVAL, -EINVAL};
Songchun Fan374f7652020-08-20 08:40:29 -07002203 }
2204 l.unlock();
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002205 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
Songchun Fan374f7652020-08-20 08:40:29 -07002206}
2207
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002208IncrementalService::LoadingProgress IncrementalService::getLoadingProgressFromPath(
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002209 const IncFsMount& ifs, std::string_view storagePath) const {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002210 ssize_t totalBlocks = 0, filledBlocks = 0, error = 0;
2211 mFs->listFilesRecursive(storagePath, [&, this](auto filePath) {
Songchun Fan374f7652020-08-20 08:40:29 -07002212 const auto [filledBlocksCount, totalBlocksCount] =
2213 mIncFs->countFilledBlocks(ifs.control, filePath);
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002214 if (filledBlocksCount == -EOPNOTSUPP || filledBlocksCount == -ENOTSUP ||
2215 filledBlocksCount == -ENOENT) {
2216 // a kind of a file that's not really being loaded, e.g. a mapped range
2217 // an older IncFS used to return ENOENT in this case, so handle it the same way
2218 return true;
2219 }
Songchun Fan374f7652020-08-20 08:40:29 -07002220 if (filledBlocksCount < 0) {
2221 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002222 << ", errno: " << filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002223 error = filledBlocksCount;
2224 return false;
Songchun Fan374f7652020-08-20 08:40:29 -07002225 }
2226 totalBlocks += totalBlocksCount;
2227 filledBlocks += filledBlocksCount;
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002228 return true;
2229 });
Songchun Fan374f7652020-08-20 08:40:29 -07002230
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -08002231 return error ? LoadingProgress{error, error} : LoadingProgress{filledBlocks, totalBlocks};
Songchun Fan374f7652020-08-20 08:40:29 -07002232}
2233
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002234bool IncrementalService::updateLoadingProgress(StorageId storage,
2235 StorageLoadingProgressListener&& progressListener) {
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002236 const auto progress = getLoadingProgress(storage);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002237 if (progress.isError()) {
Songchun Fana7098592020-09-03 11:45:53 -07002238 // Failed to get progress from incfs, abort.
2239 return false;
2240 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002241 progressListener->onStorageLoadingProgressChanged(storage, progress.getProgress());
2242 if (progress.fullyLoaded()) {
Songchun Fana7098592020-09-03 11:45:53 -07002243 // Stop updating progress once it is fully loaded
2244 return true;
2245 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -08002246 addTimedJob(*mProgressUpdateJobQueue, storage,
2247 Constants::progressUpdateInterval /* repeat after 1s */,
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002248 [storage, progressListener = std::move(progressListener), this]() mutable {
2249 updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002250 });
2251 return true;
2252}
2253
2254bool IncrementalService::registerLoadingProgressListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002255 StorageId storage, StorageLoadingProgressListener progressListener) {
2256 return updateLoadingProgress(storage, std::move(progressListener));
Songchun Fana7098592020-09-03 11:45:53 -07002257}
2258
2259bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
2260 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
2261}
2262
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002263bool IncrementalService::perfLoggingEnabled() {
2264 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
2265 return enabled;
2266}
2267
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002268void IncrementalService::runJobProcessing() {
2269 for (;;) {
2270 std::unique_lock lock(mJobMutex);
2271 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
2272 if (!mRunning) {
2273 return;
2274 }
2275
2276 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002277 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002278 auto queue = std::move(it->second);
2279 mJobQueue.erase(it);
2280 lock.unlock();
2281
2282 for (auto&& job : queue) {
2283 job();
2284 }
2285
2286 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07002287 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002288 lock.unlock();
2289 mJobCondition.notify_all();
2290 }
2291}
2292
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002293void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002294 sp<IAppOpsCallback> listener;
2295 {
2296 std::unique_lock lock{mCallbacksLock};
2297 auto& cb = mCallbackRegistered[packageName];
2298 if (cb) {
2299 return;
2300 }
2301 cb = new AppOpsListener(*this, packageName);
2302 listener = cb;
2303 }
2304
Yurii Zubrytskyida208012020-04-07 15:35:21 -07002305 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
2306 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002307}
2308
2309bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
2310 sp<IAppOpsCallback> listener;
2311 {
2312 std::unique_lock lock{mCallbacksLock};
2313 auto found = mCallbackRegistered.find(packageName);
2314 if (found == mCallbackRegistered.end()) {
2315 return false;
2316 }
2317 listener = found->second;
2318 mCallbackRegistered.erase(found);
2319 }
2320
2321 mAppOpsManager->stopWatchingMode(listener);
2322 return true;
2323}
2324
2325void IncrementalService::onAppOpChanged(const std::string& packageName) {
2326 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002327 return;
2328 }
2329
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002330 std::vector<IfsMountPtr> affected;
2331 {
2332 std::lock_guard l(mLock);
2333 affected.reserve(mMounts.size());
2334 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002335 std::unique_lock ll(ifs->lock);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002336 if (ifs->mountId == id && ifs->dataLoaderStub &&
2337 ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002338 affected.push_back(ifs);
2339 }
2340 }
2341 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002342 for (auto&& ifs : affected) {
Alex Buynytskyy50d83ff2021-03-23 22:37:02 -07002343 std::unique_lock ll(ifs->lock);
2344 disableReadLogsLocked(*ifs);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002345 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002346}
2347
Songchun Fana7098592020-09-03 11:45:53 -07002348bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
2349 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002350 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002351 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002352 }
Songchun Fana7098592020-09-03 11:45:53 -07002353 timedQueue.addJob(id, after, std::move(what));
2354 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002355}
2356
Songchun Fana7098592020-09-03 11:45:53 -07002357bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002358 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07002359 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002360 }
Songchun Fana7098592020-09-03 11:45:53 -07002361 timedQueue.removeJobs(id);
2362 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002363}
2364
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002365void IncrementalService::addIfsStateCallback(StorageId storageId, IfsStateCallback callback) {
2366 bool wasEmpty;
2367 {
2368 std::lock_guard l(mIfsStateCallbacksLock);
2369 wasEmpty = mIfsStateCallbacks.empty();
2370 mIfsStateCallbacks[storageId].emplace_back(std::move(callback));
2371 }
2372 if (wasEmpty) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002373 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002374 [this]() { processIfsStateCallbacks(); });
2375 }
2376}
2377
2378void IncrementalService::processIfsStateCallbacks() {
2379 StorageId storageId = kInvalidStorageId;
2380 std::vector<IfsStateCallback> local;
2381 while (true) {
2382 {
2383 std::lock_guard l(mIfsStateCallbacksLock);
2384 if (mIfsStateCallbacks.empty()) {
2385 return;
2386 }
2387 IfsStateCallbacks::iterator it;
2388 if (storageId == kInvalidStorageId) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002389 // First entry, initialize the |it|.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002390 it = mIfsStateCallbacks.begin();
2391 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002392 // Subsequent entries, update the |storageId|, and shift to the new one (not that
2393 // it guarantees much about updated items, but at least the loop will finish).
2394 it = mIfsStateCallbacks.lower_bound(storageId);
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002395 if (it == mIfsStateCallbacks.end()) {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002396 // Nothing else left, too bad.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002397 break;
2398 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002399 if (it->first != storageId) {
2400 local.clear(); // Was removed during processing, forget the old callbacks.
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002401 } else {
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002402 // Put the 'surviving' callbacks back into the map and advance the position.
2403 auto& callbacks = it->second;
2404 if (callbacks.empty()) {
2405 std::swap(callbacks, local);
2406 } else {
2407 callbacks.insert(callbacks.end(), std::move_iterator(local.begin()),
2408 std::move_iterator(local.end()));
2409 local.clear();
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002410 }
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002411 if (callbacks.empty()) {
2412 it = mIfsStateCallbacks.erase(it);
2413 if (mIfsStateCallbacks.empty()) {
2414 return;
2415 }
2416 } else {
2417 ++it;
2418 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002419 }
2420 }
2421
2422 if (it == mIfsStateCallbacks.end()) {
2423 break;
2424 }
2425
2426 storageId = it->first;
2427 auto& callbacks = it->second;
2428 if (callbacks.empty()) {
2429 // Invalid case, one extra lookup should be ok.
2430 continue;
2431 }
2432 std::swap(callbacks, local);
2433 }
2434
2435 processIfsStateCallbacks(storageId, local);
2436 }
2437
Yurii Zubrytskyi9acc9ac2021-03-24 00:48:24 -07002438 addTimedJob(*mTimedQueue, kAllStoragesId, Constants::progressUpdateInterval,
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002439 [this]() { processIfsStateCallbacks(); });
2440}
2441
2442void IncrementalService::processIfsStateCallbacks(StorageId storageId,
2443 std::vector<IfsStateCallback>& callbacks) {
2444 const auto state = isMountFullyLoaded(storageId);
2445 IfsState storageState = {};
2446 storageState.error = int(state) < 0;
2447 storageState.fullyLoaded = state == incfs::LoadingState::Full;
2448 if (storageState.fullyLoaded) {
2449 const auto ifs = getIfs(storageId);
2450 storageState.readLogsEnabled = ifs && ifs->readLogsEnabled();
2451 }
2452
2453 for (auto cur = callbacks.begin(); cur != callbacks.end();) {
2454 if ((*cur)(storageId, storageState)) {
2455 ++cur;
2456 } else {
2457 cur = callbacks.erase(cur);
2458 }
2459 }
2460}
2461
2462void IncrementalService::removeIfsStateCallbacks(StorageId storageId) {
2463 std::lock_guard l(mIfsStateCallbacksLock);
2464 mIfsStateCallbacks.erase(storageId);
2465}
2466
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002467void IncrementalService::getMetrics(StorageId storageId, android::os::PersistableBundle* result) {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002468 const auto ifs = getIfs(storageId);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002469 if (!ifs) {
Songchun Fan9471be52021-04-21 17:49:27 -07002470 LOG(ERROR) << "getMetrics failed, invalid storageId: " << storageId;
2471 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002472 }
Songchun Fan0dc77722021-05-03 17:13:52 -07002473 const auto& kMetricsReadLogsEnabled =
Songchun Fan9471be52021-04-21 17:49:27 -07002474 os::incremental::BnIncrementalService::METRICS_READ_LOGS_ENABLED();
Songchun Fan0dc77722021-05-03 17:13:52 -07002475 result->putBoolean(String16(kMetricsReadLogsEnabled.c_str()), ifs->readLogsEnabled() != 0);
Alex Buynytskyye76e1ef2021-05-07 14:50:02 -07002476 const auto incfsMetrics = mIncFs->getMetrics(ifs->metricsKey);
Songchun Fan0dc77722021-05-03 17:13:52 -07002477 if (incfsMetrics) {
2478 const auto& kMetricsTotalDelayedReads =
2479 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS();
2480 const auto totalDelayedReads =
2481 incfsMetrics->readsDelayedMin + incfsMetrics->readsDelayedPending;
2482 result->putInt(String16(kMetricsTotalDelayedReads.c_str()), totalDelayedReads);
2483 const auto& kMetricsTotalFailedReads =
2484 os::incremental::BnIncrementalService::METRICS_TOTAL_FAILED_READS();
2485 const auto totalFailedReads = incfsMetrics->readsFailedTimedOut +
2486 incfsMetrics->readsFailedHashVerification + incfsMetrics->readsFailedOther;
2487 result->putInt(String16(kMetricsTotalFailedReads.c_str()), totalFailedReads);
2488 const auto& kMetricsTotalDelayedReadsMillis =
2489 os::incremental::BnIncrementalService::METRICS_TOTAL_DELAYED_READS_MILLIS();
2490 const int64_t totalDelayedReadsMillis =
2491 (incfsMetrics->readsDelayedMinUs + incfsMetrics->readsDelayedPendingUs) / 1000;
2492 result->putLong(String16(kMetricsTotalDelayedReadsMillis.c_str()), totalDelayedReadsMillis);
2493 }
2494 const auto lastReadError = mIncFs->getLastReadError(ifs->control);
2495 if (lastReadError && lastReadError->timestampUs != 0) {
2496 const auto& kMetricsMillisSinceLastReadError =
2497 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_READ_ERROR();
2498 result->putLong(String16(kMetricsMillisSinceLastReadError.c_str()),
2499 (int64_t)elapsedUsSinceMonoTs(lastReadError->timestampUs) / 1000);
2500 const auto& kMetricsLastReadErrorNo =
2501 os::incremental::BnIncrementalService::METRICS_LAST_READ_ERROR_NUMBER();
2502 result->putInt(String16(kMetricsLastReadErrorNo.c_str()), lastReadError->errorNo);
Songchun Fan0d680162021-05-27 19:15:48 -07002503 const auto& kMetricsLastReadUid =
2504 os::incremental::BnIncrementalService::METRICS_LAST_READ_ERROR_UID();
2505 result->putInt(String16(kMetricsLastReadUid.c_str()), lastReadError->uid);
Songchun Fan0dc77722021-05-03 17:13:52 -07002506 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002507 std::unique_lock l(ifs->lock);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002508 if (!ifs->dataLoaderStub) {
Songchun Fan9471be52021-04-21 17:49:27 -07002509 return;
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002510 }
Songchun Fan9471be52021-04-21 17:49:27 -07002511 ifs->dataLoaderStub->getMetrics(result);
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002512}
2513
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002514IncrementalService::DataLoaderStub::DataLoaderStub(
2515 IncrementalService& service, MountId id, DataLoaderParamsParcel&& params,
2516 FileSystemControlParcel&& control, DataLoaderStatusListener&& statusListener,
2517 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener,
2518 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002519 : mService(service),
2520 mId(id),
2521 mParams(std::move(params)),
2522 mControl(std::move(control)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002523 mStatusListener(std::move(statusListener)),
2524 mHealthListener(std::move(healthListener)),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002525 mHealthPath(std::move(healthPath)),
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07002526 mHealthCheckParams(healthCheckParams) {
2527 if (mHealthListener && !isHealthParamsValid()) {
2528 mHealthListener = {};
2529 }
2530 if (!mHealthListener) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002531 // Disable advanced health check statuses.
2532 mHealthCheckParams.blockedTimeoutMs = -1;
2533 }
2534 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002535}
2536
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002537IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002538 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002539 cleanupResources();
2540 }
2541}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002542
2543void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002544 auto now = Clock::now();
2545 {
2546 std::unique_lock lock(mMutex);
2547 mHealthPath.clear();
2548 unregisterFromPendingReads();
2549 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07002550 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002551 }
Alex Buynytskyycb163f92021-03-18 21:21:27 -07002552 mService.removeIfsStateCallbacks(mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002553
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002554 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002555
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002556 {
2557 std::unique_lock lock(mMutex);
2558 mParams = {};
2559 mControl = {};
2560 mHealthControl = {};
2561 mHealthListener = {};
Alex Buynytskyy4bafd4d2021-06-08 16:35:39 -07002562 mStatusCondition.wait_until(lock, now + Constants::destroyTimeout, [this] {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002563 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
2564 });
2565 mStatusListener = {};
2566 mId = kInvalidStorageId;
2567 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002568}
2569
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002570sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
2571 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002572 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002573 if (!status.isOk()) {
2574 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
2575 return {};
2576 }
2577 if (!dataloader) {
2578 LOG(ERROR) << "DataLoader is null: " << status.toString8();
2579 return {};
2580 }
2581 return dataloader;
2582}
2583
Alex Buynytskyyd7aa3462021-03-14 22:20:20 -07002584bool IncrementalService::DataLoaderStub::isSystemDataLoader() const {
2585 return (params().packageName == Constants::systemPackage);
2586}
2587
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002588bool IncrementalService::DataLoaderStub::requestCreate() {
2589 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2590}
2591
2592bool IncrementalService::DataLoaderStub::requestStart() {
2593 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2594}
2595
2596bool IncrementalService::DataLoaderStub::requestDestroy() {
2597 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2598}
2599
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002600bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002601 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002602 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002603 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002604 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002605 return fsmStep();
2606}
2607
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002608void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002609 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002610 mTargetStatus = status;
2611 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002612 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002613 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002614}
2615
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002616std::optional<Milliseconds> IncrementalService::DataLoaderStub::needToBind() {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002617 std::unique_lock lock(mMutex);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002618
2619 const auto now = mService.mClock->now();
2620 const bool healthy = (mPreviousBindDelay == 0ms);
2621
2622 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_BINDING &&
2623 now - mCurrentStatusTs <= Constants::bindingTimeout) {
2624 LOG(INFO) << "Binding still in progress. "
2625 << (healthy ? "The DL is healthy/freshly bound, ok to retry for a few times."
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002626 : "Already unhealthy, don't do anything.")
2627 << " for storage " << mId;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002628 // Binding still in progress.
2629 if (!healthy) {
2630 // Already unhealthy, don't do anything.
2631 return {};
2632 }
2633 // The DL is healthy/freshly bound, ok to retry for a few times.
2634 if (now - mPreviousBindTs <= Constants::bindGracePeriod) {
2635 // Still within grace period.
2636 if (now - mCurrentStatusTs >= Constants::bindRetryInterval) {
2637 // Retry interval passed, retrying.
2638 mCurrentStatusTs = now;
2639 mPreviousBindDelay = 0ms;
2640 return 0ms;
2641 }
2642 return {};
2643 }
2644 // fallthrough, mark as unhealthy, and retry with delay
2645 }
2646
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002647 const auto previousBindTs = mPreviousBindTs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002648 mPreviousBindTs = now;
2649
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002650 const auto nonCrashingInterval =
2651 std::max(castToMs(now - previousBindTs - mPreviousBindDelay), 100ms);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002652 if (previousBindTs.time_since_epoch() == Clock::duration::zero() ||
2653 nonCrashingInterval > Constants::healthyDataLoaderUptime) {
2654 mPreviousBindDelay = 0ms;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002655 return 0ms;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002656 }
2657
2658 constexpr auto minBindDelayMs = castToMs(Constants::minBindDelay);
2659 constexpr auto maxBindDelayMs = castToMs(Constants::maxBindDelay);
2660
2661 const auto bindDelayMs =
2662 std::min(std::max(mPreviousBindDelay * Constants::bindDelayMultiplier, minBindDelayMs),
2663 maxBindDelayMs)
2664 .count();
2665 const auto bindDelayJitterRangeMs = bindDelayMs / Constants::bindDelayJitterDivider;
Yurii Zubrytskyi878714a2021-04-30 15:41:37 -07002666 // rand() is enough, not worth maintaining a full-blown <rand> object for delay jitter
2667 const auto bindDelayJitterMs = rand() % (bindDelayJitterRangeMs * 2) - // NOLINT
2668 bindDelayJitterRangeMs;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002669 mPreviousBindDelay = std::chrono::milliseconds(bindDelayMs + bindDelayJitterMs);
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002670 return mPreviousBindDelay;
2671}
2672
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002673bool IncrementalService::DataLoaderStub::bind() {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002674 const auto maybeBindDelay = needToBind();
2675 if (!maybeBindDelay) {
2676 LOG(DEBUG) << "Skipping bind to " << mParams.packageName << " because of pending bind.";
2677 return true;
2678 }
2679 const auto bindDelay = *maybeBindDelay;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002680 if (bindDelay > 1s) {
2681 LOG(INFO) << "Delaying bind to " << mParams.packageName << " by "
Alex Buynytskyy5ac55532021-03-25 12:33:15 -07002682 << bindDelay.count() / 1000 << "s"
2683 << " for storage " << mId;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002684 }
2685
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002686 bool result = false;
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08002687 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, bindDelay.count(),
2688 this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002689 if (!status.isOk() || !result) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002690 const bool healthy = (bindDelay == 0ms);
2691 LOG(ERROR) << "Failed to bind a data loader for mount " << id()
2692 << (healthy ? ", retrying." : "");
2693
2694 // Internal error, retry for healthy/new DLs.
2695 // Let needToBind migrate it to unhealthy after too many retries.
2696 if (healthy) {
2697 if (mService.addTimedJob(*mService.mTimedQueue, id(), Constants::bindRetryInterval,
2698 [this]() { fsmStep(); })) {
2699 // Mark as binding so that we know it's not the DL's fault.
2700 setCurrentStatus(IDataLoaderStatusListener::DATA_LOADER_BINDING);
2701 return true;
2702 }
2703 }
2704
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002705 return false;
2706 }
2707 return true;
2708}
2709
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002710bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002711 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002712 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002713 return false;
2714 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002715 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002716 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002717 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002718 return false;
2719 }
2720 return true;
2721}
2722
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002723bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002724 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002725 if (!dataloader) {
2726 return false;
2727 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002728 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002729 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002730 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002731 return false;
2732 }
2733 return true;
2734}
2735
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002736bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002737 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002738}
2739
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002740bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002741 if (!isValid()) {
2742 return false;
2743 }
2744
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002745 int currentStatus;
2746 int targetStatus;
2747 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002748 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002749 currentStatus = mCurrentStatus;
2750 targetStatus = mTargetStatus;
2751 }
2752
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002753 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002754
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002755 if (currentStatus == targetStatus) {
2756 return true;
2757 }
2758
2759 switch (targetStatus) {
2760 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002761 switch (currentStatus) {
Alex Buynytskyy4bafd4d2021-06-08 16:35:39 -07002762 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2763 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2764 destroy();
2765 // DataLoader is broken, just assume it's destroyed.
2766 compareAndSetCurrentStatus(currentStatus,
2767 IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2768 return true;
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002769 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyy4bafd4d2021-06-08 16:35:39 -07002770 compareAndSetCurrentStatus(currentStatus,
2771 IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002772 return true;
2773 default:
2774 return destroy();
2775 }
2776 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002777 }
2778 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2779 switch (currentStatus) {
2780 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2781 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2782 return start();
2783 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002784 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002785 }
2786 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2787 switch (currentStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002788 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002789 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2790 // Before binding need to make sure we are unbound.
2791 // Otherwise we'll get stuck binding.
Alex Buynytskyy4bafd4d2021-06-08 16:35:39 -07002792 destroy();
2793 // DataLoader is broken, just assume it's destroyed.
2794 compareAndSetCurrentStatus(currentStatus,
2795 IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2796 return true;
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002797 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002798 case IDataLoaderStatusListener::DATA_LOADER_BINDING:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002799 return bind();
2800 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002801 return create();
2802 }
2803 break;
2804 default:
2805 LOG(ERROR) << "Invalid target status: " << targetStatus
2806 << ", current status: " << currentStatus;
2807 break;
2808 }
2809 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002810}
2811
2812binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002813 if (!isValid()) {
2814 return binder::Status::
2815 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2816 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002817 if (id() != mountId) {
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002818 LOG(ERROR) << "onStatusChanged: mount ID mismatch: expected " << id()
2819 << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002820 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2821 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002822 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE ||
2823 newStatus == IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002824 // User-provided status, let's postpone the handling to avoid possible deadlocks.
2825 mService.addTimedJob(*mService.mTimedQueue, id(), Constants::userStatusDelay,
2826 [this, newStatus]() { setCurrentStatus(newStatus); });
2827 return binder::Status::ok();
2828 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002829
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002830 setCurrentStatus(newStatus);
2831 return binder::Status::ok();
2832}
2833
2834void IncrementalService::DataLoaderStub::setCurrentStatus(int newStatus) {
Alex Buynytskyy4bafd4d2021-06-08 16:35:39 -07002835 compareAndSetCurrentStatus(Constants::anyStatus, newStatus);
2836}
2837
2838void IncrementalService::DataLoaderStub::compareAndSetCurrentStatus(int expectedStatus,
2839 int newStatus) {
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002840 int oldStatus, oldTargetStatus, newTargetStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002841 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002842 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002843 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002844 if (mCurrentStatus == newStatus) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002845 return;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002846 }
Alex Buynytskyy4bafd4d2021-06-08 16:35:39 -07002847 if (expectedStatus != Constants::anyStatus && expectedStatus != mCurrentStatus) {
2848 return;
2849 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002850
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002851 oldStatus = mCurrentStatus;
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002852 oldTargetStatus = mTargetStatus;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002853 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002854
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08002855 // Change the status.
2856 mCurrentStatus = newStatus;
2857 mCurrentStatusTs = mService.mClock->now();
2858
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002859 switch (mCurrentStatus) {
2860 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2861 // Unavailable, retry.
2862 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2863 break;
2864 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE:
2865 // Unrecoverable, just unbind.
2866 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2867 break;
2868 default:
2869 break;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002870 }
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002871
2872 newTargetStatus = mTargetStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002873 }
2874
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002875 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyyde4b8232021-04-25 12:43:26 -07002876 << newStatus << " (target " << oldTargetStatus << " -> " << newTargetStatus << ")";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002877
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002878 if (listener) {
Alex Buynytskyy060c9d62021-02-18 20:55:17 -08002879 listener->onStatusChanged(id(), newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002880 }
2881
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002882 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002883
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002884 mStatusCondition.notify_all();
Songchun Fan3c82a302019-11-29 14:23:45 -08002885}
2886
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002887bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2888 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2889 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002890}
2891
Yurii Zubrytskyi883a27a2021-03-18 19:30:56 -07002892void IncrementalService::DataLoaderStub::onHealthStatus(const StorageHealthListener& healthListener,
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002893 int healthStatus) {
2894 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2895 if (healthListener) {
2896 healthListener->onHealthStatus(id(), healthStatus);
2897 }
Songchun Fan9471be52021-04-21 17:49:27 -07002898 mHealthStatus = healthStatus;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002899}
2900
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002901void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2902 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002903
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002904 int healthStatusToReport = -1;
2905 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002906
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002907 {
2908 std::unique_lock lock(mMutex);
2909 unregisterFromPendingReads();
2910
2911 healthListener = mHealthListener;
2912
2913 // Healthcheck depends on timestamp of the oldest pending read.
2914 // 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 -07002915 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2916 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002917 const auto now = Clock::now();
2918 const auto kernelTsUs = getOldestPendingReadTs();
2919 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002920 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2921 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002922 mHealthBase = {now, kernelTsUs};
2923 }
2924
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002925 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2926 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002927 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2928 registerForPendingReads();
2929 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2930 lock.unlock();
2931 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002932 return;
2933 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002934
2935 resetHealthControl();
2936
2937 // Always make sure the data loader is started.
2938 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2939
2940 // Skip any further processing if health check params are invalid.
2941 if (!isHealthParamsValid()) {
2942 LOG(DEBUG) << id()
2943 << ": Skip any further processing if health check params are invalid.";
2944 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2945 lock.unlock();
2946 onHealthStatus(healthListener, healthStatusToReport);
2947 // Triggering data loader start. This is a one-time action.
2948 fsmStep();
2949 return;
2950 }
2951
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002952 // Don't schedule timer job less than 500ms in advance.
2953 static constexpr auto kTolerance = 500ms;
2954
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002955 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2956 const auto unhealthyTimeout =
2957 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2958 const auto unhealthyMonitoring =
2959 std::max(1000ms,
2960 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2961
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002962 const auto delta = elapsedMsSinceKernelTs(now, kernelTsUs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002963
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002964 Milliseconds checkBackAfter;
2965 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002966 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002967 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002968 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002969 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002970 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002971 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002972 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2973 } else {
2974 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002975 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002976 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2977 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002978 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002979 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002980 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2981 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002982 }
2983
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002984 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002985 if (healthStatusToReport != -1) {
2986 onHealthStatus(healthListener, healthStatusToReport);
2987 }
2988
2989 fsmStep();
2990}
2991
Songchun Fan1b76ccf2021-02-24 22:25:59 +00002992Milliseconds IncrementalService::DataLoaderStub::elapsedMsSinceKernelTs(TimePoint now,
2993 BootClockTsUs kernelTsUs) {
2994 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2995 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2996 return std::chrono::duration_cast<Milliseconds>(now - userTs);
2997}
2998
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002999const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
3000 if (mHealthPath.empty()) {
3001 resetHealthControl();
3002 return mHealthControl;
3003 }
3004 if (mHealthControl.pendingReads() < 0) {
3005 mHealthControl = mService.mIncFs->openMount(mHealthPath);
3006 }
3007 if (mHealthControl.pendingReads() < 0) {
3008 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
3009 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
3010 << mHealthControl.logs() << ")";
3011 }
3012 return mHealthControl;
3013}
3014
3015void IncrementalService::DataLoaderStub::resetHealthControl() {
3016 mHealthControl = {};
3017}
3018
3019BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
3020 auto result = kMaxBootClockTsUs;
3021
3022 const auto& control = initializeHealthControl();
3023 if (control.pendingReads() < 0) {
3024 return result;
3025 }
3026
Songchun Fan6944f1e2020-11-06 15:24:24 -08003027 if (mService.mIncFs->waitForPendingReads(control, 0ms, &mLastPendingReads) !=
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003028 android::incfs::WaitResult::HaveData ||
Songchun Fan6944f1e2020-11-06 15:24:24 -08003029 mLastPendingReads.empty()) {
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003030 // Clear previous pending reads
3031 mLastPendingReads.clear();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003032 return result;
3033 }
3034
Alex Buynytskyyc144cc42021-03-31 22:19:42 -07003035 LOG(DEBUG) << id() << ": pendingReads: fd(" << control.pendingReads() << "), count("
3036 << mLastPendingReads.size() << "), block: " << mLastPendingReads.front().block
3037 << ", time: " << mLastPendingReads.front().bootClockTsUs
3038 << ", uid: " << mLastPendingReads.front().uid;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003039
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003040 return getOldestTsFromLastPendingReads();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003041}
3042
3043void IncrementalService::DataLoaderStub::registerForPendingReads() {
3044 const auto pendingReadsFd = mHealthControl.pendingReads();
3045 if (pendingReadsFd < 0) {
3046 return;
3047 }
3048
3049 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
3050
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003051 mService.mLooper->addFd(
3052 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
3053 [](int, int, void* data) -> int {
Alex Buynytskyycb163f92021-03-18 21:21:27 -07003054 auto self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003055 self->updateHealthStatus(/*baseline=*/true);
3056 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003057 },
3058 this);
3059 mService.mLooper->wake();
3060}
3061
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003062BootClockTsUs IncrementalService::DataLoaderStub::getOldestTsFromLastPendingReads() {
3063 auto result = kMaxBootClockTsUs;
3064 for (auto&& pendingRead : mLastPendingReads) {
3065 result = std::min(result, pendingRead.bootClockTsUs);
3066 }
3067 return result;
3068}
3069
Songchun Fan9471be52021-04-21 17:49:27 -07003070void IncrementalService::DataLoaderStub::getMetrics(android::os::PersistableBundle* result) {
3071 const auto duration = elapsedMsSinceOldestPendingRead();
3072 if (duration >= 0) {
Songchun Fan0dc77722021-05-03 17:13:52 -07003073 const auto& kMetricsMillisSinceOldestPendingRead =
Songchun Fan9471be52021-04-21 17:49:27 -07003074 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_OLDEST_PENDING_READ();
Songchun Fan0dc77722021-05-03 17:13:52 -07003075 result->putLong(String16(kMetricsMillisSinceOldestPendingRead.c_str()), duration);
Songchun Fan9471be52021-04-21 17:49:27 -07003076 }
Songchun Fan0dc77722021-05-03 17:13:52 -07003077 const auto& kMetricsStorageHealthStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003078 os::incremental::BnIncrementalService::METRICS_STORAGE_HEALTH_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003079 result->putInt(String16(kMetricsStorageHealthStatusCode.c_str()), mHealthStatus);
3080 const auto& kMetricsDataLoaderStatusCode =
Songchun Fan9471be52021-04-21 17:49:27 -07003081 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_STATUS_CODE();
Songchun Fan0dc77722021-05-03 17:13:52 -07003082 result->putInt(String16(kMetricsDataLoaderStatusCode.c_str()), mCurrentStatus);
3083 const auto& kMetricsMillisSinceLastDataLoaderBind =
Songchun Fan9471be52021-04-21 17:49:27 -07003084 os::incremental::BnIncrementalService::METRICS_MILLIS_SINCE_LAST_DATA_LOADER_BIND();
Songchun Fan0dc77722021-05-03 17:13:52 -07003085 result->putLong(String16(kMetricsMillisSinceLastDataLoaderBind.c_str()),
3086 elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000);
3087 const auto& kMetricsDataLoaderBindDelayMillis =
Songchun Fan9471be52021-04-21 17:49:27 -07003088 os::incremental::BnIncrementalService::METRICS_DATA_LOADER_BIND_DELAY_MILLIS();
Songchun Fan0dc77722021-05-03 17:13:52 -07003089 result->putLong(String16(kMetricsDataLoaderBindDelayMillis.c_str()),
3090 mPreviousBindDelay.count());
Songchun Fan9471be52021-04-21 17:49:27 -07003091}
3092
Songchun Fan1b76ccf2021-02-24 22:25:59 +00003093long IncrementalService::DataLoaderStub::elapsedMsSinceOldestPendingRead() {
3094 const auto oldestPendingReadKernelTs = getOldestTsFromLastPendingReads();
3095 if (oldestPendingReadKernelTs == kMaxBootClockTsUs) {
3096 return 0;
3097 }
3098 return elapsedMsSinceKernelTs(Clock::now(), oldestPendingReadKernelTs).count();
3099}
3100
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07003101void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003102 const auto pendingReadsFd = mHealthControl.pendingReads();
3103 if (pendingReadsFd < 0) {
3104 return;
3105 }
3106
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07003107 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
3108
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003109 mService.mLooper->removeFd(pendingReadsFd);
3110 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07003111}
3112
Songchun Fan2570ec02020-10-08 17:22:33 -07003113void IncrementalService::DataLoaderStub::setHealthListener(
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003114 const StorageHealthCheckParams& healthCheckParams, StorageHealthListener&& healthListener) {
Songchun Fan2570ec02020-10-08 17:22:33 -07003115 std::lock_guard lock(mMutex);
Yurii Zubrytskyif4769e22021-03-18 20:37:45 -07003116 mHealthCheckParams = healthCheckParams;
3117 mHealthListener = std::move(healthListener);
3118 if (!mHealthListener) {
3119 mHealthCheckParams.blockedTimeoutMs = -1;
Songchun Fan2570ec02020-10-08 17:22:33 -07003120 }
3121}
3122
Songchun Fan6944f1e2020-11-06 15:24:24 -08003123static std::string toHexString(const RawMetadata& metadata) {
3124 int n = metadata.size();
3125 std::string res(n * 2, '\0');
3126 // Same as incfs::toString(fileId)
3127 static constexpr char kHexChar[] = "0123456789abcdef";
3128 for (int i = 0; i < n; ++i) {
3129 res[i * 2] = kHexChar[(metadata[i] & 0xf0) >> 4];
3130 res[i * 2 + 1] = kHexChar[(metadata[i] & 0x0f)];
3131 }
3132 return res;
3133}
3134
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003135void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003136 dprintf(fd, " dataLoader: {\n");
3137 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
Alex Buynytskyy7e06d712021-03-09 19:24:23 -08003138 dprintf(fd, " currentStatusTs: %lldmcs\n",
3139 (long long)(elapsedMcs(mCurrentStatusTs, Clock::now())));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003140 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
3141 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003142 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003143 dprintf(fd, " health: {\n");
3144 dprintf(fd, " path: %s\n", mHealthPath.c_str());
3145 dprintf(fd, " base: %lldmcs (%lld)\n",
3146 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
3147 (long long)mHealthBase.kernelTsUs);
3148 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
3149 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
3150 dprintf(fd, " unhealthyMonitoringMs: %d\n",
3151 int(mHealthCheckParams.unhealthyMonitoringMs));
Songchun Fan6944f1e2020-11-06 15:24:24 -08003152 dprintf(fd, " lastPendingReads: \n");
3153 const auto control = mService.mIncFs->openMount(mHealthPath);
3154 for (auto&& pendingRead : mLastPendingReads) {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -07003155 dprintf(fd, " fileId: %s\n", IncFsWrapper::toString(pendingRead.id).c_str());
Songchun Fan6944f1e2020-11-06 15:24:24 -08003156 const auto metadata = mService.mIncFs->getMetadata(control, pendingRead.id);
3157 dprintf(fd, " metadataHex: %s\n", toHexString(metadata).c_str());
3158 dprintf(fd, " blockIndex: %d\n", pendingRead.block);
3159 dprintf(fd, " bootClockTsUs: %lld\n", (long long)pendingRead.bootClockTsUs);
3160 }
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003161 dprintf(fd, " bind: %llds ago (delay: %llds)\n",
Songchun Fan9471be52021-04-21 17:49:27 -07003162 (long long)(elapsedMcs(mPreviousBindTs, mService.mClock->now()) / 1000000),
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -08003163 (long long)(mPreviousBindDelay.count() / 1000));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07003164 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003165 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07003166 dprintf(fd, " dataLoaderParams: {\n");
3167 dprintf(fd, " type: %s\n", toString(params.type).c_str());
3168 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
3169 dprintf(fd, " className: %s\n", params.className.c_str());
3170 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
3171 dprintf(fd, " }\n");
3172 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07003173}
3174
Alex Buynytskyy1d892162020-04-03 23:00:19 -07003175void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
3176 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07003177}
3178
Alex Buynytskyyf4156792020-04-07 14:26:55 -07003179binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
3180 bool enableReadLogs, int32_t* _aidl_return) {
3181 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
3182 return binder::Status::ok();
3183}
3184
Alex Buynytskyy0b202662020-04-13 09:53:04 -07003185FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
3186 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
3187}
3188
Songchun Fan3c82a302019-11-29 14:23:45 -08003189} // namespace android::incremental