blob: f7082a9a1a0c6d3cb37282717fcfa55247c6531a [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "IncrementalService"
18
19#include "IncrementalService.h"
20
Songchun Fan3c82a302019-11-29 14:23:45 -080021#include <android-base/logging.h>
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -070022#include <android-base/no_destructor.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080023#include <android-base/properties.h>
24#include <android-base/stringprintf.h>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070025#include <binder/AppOpsManager.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080026#include <binder/Status.h>
27#include <sys/stat.h>
28#include <uuid/uuid.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080029
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070030#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080031#include <ctime>
Songchun Fan3c82a302019-11-29 14:23:45 -080032#include <iterator>
33#include <span>
Songchun Fan3c82a302019-11-29 14:23:45 -080034#include <type_traits>
35
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070036#include "IncrementalServiceValidation.h"
Songchun Fan3c82a302019-11-29 14:23:45 -080037#include "Metadata.pb.h"
38
39using namespace std::literals;
Songchun Fan1124fd32020-02-10 12:49:41 -080040namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080041
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070042constexpr const char* kDataUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070043constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070044
Songchun Fan3c82a302019-11-29 14:23:45 -080045namespace android::incremental {
46
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070047using content::pm::DataLoaderParamsParcel;
48using content::pm::FileSystemControlParcel;
49using content::pm::IDataLoader;
50
Songchun Fan3c82a302019-11-29 14:23:45 -080051namespace {
52
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070053using IncrementalFileSystemControlParcel = os::incremental::IncrementalFileSystemControlParcel;
Songchun Fan3c82a302019-11-29 14:23:45 -080054
55struct Constants {
56 static constexpr auto backing = "backing_store"sv;
57 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080058 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080059 static constexpr auto storagePrefix = "st"sv;
60 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
61 static constexpr auto infoMdName = ".info"sv;
Alex Buynytskyy04035452020-06-06 20:15:58 -070062 static constexpr auto readLogsDisabledMarkerName = ".readlogs_disabled"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080063 static constexpr auto libDir = "lib"sv;
64 static constexpr auto libSuffix = ".so"sv;
65 static constexpr auto blockSize = 4096;
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -070066 static constexpr auto systemPackage = "android"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080067};
68
69static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070070 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080071 return c;
72}
73
74template <base::LogSeverity level = base::ERROR>
75bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
76 auto cstr = path::c_str(name);
77 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080078 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080079 PLOG(level) << "Can't create directory '" << name << '\'';
80 return false;
81 }
82 struct stat st;
83 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
84 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
85 return false;
86 }
87 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080088 if (::chmod(cstr, mode)) {
89 PLOG(level) << "Changing permission failed for '" << name << '\'';
90 return false;
91 }
92
Songchun Fan3c82a302019-11-29 14:23:45 -080093 return true;
94}
95
96static std::string toMountKey(std::string_view path) {
97 if (path.empty()) {
98 return "@none";
99 }
100 if (path == "/"sv) {
101 return "@root";
102 }
103 if (path::isAbsolute(path)) {
104 path.remove_prefix(1);
105 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700106 if (path.size() > 16) {
107 path = path.substr(0, 16);
108 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800109 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700110 std::replace_if(
111 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
112 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800113}
114
115static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
116 std::string_view path) {
117 auto mountKey = toMountKey(path);
118 const auto prefixSize = mountKey.size();
119 for (int counter = 0; counter < 1000;
120 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
121 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800122 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800123 return {mountKey, mountRoot};
124 }
125 }
126 return {};
127}
128
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700129template <class Map>
130typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
131 const auto nextIt = map.upper_bound(path);
132 if (nextIt == map.begin()) {
133 return map.end();
134 }
135 const auto suspectIt = std::prev(nextIt);
136 if (!path::startsWith(path, suspectIt->first)) {
137 return map.end();
138 }
139 return suspectIt;
140}
141
142static base::unique_fd dup(base::borrowed_fd fd) {
143 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
144 return base::unique_fd(res);
145}
146
Songchun Fan3c82a302019-11-29 14:23:45 -0800147template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700148static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800149 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800150 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800151 ProtoMessage message;
152 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
153}
154
155static bool isValidMountTarget(std::string_view path) {
156 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
157}
158
159std::string makeBindMdName() {
160 static constexpr auto uuidStringSize = 36;
161
162 uuid_t guid;
163 uuid_generate(guid);
164
165 std::string name;
166 const auto prefixSize = constants().mountpointMdPrefix.size();
167 name.reserve(prefixSize + uuidStringSize);
168
169 name = constants().mountpointMdPrefix;
170 name.resize(prefixSize + uuidStringSize);
171 uuid_unparse(guid, name.data() + prefixSize);
172
173 return name;
174}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700175
176static bool checkReadLogsDisabledMarker(std::string_view root) {
177 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
178 struct stat st;
179 return (::stat(markerPath, &st) == 0);
180}
181
Songchun Fan3c82a302019-11-29 14:23:45 -0800182} // namespace
183
184IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700185 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700186 dataLoaderStub->cleanupResources();
187 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700188 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700189 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800190 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
191 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700192 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800193 incrementalService.mVold->unmountIncFs(target);
194 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700195 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800196 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
197 cleanupFilesystem(root);
198}
199
200auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800201 std::string name;
202 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
203 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
204 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800205 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
206 constants().storagePrefix.data(), id, no);
207 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800208 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800209 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800210 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
211 } else if (err != EEXIST) {
212 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
213 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800214 }
215 }
216 nextStorageDirNo = 0;
217 return storages.end();
218}
219
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700220template <class Func>
221static auto makeCleanup(Func&& f) {
222 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700223 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700224 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
225}
226
227static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
228 return {::opendir(dir), ::closedir};
229}
230
231static auto openDir(std::string_view dir) {
232 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800233}
234
235static int rmDirContent(const char* path) {
236 auto dir = openDir(path);
237 if (!dir) {
238 return -EINVAL;
239 }
240 while (auto entry = ::readdir(dir.get())) {
241 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
242 continue;
243 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700244 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800245 if (entry->d_type == DT_DIR) {
246 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
247 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
248 return err;
249 }
250 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
251 PLOG(WARNING) << "Failed to rmdir " << fullPath;
252 return err;
253 }
254 } else {
255 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
256 PLOG(WARNING) << "Failed to delete " << fullPath;
257 return err;
258 }
259 }
260 }
261 return 0;
262}
263
Songchun Fan3c82a302019-11-29 14:23:45 -0800264void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800265 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800266 ::rmdir(path::join(root, constants().backing).c_str());
267 ::rmdir(path::join(root, constants().mount).c_str());
268 ::rmdir(path::c_str(root));
269}
270
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800271IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800272 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800273 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800274 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700275 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700276 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700277 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700278 mTimedQueue(sm.getTimedQueue()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800279 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700280 CHECK(mVold) << "Vold service is unavailable";
281 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
282 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
283 CHECK(mJni) << "JNI is unavailable";
284 CHECK(mLooper) << "Looper is unavailable";
285 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700286
287 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700288 mJobProcessor = std::thread([this]() {
289 mJni->initializeForCurrentThread();
290 runJobProcessing();
291 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700292 mCmdLooperThread = std::thread([this]() {
293 mJni->initializeForCurrentThread();
294 runCmdLooper();
295 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700296
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700297 const auto mountedRootNames = adoptMountedInstances();
298 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800299}
300
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700301IncrementalService::~IncrementalService() {
302 {
303 std::lock_guard lock(mJobMutex);
304 mRunning = false;
305 }
306 mJobCondition.notify_all();
307 mJobProcessor.join();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700308 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700309 mTimedQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700310 // Ensure that mounts are destroyed while the service is still valid.
311 mBindsByPath.clear();
312 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700313}
Songchun Fan3c82a302019-11-29 14:23:45 -0800314
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700315static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800316 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800317 case IncrementalService::BindKind::Temporary:
318 return "Temporary";
319 case IncrementalService::BindKind::Permanent:
320 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800321 }
322}
323
324void IncrementalService::onDump(int fd) {
325 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
326 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
327
328 std::unique_lock l(mLock);
329
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700330 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800331 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700332 const IncFsMount& mnt = *ifs;
333 dprintf(fd, " [%d]: {\n", id);
334 if (id != mnt.mountId) {
335 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
336 } else {
337 dprintf(fd, " mountId: %d\n", mnt.mountId);
338 dprintf(fd, " root: %s\n", mnt.root.c_str());
339 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
340 if (mnt.dataLoaderStub) {
341 mnt.dataLoaderStub->onDump(fd);
342 } else {
343 dprintf(fd, " dataLoader: null\n");
344 }
345 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
346 for (auto&& [storageId, storage] : mnt.storages) {
347 dprintf(fd, " [%d] -> [%s]\n", storageId, storage.name.c_str());
348 }
349 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800350
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700351 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
352 for (auto&& [target, bind] : mnt.bindPoints) {
353 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
354 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
355 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
356 dprintf(fd, " kind: %s\n", toString(bind.kind));
357 }
358 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800359 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700360 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800361 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700362 dprintf(fd, "}\n");
363 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800364 for (auto&& [target, mountPairIt] : mBindsByPath) {
365 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700366 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
367 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
368 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
369 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800370 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700371 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800372}
373
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700374void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800375 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700376 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800377 }
378
379 std::vector<IfsMountPtr> mounts;
380 {
381 std::lock_guard l(mLock);
382 mounts.reserve(mMounts.size());
383 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -0700384 if (ifs->mountId == id &&
385 ifs->dataLoaderStub->params().packageName == Constants::systemPackage) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800386 mounts.push_back(ifs);
387 }
388 }
389 }
390
Alex Buynytskyy69941662020-04-11 21:40:37 -0700391 if (mounts.empty()) {
392 return;
393 }
394
Songchun Fan3c82a302019-11-29 14:23:45 -0800395 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700396 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800397 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700398 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800399 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800400 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800401}
402
403auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
404 for (;;) {
405 if (mNextId == kMaxStorageId) {
406 mNextId = 0;
407 }
408 auto id = ++mNextId;
409 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
410 if (inserted) {
411 return it;
412 }
413 }
414}
415
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700416StorageId IncrementalService::createStorage(std::string_view mountPoint,
417 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
418 CreateOptions options,
419 const DataLoaderStatusListener& statusListener,
420 StorageHealthCheckParams&& healthCheckParams,
421 const StorageHealthListener& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800422 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
423 if (!path::isAbsolute(mountPoint)) {
424 LOG(ERROR) << "path is not absolute: " << mountPoint;
425 return kInvalidStorageId;
426 }
427
428 auto mountNorm = path::normalize(mountPoint);
429 {
430 const auto id = findStorageId(mountNorm);
431 if (id != kInvalidStorageId) {
432 if (options & CreateOptions::OpenExisting) {
433 LOG(INFO) << "Opened existing storage " << id;
434 return id;
435 }
436 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
437 return kInvalidStorageId;
438 }
439 }
440
441 if (!(options & CreateOptions::CreateNew)) {
442 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
443 return kInvalidStorageId;
444 }
445
446 if (!path::isEmptyDir(mountNorm)) {
447 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
448 return kInvalidStorageId;
449 }
450 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
451 if (mountRoot.empty()) {
452 LOG(ERROR) << "Bad mount point";
453 return kInvalidStorageId;
454 }
455 // Make sure the code removes all crap it may create while still failing.
456 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
457 auto firstCleanupOnFailure =
458 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
459
460 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800461 const auto backing = path::join(mountRoot, constants().backing);
462 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800463 return kInvalidStorageId;
464 }
465
Songchun Fan3c82a302019-11-29 14:23:45 -0800466 IncFsMount::Control control;
467 {
468 std::lock_guard l(mMountOperationLock);
469 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800470
471 if (auto err = rmDirContent(backing.c_str())) {
472 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
473 return kInvalidStorageId;
474 }
475 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
476 return kInvalidStorageId;
477 }
478 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800479 if (!status.isOk()) {
480 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
481 return kInvalidStorageId;
482 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800483 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
484 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800485 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
486 return kInvalidStorageId;
487 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800488 int cmd = controlParcel.cmd.release().release();
489 int pendingReads = controlParcel.pendingReads.release().release();
490 int logs = controlParcel.log.release().release();
491 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800492 }
493
494 std::unique_lock l(mLock);
495 const auto mountIt = getStorageSlotLocked();
496 const auto mountId = mountIt->first;
497 l.unlock();
498
499 auto ifs =
500 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
501 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
502 // is the removal of the |ifs|.
503 firstCleanupOnFailure.release();
504
505 auto secondCleanup = [this, &l](auto itPtr) {
506 if (!l.owns_lock()) {
507 l.lock();
508 }
509 mMounts.erase(*itPtr);
510 };
511 auto secondCleanupOnFailure =
512 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
513
514 const auto storageIt = ifs->makeStorage(ifs->mountId);
515 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800516 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800517 return kInvalidStorageId;
518 }
519
520 {
521 metadata::Mount m;
522 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700523 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700524 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
525 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
526 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800527 const auto metadata = m.SerializeAsString();
528 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800529 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800530 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800531 if (auto err =
532 mIncFs->makeFile(ifs->control,
533 path::join(ifs->root, constants().mount,
534 constants().infoMdName),
535 0777, idFromMetadata(metadata),
536 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800537 LOG(ERROR) << "Saving mount metadata failed: " << -err;
538 return kInvalidStorageId;
539 }
540 }
541
542 const auto bk =
543 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800544 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
545 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800546 err < 0) {
547 LOG(ERROR) << "adding bind mount failed: " << -err;
548 return kInvalidStorageId;
549 }
550
551 // Done here as well, all data structures are in good state.
552 secondCleanupOnFailure.release();
553
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700554 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
555 std::move(healthCheckParams), &healthListener);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700556 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800557
558 mountIt->second = std::move(ifs);
559 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700560
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700561 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700562 // failed to create data loader
563 LOG(ERROR) << "initializeDataLoader() failed";
564 deleteStorage(dataLoaderStub->id());
565 return kInvalidStorageId;
566 }
567
Songchun Fan3c82a302019-11-29 14:23:45 -0800568 LOG(INFO) << "created storage " << mountId;
569 return mountId;
570}
571
572StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
573 StorageId linkedStorage,
574 IncrementalService::CreateOptions options) {
575 if (!isValidMountTarget(mountPoint)) {
576 LOG(ERROR) << "Mount point is invalid or missing";
577 return kInvalidStorageId;
578 }
579
580 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700581 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800582 if (!ifs) {
583 LOG(ERROR) << "Ifs unavailable";
584 return kInvalidStorageId;
585 }
586
587 const auto mountIt = getStorageSlotLocked();
588 const auto storageId = mountIt->first;
589 const auto storageIt = ifs->makeStorage(storageId);
590 if (storageIt == ifs->storages.end()) {
591 LOG(ERROR) << "Can't create a new storage";
592 mMounts.erase(mountIt);
593 return kInvalidStorageId;
594 }
595
596 l.unlock();
597
598 const auto bk =
599 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800600 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
601 std::string(storageIt->second.name), path::normalize(mountPoint),
602 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800603 err < 0) {
604 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700605 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
606 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800607 return kInvalidStorageId;
608 }
609
610 mountIt->second = ifs;
611 return storageId;
612}
613
614IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
615 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700616 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800617}
618
619StorageId IncrementalService::findStorageId(std::string_view path) const {
620 std::lock_guard l(mLock);
621 auto it = findStorageLocked(path);
622 if (it == mBindsByPath.end()) {
623 return kInvalidStorageId;
624 }
625 return it->second->second.storage;
626}
627
Alex Buynytskyy04035452020-06-06 20:15:58 -0700628void IncrementalService::disableReadLogs(StorageId storageId) {
629 std::unique_lock l(mLock);
630 const auto ifs = getIfsLocked(storageId);
631 if (!ifs) {
632 LOG(ERROR) << "disableReadLogs failed, invalid storageId: " << storageId;
633 return;
634 }
635 if (!ifs->readLogsEnabled()) {
636 return;
637 }
638 ifs->disableReadLogs();
639 l.unlock();
640
641 const auto metadata = constants().readLogsDisabledMarkerName;
642 if (auto err = mIncFs->makeFile(ifs->control,
643 path::join(ifs->root, constants().mount,
644 constants().readLogsDisabledMarkerName),
645 0777, idFromMetadata(metadata), {})) {
646 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
647 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
648 return;
649 }
650
651 setStorageParams(storageId, /*enableReadLogs=*/false);
652}
653
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700654int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
655 const auto ifs = getIfs(storageId);
656 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700657 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700658 return -EINVAL;
659 }
660
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700661 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700662 if (enableReadLogs) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700663 if (!ifs->readLogsEnabled()) {
664 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
665 return -EPERM;
666 }
667
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700668 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
669 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700670 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700671 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700672 return fromBinderStatus(status);
673 }
674 }
675
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700676 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
677 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
678 return fromBinderStatus(status);
679 }
680
681 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700682 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700683 }
684
685 return 0;
686}
687
688binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700689 os::incremental::IncrementalFileSystemControlParcel control;
690 control.cmd.reset(dup(ifs.control.cmd()));
691 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700692 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700693 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700694 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700695 }
696
697 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700698 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700699}
700
Songchun Fan3c82a302019-11-29 14:23:45 -0800701void IncrementalService::deleteStorage(StorageId storageId) {
702 const auto ifs = getIfs(storageId);
703 if (!ifs) {
704 return;
705 }
706 deleteStorage(*ifs);
707}
708
709void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
710 std::unique_lock l(ifs.lock);
711 deleteStorageLocked(ifs, std::move(l));
712}
713
714void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
715 std::unique_lock<std::mutex>&& ifsLock) {
716 const auto storages = std::move(ifs.storages);
717 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
718 const auto bindPoints = ifs.bindPoints;
719 ifsLock.unlock();
720
721 std::lock_guard l(mLock);
722 for (auto&& [id, _] : storages) {
723 if (id != ifs.mountId) {
724 mMounts.erase(id);
725 }
726 }
727 for (auto&& [path, _] : bindPoints) {
728 mBindsByPath.erase(path);
729 }
730 mMounts.erase(ifs.mountId);
731}
732
733StorageId IncrementalService::openStorage(std::string_view pathInMount) {
734 if (!path::isAbsolute(pathInMount)) {
735 return kInvalidStorageId;
736 }
737
738 return findStorageId(path::normalize(pathInMount));
739}
740
Songchun Fan3c82a302019-11-29 14:23:45 -0800741IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
742 std::lock_guard l(mLock);
743 return getIfsLocked(storage);
744}
745
746const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
747 auto it = mMounts.find(storage);
748 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700749 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700750 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800751 }
752 return it->second;
753}
754
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800755int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
756 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800757 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700758 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800759 return -EINVAL;
760 }
761
762 const auto ifs = getIfs(storage);
763 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700764 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800765 return -EINVAL;
766 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800767
Songchun Fan3c82a302019-11-29 14:23:45 -0800768 std::unique_lock l(ifs->lock);
769 const auto storageInfo = ifs->storages.find(storage);
770 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700771 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800772 return -EINVAL;
773 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700774 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700775 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700776 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700777 return -EINVAL;
778 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800779 l.unlock();
780 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800781 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
782 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800783}
784
785int IncrementalService::unbind(StorageId storage, std::string_view target) {
786 if (!path::isAbsolute(target)) {
787 return -EINVAL;
788 }
789
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700790 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800791
792 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
793 // otherwise there's a chance to unmount something completely unrelated
794 const auto norm = path::normalize(target);
795 std::unique_lock l(mLock);
796 const auto storageIt = mBindsByPath.find(norm);
797 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
798 return -EINVAL;
799 }
800 const auto bindIt = storageIt->second;
801 const auto storageId = bindIt->second.storage;
802 const auto ifs = getIfsLocked(storageId);
803 if (!ifs) {
804 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
805 << " is missing";
806 return -EFAULT;
807 }
808 mBindsByPath.erase(storageIt);
809 l.unlock();
810
811 mVold->unmountIncFs(bindIt->first);
812 std::unique_lock l2(ifs->lock);
813 if (ifs->bindPoints.size() <= 1) {
814 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700815 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800816 } else {
817 const std::string savedFile = std::move(bindIt->second.savedFilename);
818 ifs->bindPoints.erase(bindIt);
819 l2.unlock();
820 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800821 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800822 }
823 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700824
Songchun Fan3c82a302019-11-29 14:23:45 -0800825 return 0;
826}
827
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700828std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700829 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700830 std::string_view path) const {
831 if (!path::isAbsolute(path)) {
832 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700833 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700834 auto normPath = path::normalize(path);
835 if (path::startsWith(normPath, storageIt->second.name)) {
836 return normPath;
837 }
838 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700839 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
840 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700841 return {};
842 }
843 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700844}
845
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700846std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700847 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700848 std::unique_lock l(ifs.lock);
849 const auto storageInfo = ifs.storages.find(storage);
850 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800851 return {};
852 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700853 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800854}
855
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800856int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
857 incfs::NewFileParams params) {
858 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700859 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800860 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700861 LOG(ERROR) << "Internal error: storageId " << storage
862 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800863 return -EINVAL;
864 }
865 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800866 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700867 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800868 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800869 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800870 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800871 }
872 return -EINVAL;
873}
874
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800875int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800876 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700877 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800878 if (normPath.empty()) {
879 return -EINVAL;
880 }
881 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800882 }
883 return -EINVAL;
884}
885
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800886int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800887 const auto ifs = getIfs(storageId);
888 if (!ifs) {
889 return -EINVAL;
890 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700891 return makeDirs(*ifs, storageId, path, mode);
892}
893
894int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
895 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800896 std::string normPath = normalizePathToStorage(ifs, storageId, path);
897 if (normPath.empty()) {
898 return -EINVAL;
899 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700900 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800901}
902
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800903int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
904 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700905 std::unique_lock l(mLock);
906 auto ifsSrc = getIfsLocked(sourceStorageId);
907 if (!ifsSrc) {
908 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800909 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700910 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
911 return -EINVAL;
912 }
913 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700914 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
915 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700916 if (normOldPath.empty() || normNewPath.empty()) {
917 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
918 return -EINVAL;
919 }
920 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800921}
922
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800923int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800924 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700925 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800926 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800927 }
928 return -EINVAL;
929}
930
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800931int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
932 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800933 std::string&& target, BindKind kind,
934 std::unique_lock<std::mutex>& mainLock) {
935 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700936 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800937 return -EINVAL;
938 }
939
940 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700941 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800942 if (kind != BindKind::Temporary) {
943 metadata::BindPoint bp;
944 bp.set_storage_id(storage);
945 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800946 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800947 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800948 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800949 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800950 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700951 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
952 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
953 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800954 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700955 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800956 return int(node);
957 }
958 }
959
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700960 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
961 std::move(target), kind, mainLock);
962 if (res) {
963 mIncFs->unlink(ifs.control, metadataFullPath);
964 }
965 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800966}
967
968int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800969 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800970 std::string&& target, BindKind kind,
971 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800972 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800973 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800974 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800975 if (!status.isOk()) {
976 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
977 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
978 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
979 : status.serviceSpecificErrorCode() == 0
980 ? -EFAULT
981 : status.serviceSpecificErrorCode()
982 : -EIO;
983 }
984 }
985
986 if (!mainLock.owns_lock()) {
987 mainLock.lock();
988 }
989 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700990 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
991 std::move(target), kind);
992 return 0;
993}
994
995void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
996 std::string&& metadataName, std::string&& source,
997 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800998 const auto [it, _] =
999 ifs.bindPoints.insert_or_assign(target,
1000 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001001 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001002 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001003}
1004
1005RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1006 const auto ifs = getIfs(storage);
1007 if (!ifs) {
1008 return {};
1009 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001010 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001011 if (normPath.empty()) {
1012 return {};
1013 }
1014 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001015}
1016
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001017RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001018 const auto ifs = getIfs(storage);
1019 if (!ifs) {
1020 return {};
1021 }
1022 return mIncFs->getMetadata(ifs->control, node);
1023}
1024
Songchun Fan3c82a302019-11-29 14:23:45 -08001025bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001026 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001027 {
1028 std::unique_lock l(mLock);
1029 const auto& ifs = getIfsLocked(storage);
1030 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001031 return false;
1032 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001033 dataLoaderStub = ifs->dataLoaderStub;
1034 if (!dataLoaderStub) {
1035 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001036 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001037 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001038 dataLoaderStub->requestStart();
1039 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001040}
1041
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001042std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1043 std::unordered_set<std::string_view> mountedRootNames;
1044 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1045 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1046 for (auto [source, target] : binds) {
1047 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1048 LOG(INFO) << " " << path::join(root, source);
1049 }
1050
1051 // Ensure it's a kind of a mount that's managed by IncrementalService
1052 if (path::basename(root) != constants().mount ||
1053 path::basename(backingDir) != constants().backing) {
1054 return;
1055 }
1056 const auto expectedRoot = path::dirname(root);
1057 if (path::dirname(backingDir) != expectedRoot) {
1058 return;
1059 }
1060 if (path::dirname(expectedRoot) != mIncrementalDir) {
1061 return;
1062 }
1063 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1064 return;
1065 }
1066
1067 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1068
1069 // make sure we clean up the mount if it happens to be a bad one.
1070 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1071 auto cleanupFiles = makeCleanup([&]() {
1072 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1073 IncFsMount::cleanupFilesystem(expectedRoot);
1074 });
1075 auto cleanupMounts = makeCleanup([&]() {
1076 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1077 for (auto&& [_, target] : binds) {
1078 mVold->unmountIncFs(std::string(target));
1079 }
1080 mVold->unmountIncFs(std::string(root));
1081 });
1082
1083 auto control = mIncFs->openMount(root);
1084 if (!control) {
1085 LOG(INFO) << "failed to open mount " << root;
1086 return;
1087 }
1088
1089 auto mountRecord =
1090 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1091 path::join(root, constants().infoMdName));
1092 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1093 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1094 return;
1095 }
1096
1097 auto mountId = mountRecord.storage().id();
1098 mNextId = std::max(mNextId, mountId + 1);
1099
1100 DataLoaderParamsParcel dataLoaderParams;
1101 {
1102 const auto& loader = mountRecord.loader();
1103 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1104 dataLoaderParams.packageName = loader.package_name();
1105 dataLoaderParams.className = loader.class_name();
1106 dataLoaderParams.arguments = loader.arguments();
1107 }
1108
1109 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1110 std::move(control), *this);
1111 cleanupFiles.release(); // ifs will take care of that now
1112
Alex Buynytskyy04035452020-06-06 20:15:58 -07001113 // Check if marker file present.
1114 if (checkReadLogsDisabledMarker(root)) {
1115 ifs->disableReadLogs();
1116 }
1117
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001118 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1119 auto d = openDir(root);
1120 while (auto e = ::readdir(d.get())) {
1121 if (e->d_type == DT_REG) {
1122 auto name = std::string_view(e->d_name);
1123 if (name.starts_with(constants().mountpointMdPrefix)) {
1124 permanentBindPoints
1125 .emplace_back(name,
1126 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1127 ifs->control,
1128 path::join(root,
1129 name)));
1130 if (permanentBindPoints.back().second.dest_path().empty() ||
1131 permanentBindPoints.back().second.source_subdir().empty()) {
1132 permanentBindPoints.pop_back();
1133 mIncFs->unlink(ifs->control, path::join(root, name));
1134 } else {
1135 LOG(INFO) << "Permanent bind record: '"
1136 << permanentBindPoints.back().second.source_subdir() << "'->'"
1137 << permanentBindPoints.back().second.dest_path() << "'";
1138 }
1139 }
1140 } else if (e->d_type == DT_DIR) {
1141 if (e->d_name == "."sv || e->d_name == ".."sv) {
1142 continue;
1143 }
1144 auto name = std::string_view(e->d_name);
1145 if (name.starts_with(constants().storagePrefix)) {
1146 int storageId;
1147 const auto res =
1148 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1149 name.data() + name.size(), storageId);
1150 if (res.ec != std::errc{} || *res.ptr != '_') {
1151 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1152 << "' for mount " << expectedRoot;
1153 continue;
1154 }
1155 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1156 if (!inserted) {
1157 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1158 << " for mount " << expectedRoot;
1159 continue;
1160 }
1161 ifs->storages.insert_or_assign(storageId,
1162 IncFsMount::Storage{path::join(root, name)});
1163 mNextId = std::max(mNextId, storageId + 1);
1164 }
1165 }
1166 }
1167
1168 if (ifs->storages.empty()) {
1169 LOG(WARNING) << "No valid storages in mount " << root;
1170 return;
1171 }
1172
1173 // now match the mounted directories with what we expect to have in the metadata
1174 {
1175 std::unique_lock l(mLock, std::defer_lock);
1176 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1177 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1178 [&, bindRecord = bindRecord](auto&& bind) {
1179 return bind.second == bindRecord.dest_path() &&
1180 path::join(root, bind.first) ==
1181 bindRecord.source_subdir();
1182 });
1183 if (mountedIt != binds.end()) {
1184 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1185 << " to mount " << mountedIt->first;
1186 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1187 std::move(*bindRecord.mutable_source_subdir()),
1188 std::move(*bindRecord.mutable_dest_path()),
1189 BindKind::Permanent);
1190 if (mountedIt != binds.end() - 1) {
1191 std::iter_swap(mountedIt, binds.end() - 1);
1192 }
1193 binds = binds.first(binds.size() - 1);
1194 } else {
1195 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1196 << ", mounting";
1197 // doesn't exist - try mounting back
1198 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1199 std::move(*bindRecord.mutable_source_subdir()),
1200 std::move(*bindRecord.mutable_dest_path()),
1201 BindKind::Permanent, l)) {
1202 mIncFs->unlink(ifs->control, metadataFile);
1203 }
1204 }
1205 }
1206 }
1207
1208 // if anything stays in |binds| those are probably temporary binds; system restarted since
1209 // they were mounted - so let's unmount them all.
1210 for (auto&& [source, target] : binds) {
1211 if (source.empty()) {
1212 continue;
1213 }
1214 mVold->unmountIncFs(std::string(target));
1215 }
1216 cleanupMounts.release(); // ifs now manages everything
1217
1218 if (ifs->bindPoints.empty()) {
1219 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1220 deleteStorage(*ifs);
1221 return;
1222 }
1223
1224 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1225 CHECK(ifs->dataLoaderStub);
1226
1227 mountedRootNames.insert(path::basename(ifs->root));
1228
1229 // not locking here at all: we're still in the constructor, no other calls can happen
1230 mMounts[ifs->mountId] = std::move(ifs);
1231 });
1232
1233 return mountedRootNames;
1234}
1235
1236void IncrementalService::mountExistingImages(
1237 const std::unordered_set<std::string_view>& mountedRootNames) {
1238 auto dir = openDir(mIncrementalDir);
1239 if (!dir) {
1240 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1241 return;
1242 }
1243 while (auto entry = ::readdir(dir.get())) {
1244 if (entry->d_type != DT_DIR) {
1245 continue;
1246 }
1247 std::string_view name = entry->d_name;
1248 if (!name.starts_with(constants().mountKeyPrefix)) {
1249 continue;
1250 }
1251 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001252 continue;
1253 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001254 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001255 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001256 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001257 }
1258 }
1259}
1260
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001261bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001262 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001263 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001264
Songchun Fan3c82a302019-11-29 14:23:45 -08001265 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001266 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001267 if (!status.isOk()) {
1268 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1269 return false;
1270 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001271
1272 int cmd = controlParcel.cmd.release().release();
1273 int pendingReads = controlParcel.pendingReads.release().release();
1274 int logs = controlParcel.log.release().release();
1275 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001276
1277 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1278
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001279 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1280 path::join(mountTarget, constants().infoMdName));
1281 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001282 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1283 return false;
1284 }
1285
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001286 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001287 mNextId = std::max(mNextId, ifs->mountId + 1);
1288
Alex Buynytskyy04035452020-06-06 20:15:58 -07001289 // Check if marker file present.
1290 if (checkReadLogsDisabledMarker(mountTarget)) {
1291 ifs->disableReadLogs();
1292 }
1293
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001294 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001295 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001296 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001297 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001298 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001299 dataLoaderParams.packageName = loader.package_name();
1300 dataLoaderParams.className = loader.class_name();
1301 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001302 }
1303
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001304 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001305 CHECK(ifs->dataLoaderStub);
1306
Songchun Fan3c82a302019-11-29 14:23:45 -08001307 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001308 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001309 while (auto e = ::readdir(d.get())) {
1310 if (e->d_type == DT_REG) {
1311 auto name = std::string_view(e->d_name);
1312 if (name.starts_with(constants().mountpointMdPrefix)) {
1313 bindPoints.emplace_back(name,
1314 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1315 ifs->control,
1316 path::join(mountTarget,
1317 name)));
1318 if (bindPoints.back().second.dest_path().empty() ||
1319 bindPoints.back().second.source_subdir().empty()) {
1320 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001321 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001322 }
1323 }
1324 } else if (e->d_type == DT_DIR) {
1325 if (e->d_name == "."sv || e->d_name == ".."sv) {
1326 continue;
1327 }
1328 auto name = std::string_view(e->d_name);
1329 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001330 int storageId;
1331 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1332 name.data() + name.size(), storageId);
1333 if (res.ec != std::errc{} || *res.ptr != '_') {
1334 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1335 << root;
1336 continue;
1337 }
1338 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001339 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001340 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001341 << " for mount " << root;
1342 continue;
1343 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001344 ifs->storages.insert_or_assign(storageId,
1345 IncFsMount::Storage{
1346 path::join(root, constants().mount, name)});
1347 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001348 }
1349 }
1350 }
1351
1352 if (ifs->storages.empty()) {
1353 LOG(WARNING) << "No valid storages in mount " << root;
1354 return false;
1355 }
1356
1357 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001358 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001359 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001360 for (auto&& bp : bindPoints) {
1361 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1362 std::move(*bp.second.mutable_source_subdir()),
1363 std::move(*bp.second.mutable_dest_path()),
1364 BindKind::Permanent, l);
1365 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001366 }
1367
1368 if (bindCount == 0) {
1369 LOG(WARNING) << "No valid bind points for mount " << root;
1370 deleteStorage(*ifs);
1371 return false;
1372 }
1373
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001374 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001375 mMounts[ifs->mountId] = std::move(ifs);
1376 return true;
1377}
1378
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001379void IncrementalService::runCmdLooper() {
1380 constexpr auto kTimeoutMsecs = 1000;
1381 while (mRunning.load(std::memory_order_relaxed)) {
1382 mLooper->pollAll(kTimeoutMsecs);
1383 }
1384}
1385
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001386IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001387 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001388 const DataLoaderStatusListener* statusListener,
1389 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001390 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001391 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1392 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001393 return ifs.dataLoaderStub;
1394}
1395
1396void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001397 const DataLoaderStatusListener* statusListener,
1398 StorageHealthCheckParams&& healthCheckParams,
1399 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001400 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001401 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001402 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001403 }
1404
Songchun Fan3c82a302019-11-29 14:23:45 -08001405 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001406 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001407 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1408 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1409 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001410 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001411
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001412 ifs.dataLoaderStub =
1413 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001414 statusListener, std::move(healthCheckParams), healthListener,
1415 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001416}
1417
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001418template <class Duration>
1419static long elapsedMcs(Duration start, Duration end) {
1420 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1421}
1422
1423// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001424// Lib files should be placed next to the APK file in the following matter:
1425// Example:
1426// /path/to/base.apk
1427// /path/to/lib/arm/first.so
1428// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001429bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1430 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001431 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001432 auto start = Clock::now();
1433
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001434 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001435 if (!ifs) {
1436 LOG(ERROR) << "Invalid storage " << storage;
1437 return false;
1438 }
1439
Songchun Fanc8975312020-07-13 12:14:37 -07001440 const auto targetLibPathRelativeToStorage =
1441 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1442 libDirRelativePath);
1443
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001444 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001445 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1446 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001447 << " errno: " << res;
1448 return false;
1449 }
1450
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001451 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001452 ZipArchiveHandle zipFileHandle;
1453 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001454 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1455 return false;
1456 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001457
1458 // Need a shared pointer: will be passing it into all unpacking jobs.
1459 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001460 void* cookie = nullptr;
1461 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001462 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001463 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1464 return false;
1465 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001466 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001467 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1468
1469 auto openZipTs = Clock::now();
1470
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001471 std::vector<Job> jobQueue;
1472 ZipEntry entry;
1473 std::string_view fileName;
1474 while (!Next(cookie, &entry, &fileName)) {
1475 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001476 continue;
1477 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001478
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001479 if (!extractNativeLibs) {
1480 // ensure the file is properly aligned and unpacked
1481 if (entry.method != kCompressStored) {
1482 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1483 return false;
1484 }
1485 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1486 LOG(WARNING) << "Library " << fileName
1487 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1488 << entry.offset;
1489 return false;
1490 }
1491 continue;
1492 }
1493
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001494 auto startFileTs = Clock::now();
1495
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001496 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001497 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001498 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001499 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001500 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001501 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001502 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1503 << "; skipping extraction, spent "
1504 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1505 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001506 continue;
1507 }
1508
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001509 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001510 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001511 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001512 .signature = {},
1513 // Metadata of the new lib file is its relative path
1514 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1515 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001516 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001517 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1518 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001519 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001520 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001521 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001522 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001523
1524 auto makeFileTs = Clock::now();
1525
Songchun Fanafaf6e92020-03-18 14:12:20 -07001526 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001527 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001528 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001529 LOG(INFO) << "incfs: Extracted " << libName
1530 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001531 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001532 continue;
1533 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001534
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001535 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1536 libFileId, libPath = std::move(targetLibPath),
1537 makeFileTs]() mutable {
1538 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001539 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001540
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001541 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001542 auto prepareJobTs = Clock::now();
1543 LOG(INFO) << "incfs: Processed " << libName << ": "
1544 << elapsedMcs(startFileTs, prepareJobTs)
1545 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1546 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001547 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001548 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001549
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001550 auto processedTs = Clock::now();
1551
1552 if (!jobQueue.empty()) {
1553 {
1554 std::lock_guard lock(mJobMutex);
1555 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001556 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001557 if (existingJobs.empty()) {
1558 existingJobs = std::move(jobQueue);
1559 } else {
1560 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1561 std::move_iterator(jobQueue.end()));
1562 }
1563 }
1564 }
1565 mJobCondition.notify_all();
1566 }
1567
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001568 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001569 auto end = Clock::now();
1570 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1571 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1572 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001573 << " make files: " << elapsedMcs(openZipTs, processedTs)
1574 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001575 }
1576
1577 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001578}
1579
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001580void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1581 ZipEntry& entry, const incfs::FileId& libFileId,
1582 std::string_view targetLibPath,
1583 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001584 if (!ifs) {
1585 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1586 return;
1587 }
1588
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001589 auto libName = path::basename(targetLibPath);
1590 auto startedTs = Clock::now();
1591
1592 // Write extracted data to new file
1593 // NOTE: don't zero-initialize memory, it may take a while for nothing
1594 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1595 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1596 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1597 return;
1598 }
1599
1600 auto extractFileTs = Clock::now();
1601
1602 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1603 if (!writeFd.ok()) {
1604 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1605 return;
1606 }
1607
1608 auto openFileTs = Clock::now();
1609 const int numBlocks =
1610 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1611 std::vector<IncFsDataBlock> instructions(numBlocks);
1612 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1613 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001614 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001615 instructions[i] = IncFsDataBlock{
1616 .fileFd = writeFd.get(),
1617 .pageIndex = static_cast<IncFsBlockIndex>(i),
1618 .compression = INCFS_COMPRESSION_KIND_NONE,
1619 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001620 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001621 .data = reinterpret_cast<const char*>(remainingData.data()),
1622 };
1623 remainingData = remainingData.subspan(blockSize);
1624 }
1625 auto prepareInstsTs = Clock::now();
1626
1627 size_t res = mIncFs->writeBlocks(instructions);
1628 if (res != instructions.size()) {
1629 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1630 return;
1631 }
1632
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001633 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001634 auto endFileTs = Clock::now();
1635 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1636 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1637 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1638 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1639 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1640 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1641 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1642 }
1643}
1644
1645bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001646 struct WaitPrinter {
1647 const Clock::time_point startTs = Clock::now();
1648 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001649 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001650 const auto endTs = Clock::now();
1651 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1652 << elapsedMcs(startTs, endTs) << "mcs";
1653 }
1654 }
1655 } waitPrinter;
1656
1657 MountId mount;
1658 {
1659 auto ifs = getIfs(storage);
1660 if (!ifs) {
1661 return true;
1662 }
1663 mount = ifs->mountId;
1664 }
1665
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001666 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001667 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001668 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001669 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001670 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001671 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001672}
1673
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001674bool IncrementalService::perfLoggingEnabled() {
1675 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1676 return enabled;
1677}
1678
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001679void IncrementalService::runJobProcessing() {
1680 for (;;) {
1681 std::unique_lock lock(mJobMutex);
1682 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1683 if (!mRunning) {
1684 return;
1685 }
1686
1687 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001688 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001689 auto queue = std::move(it->second);
1690 mJobQueue.erase(it);
1691 lock.unlock();
1692
1693 for (auto&& job : queue) {
1694 job();
1695 }
1696
1697 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001698 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001699 lock.unlock();
1700 mJobCondition.notify_all();
1701 }
1702}
1703
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001704void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001705 sp<IAppOpsCallback> listener;
1706 {
1707 std::unique_lock lock{mCallbacksLock};
1708 auto& cb = mCallbackRegistered[packageName];
1709 if (cb) {
1710 return;
1711 }
1712 cb = new AppOpsListener(*this, packageName);
1713 listener = cb;
1714 }
1715
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001716 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1717 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001718}
1719
1720bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1721 sp<IAppOpsCallback> listener;
1722 {
1723 std::unique_lock lock{mCallbacksLock};
1724 auto found = mCallbackRegistered.find(packageName);
1725 if (found == mCallbackRegistered.end()) {
1726 return false;
1727 }
1728 listener = found->second;
1729 mCallbackRegistered.erase(found);
1730 }
1731
1732 mAppOpsManager->stopWatchingMode(listener);
1733 return true;
1734}
1735
1736void IncrementalService::onAppOpChanged(const std::string& packageName) {
1737 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001738 return;
1739 }
1740
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001741 std::vector<IfsMountPtr> affected;
1742 {
1743 std::lock_guard l(mLock);
1744 affected.reserve(mMounts.size());
1745 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001746 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001747 affected.push_back(ifs);
1748 }
1749 }
1750 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001751 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001752 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001753 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001754}
1755
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07001756void IncrementalService::addTimedJob(MountId id, Milliseconds after, Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001757 if (id == kInvalidStorageId) {
1758 return;
1759 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07001760 mTimedQueue->addJob(id, after, std::move(what));
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001761}
1762
1763void IncrementalService::removeTimedJobs(MountId id) {
1764 if (id == kInvalidStorageId) {
1765 return;
1766 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07001767 mTimedQueue->removeJobs(id);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001768}
1769
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001770IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1771 DataLoaderParamsParcel&& params,
1772 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001773 const DataLoaderStatusListener* statusListener,
1774 StorageHealthCheckParams&& healthCheckParams,
1775 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001776 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001777 : mService(service),
1778 mId(id),
1779 mParams(std::move(params)),
1780 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001781 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
1782 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001783 mHealthPath(std::move(healthPath)),
1784 mHealthCheckParams(std::move(healthCheckParams)) {
1785 if (mHealthListener) {
1786 if (!isHealthParamsValid()) {
1787 mHealthListener = {};
1788 }
1789 } else {
1790 // Disable advanced health check statuses.
1791 mHealthCheckParams.blockedTimeoutMs = -1;
1792 }
1793 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001794}
1795
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001796IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001797 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001798 cleanupResources();
1799 }
1800}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001801
1802void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001803 auto now = Clock::now();
1804 {
1805 std::unique_lock lock(mMutex);
1806 mHealthPath.clear();
1807 unregisterFromPendingReads();
1808 resetHealthControl();
1809 mService.removeTimedJobs(mId);
1810 }
1811
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001812 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001813
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001814 {
1815 std::unique_lock lock(mMutex);
1816 mParams = {};
1817 mControl = {};
1818 mHealthControl = {};
1819 mHealthListener = {};
1820 mStatusCondition.wait_until(lock, now + 60s, [this] {
1821 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1822 });
1823 mStatusListener = {};
1824 mId = kInvalidStorageId;
1825 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001826}
1827
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001828sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1829 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001830 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001831 if (!status.isOk()) {
1832 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1833 return {};
1834 }
1835 if (!dataloader) {
1836 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1837 return {};
1838 }
1839 return dataloader;
1840}
1841
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001842bool IncrementalService::DataLoaderStub::requestCreate() {
1843 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1844}
1845
1846bool IncrementalService::DataLoaderStub::requestStart() {
1847 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1848}
1849
1850bool IncrementalService::DataLoaderStub::requestDestroy() {
1851 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1852}
1853
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001854bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001855 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001856 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001857 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001858 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001859 return fsmStep();
1860}
1861
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001862void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001863 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001864 mTargetStatus = status;
1865 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001866 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001867 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001868}
1869
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001870bool IncrementalService::DataLoaderStub::bind() {
1871 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001872 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001873 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001874 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001875 return false;
1876 }
1877 return true;
1878}
1879
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001880bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001881 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001882 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001883 return false;
1884 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001885 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001886 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001887 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001888 return false;
1889 }
1890 return true;
1891}
1892
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001893bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001894 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001895 if (!dataloader) {
1896 return false;
1897 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001898 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001899 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001900 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001901 return false;
1902 }
1903 return true;
1904}
1905
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001906bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001907 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001908}
1909
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001910bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001911 if (!isValid()) {
1912 return false;
1913 }
1914
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001915 int currentStatus;
1916 int targetStatus;
1917 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001918 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001919 currentStatus = mCurrentStatus;
1920 targetStatus = mTargetStatus;
1921 }
1922
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001923 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001924
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001925 if (currentStatus == targetStatus) {
1926 return true;
1927 }
1928
1929 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001930 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
1931 // Do nothing, this is a reset state.
1932 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001933 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1934 return destroy();
1935 }
1936 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1937 switch (currentStatus) {
1938 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1939 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1940 return start();
1941 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001942 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001943 }
1944 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1945 switch (currentStatus) {
1946 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001947 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001948 return bind();
1949 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001950 return create();
1951 }
1952 break;
1953 default:
1954 LOG(ERROR) << "Invalid target status: " << targetStatus
1955 << ", current status: " << currentStatus;
1956 break;
1957 }
1958 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001959}
1960
1961binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001962 if (!isValid()) {
1963 return binder::Status::
1964 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
1965 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001966 if (id() != mountId) {
1967 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001968 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
1969 }
1970
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001971 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001972 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001973 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001974 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001975 if (mCurrentStatus == newStatus) {
1976 return binder::Status::ok();
1977 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001978
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001979 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001980 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001981 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001982
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001983 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001984
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001985 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001986 // For unavailable, unbind from DataLoader to ensure proper re-commit.
1987 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001988 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001989 }
1990
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001991 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001992 << newStatus << " (target " << targetStatus << ")";
1993
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001994 if (listener) {
1995 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001996 }
1997
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001998 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08001999
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002000 mStatusCondition.notify_all();
2001
Songchun Fan3c82a302019-11-29 14:23:45 -08002002 return binder::Status::ok();
2003}
2004
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002005bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2006 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2007 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002008}
2009
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002010void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2011 int healthStatus) {
2012 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2013 if (healthListener) {
2014 healthListener->onHealthStatus(id(), healthStatus);
2015 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002016}
2017
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002018void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2019 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002020
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002021 int healthStatusToReport = -1;
2022 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002023
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002024 {
2025 std::unique_lock lock(mMutex);
2026 unregisterFromPendingReads();
2027
2028 healthListener = mHealthListener;
2029
2030 // Healthcheck depends on timestamp of the oldest pending read.
2031 // To get it, we need to re-open a pendingReads FD to get a full list of reads.
2032 // Additionally we need to re-register for epoll with fresh FDs in case there are no reads.
2033 const auto now = Clock::now();
2034 const auto kernelTsUs = getOldestPendingReadTs();
2035 if (baseline) {
2036 // Updating baseline only on looper/epoll callback, i.e. on new set of pending reads.
2037 mHealthBase = {now, kernelTsUs};
2038 }
2039
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002040 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2041 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002042 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2043 registerForPendingReads();
2044 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2045 lock.unlock();
2046 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002047 return;
2048 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002049
2050 resetHealthControl();
2051
2052 // Always make sure the data loader is started.
2053 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2054
2055 // Skip any further processing if health check params are invalid.
2056 if (!isHealthParamsValid()) {
2057 LOG(DEBUG) << id()
2058 << ": Skip any further processing if health check params are invalid.";
2059 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2060 lock.unlock();
2061 onHealthStatus(healthListener, healthStatusToReport);
2062 // Triggering data loader start. This is a one-time action.
2063 fsmStep();
2064 return;
2065 }
2066
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002067 // Don't schedule timer job less than 500ms in advance.
2068 static constexpr auto kTolerance = 500ms;
2069
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002070 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2071 const auto unhealthyTimeout =
2072 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2073 const auto unhealthyMonitoring =
2074 std::max(1000ms,
2075 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2076
2077 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2078 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002079 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002080
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002081 Milliseconds checkBackAfter;
2082 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002083 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002084 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002085 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002086 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002087 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002088 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002089 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2090 } else {
2091 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002092 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002093 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2094 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002095 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002096 << "secs";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002097 mService.addTimedJob(id(), checkBackAfter, [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002098 }
2099
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002100 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002101 if (healthStatusToReport != -1) {
2102 onHealthStatus(healthListener, healthStatusToReport);
2103 }
2104
2105 fsmStep();
2106}
2107
2108const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2109 if (mHealthPath.empty()) {
2110 resetHealthControl();
2111 return mHealthControl;
2112 }
2113 if (mHealthControl.pendingReads() < 0) {
2114 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2115 }
2116 if (mHealthControl.pendingReads() < 0) {
2117 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2118 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2119 << mHealthControl.logs() << ")";
2120 }
2121 return mHealthControl;
2122}
2123
2124void IncrementalService::DataLoaderStub::resetHealthControl() {
2125 mHealthControl = {};
2126}
2127
2128BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2129 auto result = kMaxBootClockTsUs;
2130
2131 const auto& control = initializeHealthControl();
2132 if (control.pendingReads() < 0) {
2133 return result;
2134 }
2135
2136 std::vector<incfs::ReadInfo> pendingReads;
2137 if (mService.mIncFs->waitForPendingReads(control, 0ms, &pendingReads) !=
2138 android::incfs::WaitResult::HaveData ||
2139 pendingReads.empty()) {
2140 return result;
2141 }
2142
2143 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
2144 << pendingReads.size() << ": " << pendingReads.front().bootClockTsUs;
2145
2146 for (auto&& pendingRead : pendingReads) {
2147 result = std::min(result, pendingRead.bootClockTsUs);
2148 }
2149 return result;
2150}
2151
2152void IncrementalService::DataLoaderStub::registerForPendingReads() {
2153 const auto pendingReadsFd = mHealthControl.pendingReads();
2154 if (pendingReadsFd < 0) {
2155 return;
2156 }
2157
2158 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2159
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002160 mService.mLooper->addFd(
2161 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2162 [](int, int, void* data) -> int {
2163 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002164 self->updateHealthStatus(/*baseline=*/true);
2165 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002166 },
2167 this);
2168 mService.mLooper->wake();
2169}
2170
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002171void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002172 const auto pendingReadsFd = mHealthControl.pendingReads();
2173 if (pendingReadsFd < 0) {
2174 return;
2175 }
2176
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002177 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2178
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002179 mService.mLooper->removeFd(pendingReadsFd);
2180 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002181}
2182
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002183void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002184 dprintf(fd, " dataLoader: {\n");
2185 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2186 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2187 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002188 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002189 dprintf(fd, " health: {\n");
2190 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2191 dprintf(fd, " base: %lldmcs (%lld)\n",
2192 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2193 (long long)mHealthBase.kernelTsUs);
2194 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2195 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2196 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2197 int(mHealthCheckParams.unhealthyMonitoringMs));
2198 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002199 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002200 dprintf(fd, " dataLoaderParams: {\n");
2201 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2202 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2203 dprintf(fd, " className: %s\n", params.className.c_str());
2204 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2205 dprintf(fd, " }\n");
2206 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002207}
2208
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002209void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2210 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002211}
2212
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002213binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2214 bool enableReadLogs, int32_t* _aidl_return) {
2215 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2216 return binder::Status::ok();
2217}
2218
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002219FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2220 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2221}
2222
Songchun Fan3c82a302019-11-29 14:23:45 -08002223} // namespace android::incremental