blob: a5f0d045948ca19673ada3291d9398e429e6ce0f [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>
Jooyung Han66c567a2020-03-07 21:47:09 +090026#include <binder/Nullable.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080027#include <binder/Status.h>
28#include <sys/stat.h>
29#include <uuid/uuid.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080030
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070031#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080032#include <ctime>
Songchun Fan3c82a302019-11-29 14:23:45 -080033#include <iterator>
34#include <span>
Songchun Fan3c82a302019-11-29 14:23:45 -080035#include <type_traits>
36
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070037#include "IncrementalServiceValidation.h"
Songchun Fan3c82a302019-11-29 14:23:45 -080038#include "Metadata.pb.h"
39
40using namespace std::literals;
Songchun Fan1124fd32020-02-10 12:49:41 -080041namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080042
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070043constexpr const char* kDataUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070044constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070045
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;
Songchun Fan3c82a302019-11-29 14:23:45 -080068};
69
70static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070071 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080072 return c;
73}
74
75template <base::LogSeverity level = base::ERROR>
76bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
77 auto cstr = path::c_str(name);
78 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080079 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080080 PLOG(level) << "Can't create directory '" << name << '\'';
81 return false;
82 }
83 struct stat st;
84 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
85 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
86 return false;
87 }
88 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080089 if (::chmod(cstr, mode)) {
90 PLOG(level) << "Changing permission failed for '" << name << '\'';
91 return false;
92 }
93
Songchun Fan3c82a302019-11-29 14:23:45 -080094 return true;
95}
96
97static std::string toMountKey(std::string_view path) {
98 if (path.empty()) {
99 return "@none";
100 }
101 if (path == "/"sv) {
102 return "@root";
103 }
104 if (path::isAbsolute(path)) {
105 path.remove_prefix(1);
106 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700107 if (path.size() > 16) {
108 path = path.substr(0, 16);
109 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800110 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700111 std::replace_if(
112 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
113 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800114}
115
116static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
117 std::string_view path) {
118 auto mountKey = toMountKey(path);
119 const auto prefixSize = mountKey.size();
120 for (int counter = 0; counter < 1000;
121 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
122 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800123 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800124 return {mountKey, mountRoot};
125 }
126 }
127 return {};
128}
129
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700130template <class Map>
131typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
132 const auto nextIt = map.upper_bound(path);
133 if (nextIt == map.begin()) {
134 return map.end();
135 }
136 const auto suspectIt = std::prev(nextIt);
137 if (!path::startsWith(path, suspectIt->first)) {
138 return map.end();
139 }
140 return suspectIt;
141}
142
143static base::unique_fd dup(base::borrowed_fd fd) {
144 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
145 return base::unique_fd(res);
146}
147
Songchun Fan3c82a302019-11-29 14:23:45 -0800148template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700149static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800150 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800151 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800152 ProtoMessage message;
153 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
154}
155
156static bool isValidMountTarget(std::string_view path) {
157 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
158}
159
160std::string makeBindMdName() {
161 static constexpr auto uuidStringSize = 36;
162
163 uuid_t guid;
164 uuid_generate(guid);
165
166 std::string name;
167 const auto prefixSize = constants().mountpointMdPrefix.size();
168 name.reserve(prefixSize + uuidStringSize);
169
170 name = constants().mountpointMdPrefix;
171 name.resize(prefixSize + uuidStringSize);
172 uuid_unparse(guid, name.data() + prefixSize);
173
174 return name;
175}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700176
177static bool checkReadLogsDisabledMarker(std::string_view root) {
178 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
179 struct stat st;
180 return (::stat(markerPath, &st) == 0);
181}
182
Songchun Fan3c82a302019-11-29 14:23:45 -0800183} // namespace
184
185IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700186 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700187 dataLoaderStub->cleanupResources();
188 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700189 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700190 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800191 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
192 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700193 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800194 incrementalService.mVold->unmountIncFs(target);
195 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700196 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800197 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
198 cleanupFilesystem(root);
199}
200
201auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800202 std::string name;
203 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
204 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
205 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800206 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
207 constants().storagePrefix.data(), id, no);
208 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800209 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800210 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800211 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
212 } else if (err != EEXIST) {
213 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
214 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800215 }
216 }
217 nextStorageDirNo = 0;
218 return storages.end();
219}
220
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700221template <class Func>
222static auto makeCleanup(Func&& f) {
223 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700224 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700225 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
226}
227
228static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
229 return {::opendir(dir), ::closedir};
230}
231
232static auto openDir(std::string_view dir) {
233 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800234}
235
236static int rmDirContent(const char* path) {
237 auto dir = openDir(path);
238 if (!dir) {
239 return -EINVAL;
240 }
241 while (auto entry = ::readdir(dir.get())) {
242 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
243 continue;
244 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700245 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800246 if (entry->d_type == DT_DIR) {
247 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
248 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
249 return err;
250 }
251 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
252 PLOG(WARNING) << "Failed to rmdir " << fullPath;
253 return err;
254 }
255 } else {
256 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
257 PLOG(WARNING) << "Failed to delete " << fullPath;
258 return err;
259 }
260 }
261 }
262 return 0;
263}
264
Songchun Fan3c82a302019-11-29 14:23:45 -0800265void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800266 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800267 ::rmdir(path::join(root, constants().backing).c_str());
268 ::rmdir(path::join(root, constants().mount).c_str());
269 ::rmdir(path::c_str(root));
270}
271
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800272IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800273 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800274 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800275 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700276 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700277 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700278 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700279 mTimedQueue(sm.getTimedQueue()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800280 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700281 CHECK(mVold) << "Vold service is unavailable";
282 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
283 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
284 CHECK(mJni) << "JNI is unavailable";
285 CHECK(mLooper) << "Looper is unavailable";
286 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700287
288 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700289 mJobProcessor = std::thread([this]() {
290 mJni->initializeForCurrentThread();
291 runJobProcessing();
292 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700293 mCmdLooperThread = std::thread([this]() {
294 mJni->initializeForCurrentThread();
295 runCmdLooper();
296 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700297
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700298 const auto mountedRootNames = adoptMountedInstances();
299 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800300}
301
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700302IncrementalService::~IncrementalService() {
303 {
304 std::lock_guard lock(mJobMutex);
305 mRunning = false;
306 }
307 mJobCondition.notify_all();
308 mJobProcessor.join();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700309 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700310 mTimedQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700311 // Ensure that mounts are destroyed while the service is still valid.
312 mBindsByPath.clear();
313 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700314}
Songchun Fan3c82a302019-11-29 14:23:45 -0800315
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700316static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800317 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800318 case IncrementalService::BindKind::Temporary:
319 return "Temporary";
320 case IncrementalService::BindKind::Permanent:
321 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800322 }
323}
324
325void IncrementalService::onDump(int fd) {
326 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
327 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
328
329 std::unique_lock l(mLock);
330
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700331 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800332 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700333 const IncFsMount& mnt = *ifs;
334 dprintf(fd, " [%d]: {\n", id);
335 if (id != mnt.mountId) {
336 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
337 } else {
338 dprintf(fd, " mountId: %d\n", mnt.mountId);
339 dprintf(fd, " root: %s\n", mnt.root.c_str());
340 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
341 if (mnt.dataLoaderStub) {
342 mnt.dataLoaderStub->onDump(fd);
343 } else {
344 dprintf(fd, " dataLoader: null\n");
345 }
346 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
347 for (auto&& [storageId, storage] : mnt.storages) {
348 dprintf(fd, " [%d] -> [%s]\n", storageId, storage.name.c_str());
349 }
350 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800351
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700352 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
353 for (auto&& [target, bind] : mnt.bindPoints) {
354 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
355 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
356 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
357 dprintf(fd, " kind: %s\n", toString(bind.kind));
358 }
359 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800360 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700361 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800362 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700363 dprintf(fd, "}\n");
364 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800365 for (auto&& [target, mountPairIt] : mBindsByPath) {
366 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700367 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
368 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
369 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
370 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800371 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700372 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800373}
374
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700375void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800376 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700377 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800378 }
379
380 std::vector<IfsMountPtr> mounts;
381 {
382 std::lock_guard l(mLock);
383 mounts.reserve(mMounts.size());
384 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -0700385 if (ifs->mountId == id &&
386 ifs->dataLoaderStub->params().packageName == Constants::systemPackage) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800387 mounts.push_back(ifs);
388 }
389 }
390 }
391
Alex Buynytskyy69941662020-04-11 21:40:37 -0700392 if (mounts.empty()) {
393 return;
394 }
395
Songchun Fan3c82a302019-11-29 14:23:45 -0800396 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700397 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800398 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700399 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800400 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800401 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800402}
403
404auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
405 for (;;) {
406 if (mNextId == kMaxStorageId) {
407 mNextId = 0;
408 }
409 auto id = ++mNextId;
410 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
411 if (inserted) {
412 return it;
413 }
414 }
415}
416
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700417StorageId IncrementalService::createStorage(std::string_view mountPoint,
418 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
419 CreateOptions options,
420 const DataLoaderStatusListener& statusListener,
421 StorageHealthCheckParams&& healthCheckParams,
422 const StorageHealthListener& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800423 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
424 if (!path::isAbsolute(mountPoint)) {
425 LOG(ERROR) << "path is not absolute: " << mountPoint;
426 return kInvalidStorageId;
427 }
428
429 auto mountNorm = path::normalize(mountPoint);
430 {
431 const auto id = findStorageId(mountNorm);
432 if (id != kInvalidStorageId) {
433 if (options & CreateOptions::OpenExisting) {
434 LOG(INFO) << "Opened existing storage " << id;
435 return id;
436 }
437 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
438 return kInvalidStorageId;
439 }
440 }
441
442 if (!(options & CreateOptions::CreateNew)) {
443 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
444 return kInvalidStorageId;
445 }
446
447 if (!path::isEmptyDir(mountNorm)) {
448 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
449 return kInvalidStorageId;
450 }
451 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
452 if (mountRoot.empty()) {
453 LOG(ERROR) << "Bad mount point";
454 return kInvalidStorageId;
455 }
456 // Make sure the code removes all crap it may create while still failing.
457 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
458 auto firstCleanupOnFailure =
459 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
460
461 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800462 const auto backing = path::join(mountRoot, constants().backing);
463 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800464 return kInvalidStorageId;
465 }
466
Songchun Fan3c82a302019-11-29 14:23:45 -0800467 IncFsMount::Control control;
468 {
469 std::lock_guard l(mMountOperationLock);
470 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800471
472 if (auto err = rmDirContent(backing.c_str())) {
473 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
474 return kInvalidStorageId;
475 }
476 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
477 return kInvalidStorageId;
478 }
479 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800480 if (!status.isOk()) {
481 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
482 return kInvalidStorageId;
483 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800484 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
485 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800486 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
487 return kInvalidStorageId;
488 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800489 int cmd = controlParcel.cmd.release().release();
490 int pendingReads = controlParcel.pendingReads.release().release();
491 int logs = controlParcel.log.release().release();
492 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800493 }
494
495 std::unique_lock l(mLock);
496 const auto mountIt = getStorageSlotLocked();
497 const auto mountId = mountIt->first;
498 l.unlock();
499
500 auto ifs =
501 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
502 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
503 // is the removal of the |ifs|.
504 firstCleanupOnFailure.release();
505
506 auto secondCleanup = [this, &l](auto itPtr) {
507 if (!l.owns_lock()) {
508 l.lock();
509 }
510 mMounts.erase(*itPtr);
511 };
512 auto secondCleanupOnFailure =
513 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
514
515 const auto storageIt = ifs->makeStorage(ifs->mountId);
516 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800517 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800518 return kInvalidStorageId;
519 }
520
521 {
522 metadata::Mount m;
523 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700524 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700525 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
526 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
527 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800528 const auto metadata = m.SerializeAsString();
529 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800530 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800531 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800532 if (auto err =
533 mIncFs->makeFile(ifs->control,
534 path::join(ifs->root, constants().mount,
535 constants().infoMdName),
536 0777, idFromMetadata(metadata),
537 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800538 LOG(ERROR) << "Saving mount metadata failed: " << -err;
539 return kInvalidStorageId;
540 }
541 }
542
543 const auto bk =
544 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800545 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
546 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800547 err < 0) {
548 LOG(ERROR) << "adding bind mount failed: " << -err;
549 return kInvalidStorageId;
550 }
551
552 // Done here as well, all data structures are in good state.
553 secondCleanupOnFailure.release();
554
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700555 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
556 std::move(healthCheckParams), &healthListener);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700557 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800558
559 mountIt->second = std::move(ifs);
560 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700561
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700562 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700563 // failed to create data loader
564 LOG(ERROR) << "initializeDataLoader() failed";
565 deleteStorage(dataLoaderStub->id());
566 return kInvalidStorageId;
567 }
568
Songchun Fan3c82a302019-11-29 14:23:45 -0800569 LOG(INFO) << "created storage " << mountId;
570 return mountId;
571}
572
573StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
574 StorageId linkedStorage,
575 IncrementalService::CreateOptions options) {
576 if (!isValidMountTarget(mountPoint)) {
577 LOG(ERROR) << "Mount point is invalid or missing";
578 return kInvalidStorageId;
579 }
580
581 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700582 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800583 if (!ifs) {
584 LOG(ERROR) << "Ifs unavailable";
585 return kInvalidStorageId;
586 }
587
588 const auto mountIt = getStorageSlotLocked();
589 const auto storageId = mountIt->first;
590 const auto storageIt = ifs->makeStorage(storageId);
591 if (storageIt == ifs->storages.end()) {
592 LOG(ERROR) << "Can't create a new storage";
593 mMounts.erase(mountIt);
594 return kInvalidStorageId;
595 }
596
597 l.unlock();
598
599 const auto bk =
600 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800601 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
602 std::string(storageIt->second.name), path::normalize(mountPoint),
603 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800604 err < 0) {
605 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700606 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
607 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800608 return kInvalidStorageId;
609 }
610
611 mountIt->second = ifs;
612 return storageId;
613}
614
615IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
616 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700617 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800618}
619
620StorageId IncrementalService::findStorageId(std::string_view path) const {
621 std::lock_guard l(mLock);
622 auto it = findStorageLocked(path);
623 if (it == mBindsByPath.end()) {
624 return kInvalidStorageId;
625 }
626 return it->second->second.storage;
627}
628
Alex Buynytskyy04035452020-06-06 20:15:58 -0700629void IncrementalService::disableReadLogs(StorageId storageId) {
630 std::unique_lock l(mLock);
631 const auto ifs = getIfsLocked(storageId);
632 if (!ifs) {
633 LOG(ERROR) << "disableReadLogs failed, invalid storageId: " << storageId;
634 return;
635 }
636 if (!ifs->readLogsEnabled()) {
637 return;
638 }
639 ifs->disableReadLogs();
640 l.unlock();
641
642 const auto metadata = constants().readLogsDisabledMarkerName;
643 if (auto err = mIncFs->makeFile(ifs->control,
644 path::join(ifs->root, constants().mount,
645 constants().readLogsDisabledMarkerName),
646 0777, idFromMetadata(metadata), {})) {
647 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
648 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
649 return;
650 }
651
652 setStorageParams(storageId, /*enableReadLogs=*/false);
653}
654
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700655int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
656 const auto ifs = getIfs(storageId);
657 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700658 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700659 return -EINVAL;
660 }
661
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700662 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700663 if (enableReadLogs) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700664 if (!ifs->readLogsEnabled()) {
665 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
666 return -EPERM;
667 }
668
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700669 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
670 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700671 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700672 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700673 return fromBinderStatus(status);
674 }
675 }
676
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700677 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
678 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
679 return fromBinderStatus(status);
680 }
681
682 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700683 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700684 }
685
686 return 0;
687}
688
689binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700690 os::incremental::IncrementalFileSystemControlParcel control;
691 control.cmd.reset(dup(ifs.control.cmd()));
692 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700693 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700694 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700695 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700696 }
697
698 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700699 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700700}
701
Songchun Fan3c82a302019-11-29 14:23:45 -0800702void IncrementalService::deleteStorage(StorageId storageId) {
703 const auto ifs = getIfs(storageId);
704 if (!ifs) {
705 return;
706 }
707 deleteStorage(*ifs);
708}
709
710void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
711 std::unique_lock l(ifs.lock);
712 deleteStorageLocked(ifs, std::move(l));
713}
714
715void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
716 std::unique_lock<std::mutex>&& ifsLock) {
717 const auto storages = std::move(ifs.storages);
718 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
719 const auto bindPoints = ifs.bindPoints;
720 ifsLock.unlock();
721
722 std::lock_guard l(mLock);
723 for (auto&& [id, _] : storages) {
724 if (id != ifs.mountId) {
725 mMounts.erase(id);
726 }
727 }
728 for (auto&& [path, _] : bindPoints) {
729 mBindsByPath.erase(path);
730 }
731 mMounts.erase(ifs.mountId);
732}
733
734StorageId IncrementalService::openStorage(std::string_view pathInMount) {
735 if (!path::isAbsolute(pathInMount)) {
736 return kInvalidStorageId;
737 }
738
739 return findStorageId(path::normalize(pathInMount));
740}
741
Songchun Fan3c82a302019-11-29 14:23:45 -0800742IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
743 std::lock_guard l(mLock);
744 return getIfsLocked(storage);
745}
746
747const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
748 auto it = mMounts.find(storage);
749 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700750 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700751 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800752 }
753 return it->second;
754}
755
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800756int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
757 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800758 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700759 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800760 return -EINVAL;
761 }
762
763 const auto ifs = getIfs(storage);
764 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700765 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800766 return -EINVAL;
767 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800768
Songchun Fan3c82a302019-11-29 14:23:45 -0800769 std::unique_lock l(ifs->lock);
770 const auto storageInfo = ifs->storages.find(storage);
771 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700772 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800773 return -EINVAL;
774 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700775 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700776 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700777 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700778 return -EINVAL;
779 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800780 l.unlock();
781 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800782 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
783 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800784}
785
786int IncrementalService::unbind(StorageId storage, std::string_view target) {
787 if (!path::isAbsolute(target)) {
788 return -EINVAL;
789 }
790
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700791 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800792
793 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
794 // otherwise there's a chance to unmount something completely unrelated
795 const auto norm = path::normalize(target);
796 std::unique_lock l(mLock);
797 const auto storageIt = mBindsByPath.find(norm);
798 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
799 return -EINVAL;
800 }
801 const auto bindIt = storageIt->second;
802 const auto storageId = bindIt->second.storage;
803 const auto ifs = getIfsLocked(storageId);
804 if (!ifs) {
805 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
806 << " is missing";
807 return -EFAULT;
808 }
809 mBindsByPath.erase(storageIt);
810 l.unlock();
811
812 mVold->unmountIncFs(bindIt->first);
813 std::unique_lock l2(ifs->lock);
814 if (ifs->bindPoints.size() <= 1) {
815 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700816 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800817 } else {
818 const std::string savedFile = std::move(bindIt->second.savedFilename);
819 ifs->bindPoints.erase(bindIt);
820 l2.unlock();
821 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800822 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800823 }
824 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700825
Songchun Fan3c82a302019-11-29 14:23:45 -0800826 return 0;
827}
828
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700829std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700830 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700831 std::string_view path) const {
832 if (!path::isAbsolute(path)) {
833 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700834 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700835 auto normPath = path::normalize(path);
836 if (path::startsWith(normPath, storageIt->second.name)) {
837 return normPath;
838 }
839 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700840 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
841 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700842 return {};
843 }
844 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700845}
846
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700847std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700848 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700849 std::unique_lock l(ifs.lock);
850 const auto storageInfo = ifs.storages.find(storage);
851 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800852 return {};
853 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700854 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800855}
856
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800857int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
858 incfs::NewFileParams params) {
859 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700860 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800861 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700862 LOG(ERROR) << "Internal error: storageId " << storage
863 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800864 return -EINVAL;
865 }
866 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800867 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700868 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800869 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800870 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800871 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800872 }
873 return -EINVAL;
874}
875
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800876int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800877 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700878 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800879 if (normPath.empty()) {
880 return -EINVAL;
881 }
882 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800883 }
884 return -EINVAL;
885}
886
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800887int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800888 const auto ifs = getIfs(storageId);
889 if (!ifs) {
890 return -EINVAL;
891 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700892 return makeDirs(*ifs, storageId, path, mode);
893}
894
895int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
896 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800897 std::string normPath = normalizePathToStorage(ifs, storageId, path);
898 if (normPath.empty()) {
899 return -EINVAL;
900 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700901 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800902}
903
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800904int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
905 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700906 std::unique_lock l(mLock);
907 auto ifsSrc = getIfsLocked(sourceStorageId);
908 if (!ifsSrc) {
909 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800910 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700911 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
912 return -EINVAL;
913 }
914 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700915 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
916 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700917 if (normOldPath.empty() || normNewPath.empty()) {
918 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
919 return -EINVAL;
920 }
921 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800922}
923
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800924int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800925 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700926 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800927 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800928 }
929 return -EINVAL;
930}
931
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800932int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
933 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800934 std::string&& target, BindKind kind,
935 std::unique_lock<std::mutex>& mainLock) {
936 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700937 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800938 return -EINVAL;
939 }
940
941 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700942 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800943 if (kind != BindKind::Temporary) {
944 metadata::BindPoint bp;
945 bp.set_storage_id(storage);
946 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800947 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800948 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800949 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800950 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800951 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700952 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
953 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
954 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800955 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700956 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800957 return int(node);
958 }
959 }
960
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700961 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
962 std::move(target), kind, mainLock);
963 if (res) {
964 mIncFs->unlink(ifs.control, metadataFullPath);
965 }
966 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800967}
968
969int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800970 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800971 std::string&& target, BindKind kind,
972 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800973 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800974 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800975 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800976 if (!status.isOk()) {
977 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
978 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
979 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
980 : status.serviceSpecificErrorCode() == 0
981 ? -EFAULT
982 : status.serviceSpecificErrorCode()
983 : -EIO;
984 }
985 }
986
987 if (!mainLock.owns_lock()) {
988 mainLock.lock();
989 }
990 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700991 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
992 std::move(target), kind);
993 return 0;
994}
995
996void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
997 std::string&& metadataName, std::string&& source,
998 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800999 const auto [it, _] =
1000 ifs.bindPoints.insert_or_assign(target,
1001 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001002 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001003 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001004}
1005
1006RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1007 const auto ifs = getIfs(storage);
1008 if (!ifs) {
1009 return {};
1010 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001011 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001012 if (normPath.empty()) {
1013 return {};
1014 }
1015 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001016}
1017
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001018RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001019 const auto ifs = getIfs(storage);
1020 if (!ifs) {
1021 return {};
1022 }
1023 return mIncFs->getMetadata(ifs->control, node);
1024}
1025
Songchun Fan3c82a302019-11-29 14:23:45 -08001026bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001027 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001028 {
1029 std::unique_lock l(mLock);
1030 const auto& ifs = getIfsLocked(storage);
1031 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001032 return false;
1033 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001034 dataLoaderStub = ifs->dataLoaderStub;
1035 if (!dataLoaderStub) {
1036 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001037 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001038 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001039 dataLoaderStub->requestStart();
1040 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001041}
1042
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001043std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1044 std::unordered_set<std::string_view> mountedRootNames;
1045 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1046 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1047 for (auto [source, target] : binds) {
1048 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1049 LOG(INFO) << " " << path::join(root, source);
1050 }
1051
1052 // Ensure it's a kind of a mount that's managed by IncrementalService
1053 if (path::basename(root) != constants().mount ||
1054 path::basename(backingDir) != constants().backing) {
1055 return;
1056 }
1057 const auto expectedRoot = path::dirname(root);
1058 if (path::dirname(backingDir) != expectedRoot) {
1059 return;
1060 }
1061 if (path::dirname(expectedRoot) != mIncrementalDir) {
1062 return;
1063 }
1064 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1065 return;
1066 }
1067
1068 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1069
1070 // make sure we clean up the mount if it happens to be a bad one.
1071 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1072 auto cleanupFiles = makeCleanup([&]() {
1073 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1074 IncFsMount::cleanupFilesystem(expectedRoot);
1075 });
1076 auto cleanupMounts = makeCleanup([&]() {
1077 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1078 for (auto&& [_, target] : binds) {
1079 mVold->unmountIncFs(std::string(target));
1080 }
1081 mVold->unmountIncFs(std::string(root));
1082 });
1083
1084 auto control = mIncFs->openMount(root);
1085 if (!control) {
1086 LOG(INFO) << "failed to open mount " << root;
1087 return;
1088 }
1089
1090 auto mountRecord =
1091 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1092 path::join(root, constants().infoMdName));
1093 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1094 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1095 return;
1096 }
1097
1098 auto mountId = mountRecord.storage().id();
1099 mNextId = std::max(mNextId, mountId + 1);
1100
1101 DataLoaderParamsParcel dataLoaderParams;
1102 {
1103 const auto& loader = mountRecord.loader();
1104 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1105 dataLoaderParams.packageName = loader.package_name();
1106 dataLoaderParams.className = loader.class_name();
1107 dataLoaderParams.arguments = loader.arguments();
1108 }
1109
1110 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1111 std::move(control), *this);
1112 cleanupFiles.release(); // ifs will take care of that now
1113
Alex Buynytskyy04035452020-06-06 20:15:58 -07001114 // Check if marker file present.
1115 if (checkReadLogsDisabledMarker(root)) {
1116 ifs->disableReadLogs();
1117 }
1118
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001119 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1120 auto d = openDir(root);
1121 while (auto e = ::readdir(d.get())) {
1122 if (e->d_type == DT_REG) {
1123 auto name = std::string_view(e->d_name);
1124 if (name.starts_with(constants().mountpointMdPrefix)) {
1125 permanentBindPoints
1126 .emplace_back(name,
1127 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1128 ifs->control,
1129 path::join(root,
1130 name)));
1131 if (permanentBindPoints.back().second.dest_path().empty() ||
1132 permanentBindPoints.back().second.source_subdir().empty()) {
1133 permanentBindPoints.pop_back();
1134 mIncFs->unlink(ifs->control, path::join(root, name));
1135 } else {
1136 LOG(INFO) << "Permanent bind record: '"
1137 << permanentBindPoints.back().second.source_subdir() << "'->'"
1138 << permanentBindPoints.back().second.dest_path() << "'";
1139 }
1140 }
1141 } else if (e->d_type == DT_DIR) {
1142 if (e->d_name == "."sv || e->d_name == ".."sv) {
1143 continue;
1144 }
1145 auto name = std::string_view(e->d_name);
1146 if (name.starts_with(constants().storagePrefix)) {
1147 int storageId;
1148 const auto res =
1149 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1150 name.data() + name.size(), storageId);
1151 if (res.ec != std::errc{} || *res.ptr != '_') {
1152 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1153 << "' for mount " << expectedRoot;
1154 continue;
1155 }
1156 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1157 if (!inserted) {
1158 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1159 << " for mount " << expectedRoot;
1160 continue;
1161 }
1162 ifs->storages.insert_or_assign(storageId,
1163 IncFsMount::Storage{path::join(root, name)});
1164 mNextId = std::max(mNextId, storageId + 1);
1165 }
1166 }
1167 }
1168
1169 if (ifs->storages.empty()) {
1170 LOG(WARNING) << "No valid storages in mount " << root;
1171 return;
1172 }
1173
1174 // now match the mounted directories with what we expect to have in the metadata
1175 {
1176 std::unique_lock l(mLock, std::defer_lock);
1177 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1178 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1179 [&, bindRecord = bindRecord](auto&& bind) {
1180 return bind.second == bindRecord.dest_path() &&
1181 path::join(root, bind.first) ==
1182 bindRecord.source_subdir();
1183 });
1184 if (mountedIt != binds.end()) {
1185 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1186 << " to mount " << mountedIt->first;
1187 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1188 std::move(*bindRecord.mutable_source_subdir()),
1189 std::move(*bindRecord.mutable_dest_path()),
1190 BindKind::Permanent);
1191 if (mountedIt != binds.end() - 1) {
1192 std::iter_swap(mountedIt, binds.end() - 1);
1193 }
1194 binds = binds.first(binds.size() - 1);
1195 } else {
1196 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1197 << ", mounting";
1198 // doesn't exist - try mounting back
1199 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1200 std::move(*bindRecord.mutable_source_subdir()),
1201 std::move(*bindRecord.mutable_dest_path()),
1202 BindKind::Permanent, l)) {
1203 mIncFs->unlink(ifs->control, metadataFile);
1204 }
1205 }
1206 }
1207 }
1208
1209 // if anything stays in |binds| those are probably temporary binds; system restarted since
1210 // they were mounted - so let's unmount them all.
1211 for (auto&& [source, target] : binds) {
1212 if (source.empty()) {
1213 continue;
1214 }
1215 mVold->unmountIncFs(std::string(target));
1216 }
1217 cleanupMounts.release(); // ifs now manages everything
1218
1219 if (ifs->bindPoints.empty()) {
1220 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1221 deleteStorage(*ifs);
1222 return;
1223 }
1224
1225 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1226 CHECK(ifs->dataLoaderStub);
1227
1228 mountedRootNames.insert(path::basename(ifs->root));
1229
1230 // not locking here at all: we're still in the constructor, no other calls can happen
1231 mMounts[ifs->mountId] = std::move(ifs);
1232 });
1233
1234 return mountedRootNames;
1235}
1236
1237void IncrementalService::mountExistingImages(
1238 const std::unordered_set<std::string_view>& mountedRootNames) {
1239 auto dir = openDir(mIncrementalDir);
1240 if (!dir) {
1241 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1242 return;
1243 }
1244 while (auto entry = ::readdir(dir.get())) {
1245 if (entry->d_type != DT_DIR) {
1246 continue;
1247 }
1248 std::string_view name = entry->d_name;
1249 if (!name.starts_with(constants().mountKeyPrefix)) {
1250 continue;
1251 }
1252 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001253 continue;
1254 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001255 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001256 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001257 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001258 }
1259 }
1260}
1261
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001262bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001263 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001264 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001265
Songchun Fan3c82a302019-11-29 14:23:45 -08001266 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001267 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001268 if (!status.isOk()) {
1269 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1270 return false;
1271 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001272
1273 int cmd = controlParcel.cmd.release().release();
1274 int pendingReads = controlParcel.pendingReads.release().release();
1275 int logs = controlParcel.log.release().release();
1276 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001277
1278 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1279
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001280 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1281 path::join(mountTarget, constants().infoMdName));
1282 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001283 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1284 return false;
1285 }
1286
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001287 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001288 mNextId = std::max(mNextId, ifs->mountId + 1);
1289
Alex Buynytskyy04035452020-06-06 20:15:58 -07001290 // Check if marker file present.
1291 if (checkReadLogsDisabledMarker(mountTarget)) {
1292 ifs->disableReadLogs();
1293 }
1294
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001295 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001296 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001297 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001298 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001299 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001300 dataLoaderParams.packageName = loader.package_name();
1301 dataLoaderParams.className = loader.class_name();
1302 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001303 }
1304
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001305 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001306 CHECK(ifs->dataLoaderStub);
1307
Songchun Fan3c82a302019-11-29 14:23:45 -08001308 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001309 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001310 while (auto e = ::readdir(d.get())) {
1311 if (e->d_type == DT_REG) {
1312 auto name = std::string_view(e->d_name);
1313 if (name.starts_with(constants().mountpointMdPrefix)) {
1314 bindPoints.emplace_back(name,
1315 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1316 ifs->control,
1317 path::join(mountTarget,
1318 name)));
1319 if (bindPoints.back().second.dest_path().empty() ||
1320 bindPoints.back().second.source_subdir().empty()) {
1321 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001322 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001323 }
1324 }
1325 } else if (e->d_type == DT_DIR) {
1326 if (e->d_name == "."sv || e->d_name == ".."sv) {
1327 continue;
1328 }
1329 auto name = std::string_view(e->d_name);
1330 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001331 int storageId;
1332 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1333 name.data() + name.size(), storageId);
1334 if (res.ec != std::errc{} || *res.ptr != '_') {
1335 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1336 << root;
1337 continue;
1338 }
1339 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001340 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001341 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001342 << " for mount " << root;
1343 continue;
1344 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001345 ifs->storages.insert_or_assign(storageId,
1346 IncFsMount::Storage{
1347 path::join(root, constants().mount, name)});
1348 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001349 }
1350 }
1351 }
1352
1353 if (ifs->storages.empty()) {
1354 LOG(WARNING) << "No valid storages in mount " << root;
1355 return false;
1356 }
1357
1358 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001359 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001360 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001361 for (auto&& bp : bindPoints) {
1362 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1363 std::move(*bp.second.mutable_source_subdir()),
1364 std::move(*bp.second.mutable_dest_path()),
1365 BindKind::Permanent, l);
1366 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001367 }
1368
1369 if (bindCount == 0) {
1370 LOG(WARNING) << "No valid bind points for mount " << root;
1371 deleteStorage(*ifs);
1372 return false;
1373 }
1374
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001375 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001376 mMounts[ifs->mountId] = std::move(ifs);
1377 return true;
1378}
1379
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001380void IncrementalService::runCmdLooper() {
1381 constexpr auto kTimeoutMsecs = 1000;
1382 while (mRunning.load(std::memory_order_relaxed)) {
1383 mLooper->pollAll(kTimeoutMsecs);
1384 }
1385}
1386
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001387IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001388 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001389 const DataLoaderStatusListener* statusListener,
1390 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001391 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001392 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1393 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001394 return ifs.dataLoaderStub;
1395}
1396
1397void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001398 const DataLoaderStatusListener* statusListener,
1399 StorageHealthCheckParams&& healthCheckParams,
1400 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001401 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001402 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001403 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001404 }
1405
Songchun Fan3c82a302019-11-29 14:23:45 -08001406 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001407 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001408 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1409 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1410 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001411 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001412
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001413 ifs.dataLoaderStub =
1414 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001415 statusListener, std::move(healthCheckParams), healthListener,
1416 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001417}
1418
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001419template <class Duration>
1420static long elapsedMcs(Duration start, Duration end) {
1421 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1422}
1423
1424// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001425// Lib files should be placed next to the APK file in the following matter:
1426// Example:
1427// /path/to/base.apk
1428// /path/to/lib/arm/first.so
1429// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001430bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1431 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001432 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001433 auto start = Clock::now();
1434
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001435 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001436 if (!ifs) {
1437 LOG(ERROR) << "Invalid storage " << storage;
1438 return false;
1439 }
1440
Songchun Fanc8975312020-07-13 12:14:37 -07001441 const auto targetLibPathRelativeToStorage =
1442 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1443 libDirRelativePath);
1444
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001445 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001446 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1447 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001448 << " errno: " << res;
1449 return false;
1450 }
1451
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001452 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001453 ZipArchiveHandle zipFileHandle;
1454 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001455 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1456 return false;
1457 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001458
1459 // Need a shared pointer: will be passing it into all unpacking jobs.
1460 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001461 void* cookie = nullptr;
1462 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001463 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001464 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1465 return false;
1466 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001467 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001468 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1469
1470 auto openZipTs = Clock::now();
1471
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001472 std::vector<Job> jobQueue;
1473 ZipEntry entry;
1474 std::string_view fileName;
1475 while (!Next(cookie, &entry, &fileName)) {
1476 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001477 continue;
1478 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001479
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001480 if (!extractNativeLibs) {
1481 // ensure the file is properly aligned and unpacked
1482 if (entry.method != kCompressStored) {
1483 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1484 return false;
1485 }
1486 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1487 LOG(WARNING) << "Library " << fileName
1488 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1489 << entry.offset;
1490 return false;
1491 }
1492 continue;
1493 }
1494
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001495 auto startFileTs = Clock::now();
1496
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001497 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001498 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001499 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001500 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001501 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001502 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001503 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1504 << "; skipping extraction, spent "
1505 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1506 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001507 continue;
1508 }
1509
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001510 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001511 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001512 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001513 .signature = {},
1514 // Metadata of the new lib file is its relative path
1515 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1516 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001517 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001518 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1519 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001520 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001521 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001522 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001523 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001524
1525 auto makeFileTs = Clock::now();
1526
Songchun Fanafaf6e92020-03-18 14:12:20 -07001527 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001528 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001529 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001530 LOG(INFO) << "incfs: Extracted " << libName
1531 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001532 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001533 continue;
1534 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001535
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001536 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1537 libFileId, libPath = std::move(targetLibPath),
1538 makeFileTs]() mutable {
1539 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001540 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001541
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001542 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001543 auto prepareJobTs = Clock::now();
1544 LOG(INFO) << "incfs: Processed " << libName << ": "
1545 << elapsedMcs(startFileTs, prepareJobTs)
1546 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1547 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001548 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001549 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001550
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001551 auto processedTs = Clock::now();
1552
1553 if (!jobQueue.empty()) {
1554 {
1555 std::lock_guard lock(mJobMutex);
1556 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001557 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001558 if (existingJobs.empty()) {
1559 existingJobs = std::move(jobQueue);
1560 } else {
1561 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1562 std::move_iterator(jobQueue.end()));
1563 }
1564 }
1565 }
1566 mJobCondition.notify_all();
1567 }
1568
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001569 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001570 auto end = Clock::now();
1571 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1572 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1573 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001574 << " make files: " << elapsedMcs(openZipTs, processedTs)
1575 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001576 }
1577
1578 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001579}
1580
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001581void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1582 ZipEntry& entry, const incfs::FileId& libFileId,
1583 std::string_view targetLibPath,
1584 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001585 if (!ifs) {
1586 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1587 return;
1588 }
1589
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001590 auto libName = path::basename(targetLibPath);
1591 auto startedTs = Clock::now();
1592
1593 // Write extracted data to new file
1594 // NOTE: don't zero-initialize memory, it may take a while for nothing
1595 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1596 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1597 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1598 return;
1599 }
1600
1601 auto extractFileTs = Clock::now();
1602
1603 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1604 if (!writeFd.ok()) {
1605 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1606 return;
1607 }
1608
1609 auto openFileTs = Clock::now();
1610 const int numBlocks =
1611 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1612 std::vector<IncFsDataBlock> instructions(numBlocks);
1613 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1614 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001615 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001616 instructions[i] = IncFsDataBlock{
1617 .fileFd = writeFd.get(),
1618 .pageIndex = static_cast<IncFsBlockIndex>(i),
1619 .compression = INCFS_COMPRESSION_KIND_NONE,
1620 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001621 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001622 .data = reinterpret_cast<const char*>(remainingData.data()),
1623 };
1624 remainingData = remainingData.subspan(blockSize);
1625 }
1626 auto prepareInstsTs = Clock::now();
1627
1628 size_t res = mIncFs->writeBlocks(instructions);
1629 if (res != instructions.size()) {
1630 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1631 return;
1632 }
1633
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001634 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001635 auto endFileTs = Clock::now();
1636 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1637 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1638 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1639 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1640 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1641 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1642 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1643 }
1644}
1645
1646bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001647 struct WaitPrinter {
1648 const Clock::time_point startTs = Clock::now();
1649 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001650 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001651 const auto endTs = Clock::now();
1652 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1653 << elapsedMcs(startTs, endTs) << "mcs";
1654 }
1655 }
1656 } waitPrinter;
1657
1658 MountId mount;
1659 {
1660 auto ifs = getIfs(storage);
1661 if (!ifs) {
1662 return true;
1663 }
1664 mount = ifs->mountId;
1665 }
1666
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001667 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001668 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001669 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001670 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001671 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001672 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001673}
1674
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001675bool IncrementalService::perfLoggingEnabled() {
1676 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1677 return enabled;
1678}
1679
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001680void IncrementalService::runJobProcessing() {
1681 for (;;) {
1682 std::unique_lock lock(mJobMutex);
1683 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1684 if (!mRunning) {
1685 return;
1686 }
1687
1688 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001689 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001690 auto queue = std::move(it->second);
1691 mJobQueue.erase(it);
1692 lock.unlock();
1693
1694 for (auto&& job : queue) {
1695 job();
1696 }
1697
1698 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001699 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001700 lock.unlock();
1701 mJobCondition.notify_all();
1702 }
1703}
1704
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001705void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001706 sp<IAppOpsCallback> listener;
1707 {
1708 std::unique_lock lock{mCallbacksLock};
1709 auto& cb = mCallbackRegistered[packageName];
1710 if (cb) {
1711 return;
1712 }
1713 cb = new AppOpsListener(*this, packageName);
1714 listener = cb;
1715 }
1716
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001717 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1718 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001719}
1720
1721bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1722 sp<IAppOpsCallback> listener;
1723 {
1724 std::unique_lock lock{mCallbacksLock};
1725 auto found = mCallbackRegistered.find(packageName);
1726 if (found == mCallbackRegistered.end()) {
1727 return false;
1728 }
1729 listener = found->second;
1730 mCallbackRegistered.erase(found);
1731 }
1732
1733 mAppOpsManager->stopWatchingMode(listener);
1734 return true;
1735}
1736
1737void IncrementalService::onAppOpChanged(const std::string& packageName) {
1738 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001739 return;
1740 }
1741
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001742 std::vector<IfsMountPtr> affected;
1743 {
1744 std::lock_guard l(mLock);
1745 affected.reserve(mMounts.size());
1746 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001747 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001748 affected.push_back(ifs);
1749 }
1750 }
1751 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001752 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001753 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001754 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001755}
1756
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07001757void IncrementalService::addTimedJob(MountId id, Milliseconds after, Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001758 if (id == kInvalidStorageId) {
1759 return;
1760 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07001761 mTimedQueue->addJob(id, after, std::move(what));
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001762}
1763
1764void IncrementalService::removeTimedJobs(MountId id) {
1765 if (id == kInvalidStorageId) {
1766 return;
1767 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07001768 mTimedQueue->removeJobs(id);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001769}
1770
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001771IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1772 DataLoaderParamsParcel&& params,
1773 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001774 const DataLoaderStatusListener* statusListener,
1775 StorageHealthCheckParams&& healthCheckParams,
1776 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001777 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001778 : mService(service),
1779 mId(id),
1780 mParams(std::move(params)),
1781 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001782 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
1783 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001784 mHealthPath(std::move(healthPath)),
1785 mHealthCheckParams(std::move(healthCheckParams)) {
1786 if (mHealthListener) {
1787 if (!isHealthParamsValid()) {
1788 mHealthListener = {};
1789 }
1790 } else {
1791 // Disable advanced health check statuses.
1792 mHealthCheckParams.blockedTimeoutMs = -1;
1793 }
1794 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001795}
1796
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001797IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001798 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001799 cleanupResources();
1800 }
1801}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001802
1803void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001804 auto now = Clock::now();
1805 {
1806 std::unique_lock lock(mMutex);
1807 mHealthPath.clear();
1808 unregisterFromPendingReads();
1809 resetHealthControl();
1810 mService.removeTimedJobs(mId);
1811 }
1812
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001813 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001814
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001815 {
1816 std::unique_lock lock(mMutex);
1817 mParams = {};
1818 mControl = {};
1819 mHealthControl = {};
1820 mHealthListener = {};
1821 mStatusCondition.wait_until(lock, now + 60s, [this] {
1822 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1823 });
1824 mStatusListener = {};
1825 mId = kInvalidStorageId;
1826 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001827}
1828
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001829sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1830 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001831 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001832 if (!status.isOk()) {
1833 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1834 return {};
1835 }
1836 if (!dataloader) {
1837 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1838 return {};
1839 }
1840 return dataloader;
1841}
1842
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001843bool IncrementalService::DataLoaderStub::requestCreate() {
1844 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1845}
1846
1847bool IncrementalService::DataLoaderStub::requestStart() {
1848 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1849}
1850
1851bool IncrementalService::DataLoaderStub::requestDestroy() {
1852 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1853}
1854
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001855bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001856 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001857 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001858 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001859 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001860 return fsmStep();
1861}
1862
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001863void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001864 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001865 mTargetStatus = status;
1866 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001867 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001868 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001869}
1870
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001871bool IncrementalService::DataLoaderStub::bind() {
1872 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001873 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001874 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001875 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001876 return false;
1877 }
1878 return true;
1879}
1880
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001881bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001882 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001883 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001884 return false;
1885 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001886 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001887 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001888 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001889 return false;
1890 }
1891 return true;
1892}
1893
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001894bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001895 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001896 if (!dataloader) {
1897 return false;
1898 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001899 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001900 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001901 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001902 return false;
1903 }
1904 return true;
1905}
1906
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001907bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001908 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001909}
1910
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001911bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001912 if (!isValid()) {
1913 return false;
1914 }
1915
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001916 int currentStatus;
1917 int targetStatus;
1918 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001919 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001920 currentStatus = mCurrentStatus;
1921 targetStatus = mTargetStatus;
1922 }
1923
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001924 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001925
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001926 if (currentStatus == targetStatus) {
1927 return true;
1928 }
1929
1930 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001931 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
1932 // Do nothing, this is a reset state.
1933 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001934 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1935 return destroy();
1936 }
1937 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1938 switch (currentStatus) {
1939 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1940 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1941 return start();
1942 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001943 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001944 }
1945 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1946 switch (currentStatus) {
1947 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001948 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001949 return bind();
1950 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001951 return create();
1952 }
1953 break;
1954 default:
1955 LOG(ERROR) << "Invalid target status: " << targetStatus
1956 << ", current status: " << currentStatus;
1957 break;
1958 }
1959 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001960}
1961
1962binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001963 if (!isValid()) {
1964 return binder::Status::
1965 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
1966 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001967 if (id() != mountId) {
1968 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001969 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
1970 }
1971
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001972 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001973 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001974 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001975 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001976 if (mCurrentStatus == newStatus) {
1977 return binder::Status::ok();
1978 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001979
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001980 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001981 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001982 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001983
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001984 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001985
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001986 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001987 // For unavailable, unbind from DataLoader to ensure proper re-commit.
1988 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001989 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001990 }
1991
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001992 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001993 << newStatus << " (target " << targetStatus << ")";
1994
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001995 if (listener) {
1996 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001997 }
1998
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001999 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002000
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002001 mStatusCondition.notify_all();
2002
Songchun Fan3c82a302019-11-29 14:23:45 -08002003 return binder::Status::ok();
2004}
2005
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002006bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2007 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2008 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002009}
2010
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002011void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2012 int healthStatus) {
2013 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2014 if (healthListener) {
2015 healthListener->onHealthStatus(id(), healthStatus);
2016 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002017}
2018
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002019void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2020 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002021
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002022 int healthStatusToReport = -1;
2023 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002024
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002025 {
2026 std::unique_lock lock(mMutex);
2027 unregisterFromPendingReads();
2028
2029 healthListener = mHealthListener;
2030
2031 // Healthcheck depends on timestamp of the oldest pending read.
2032 // To get it, we need to re-open a pendingReads FD to get a full list of reads.
2033 // Additionally we need to re-register for epoll with fresh FDs in case there are no reads.
2034 const auto now = Clock::now();
2035 const auto kernelTsUs = getOldestPendingReadTs();
2036 if (baseline) {
2037 // Updating baseline only on looper/epoll callback, i.e. on new set of pending reads.
2038 mHealthBase = {now, kernelTsUs};
2039 }
2040
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002041 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2042 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002043 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2044 registerForPendingReads();
2045 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2046 lock.unlock();
2047 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002048 return;
2049 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002050
2051 resetHealthControl();
2052
2053 // Always make sure the data loader is started.
2054 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2055
2056 // Skip any further processing if health check params are invalid.
2057 if (!isHealthParamsValid()) {
2058 LOG(DEBUG) << id()
2059 << ": Skip any further processing if health check params are invalid.";
2060 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2061 lock.unlock();
2062 onHealthStatus(healthListener, healthStatusToReport);
2063 // Triggering data loader start. This is a one-time action.
2064 fsmStep();
2065 return;
2066 }
2067
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002068 // Don't schedule timer job less than 500ms in advance.
2069 static constexpr auto kTolerance = 500ms;
2070
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002071 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2072 const auto unhealthyTimeout =
2073 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2074 const auto unhealthyMonitoring =
2075 std::max(1000ms,
2076 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2077
2078 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2079 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002080 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002081
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002082 Milliseconds checkBackAfter;
2083 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002084 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002085 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002086 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002087 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002088 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002089 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002090 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2091 } else {
2092 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002093 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002094 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2095 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002096 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002097 << "secs";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002098 mService.addTimedJob(id(), checkBackAfter, [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002099 }
2100
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002101 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002102 if (healthStatusToReport != -1) {
2103 onHealthStatus(healthListener, healthStatusToReport);
2104 }
2105
2106 fsmStep();
2107}
2108
2109const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2110 if (mHealthPath.empty()) {
2111 resetHealthControl();
2112 return mHealthControl;
2113 }
2114 if (mHealthControl.pendingReads() < 0) {
2115 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2116 }
2117 if (mHealthControl.pendingReads() < 0) {
2118 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2119 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2120 << mHealthControl.logs() << ")";
2121 }
2122 return mHealthControl;
2123}
2124
2125void IncrementalService::DataLoaderStub::resetHealthControl() {
2126 mHealthControl = {};
2127}
2128
2129BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2130 auto result = kMaxBootClockTsUs;
2131
2132 const auto& control = initializeHealthControl();
2133 if (control.pendingReads() < 0) {
2134 return result;
2135 }
2136
2137 std::vector<incfs::ReadInfo> pendingReads;
2138 if (mService.mIncFs->waitForPendingReads(control, 0ms, &pendingReads) !=
2139 android::incfs::WaitResult::HaveData ||
2140 pendingReads.empty()) {
2141 return result;
2142 }
2143
2144 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
2145 << pendingReads.size() << ": " << pendingReads.front().bootClockTsUs;
2146
2147 for (auto&& pendingRead : pendingReads) {
2148 result = std::min(result, pendingRead.bootClockTsUs);
2149 }
2150 return result;
2151}
2152
2153void IncrementalService::DataLoaderStub::registerForPendingReads() {
2154 const auto pendingReadsFd = mHealthControl.pendingReads();
2155 if (pendingReadsFd < 0) {
2156 return;
2157 }
2158
2159 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2160
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002161 mService.mLooper->addFd(
2162 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2163 [](int, int, void* data) -> int {
2164 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002165 self->updateHealthStatus(/*baseline=*/true);
2166 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002167 },
2168 this);
2169 mService.mLooper->wake();
2170}
2171
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002172void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002173 const auto pendingReadsFd = mHealthControl.pendingReads();
2174 if (pendingReadsFd < 0) {
2175 return;
2176 }
2177
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002178 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2179
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002180 mService.mLooper->removeFd(pendingReadsFd);
2181 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002182}
2183
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002184void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002185 dprintf(fd, " dataLoader: {\n");
2186 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2187 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2188 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002189 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002190 dprintf(fd, " health: {\n");
2191 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2192 dprintf(fd, " base: %lldmcs (%lld)\n",
2193 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2194 (long long)mHealthBase.kernelTsUs);
2195 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2196 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2197 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2198 int(mHealthCheckParams.unhealthyMonitoringMs));
2199 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002200 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002201 dprintf(fd, " dataLoaderParams: {\n");
2202 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2203 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2204 dprintf(fd, " className: %s\n", params.className.c_str());
2205 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2206 dprintf(fd, " }\n");
2207 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002208}
2209
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002210void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2211 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002212}
2213
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002214binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2215 bool enableReadLogs, int32_t* _aidl_return) {
2216 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2217 return binder::Status::ok();
2218}
2219
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002220FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2221 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2222}
2223
Songchun Fan3c82a302019-11-29 14:23:45 -08002224} // namespace android::incremental