blob: 885f4d2d34d7c658df3186c97f044c3983aeed45 [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "IncrementalService"
18
19#include "IncrementalService.h"
20
Songchun Fan3c82a302019-11-29 14:23:45 -080021#include <android-base/logging.h>
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -070022#include <android-base/no_destructor.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080023#include <android-base/properties.h>
24#include <android-base/stringprintf.h>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070025#include <binder/AppOpsManager.h>
Jooyung Han66c567a2020-03-07 21:47:09 +090026#include <binder/Nullable.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080027#include <binder/Status.h>
28#include <sys/stat.h>
29#include <uuid/uuid.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080030
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070031#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080032#include <ctime>
Songchun Fan3c82a302019-11-29 14:23:45 -080033#include <iterator>
34#include <span>
Songchun Fan3c82a302019-11-29 14:23:45 -080035#include <type_traits>
36
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070037#include "IncrementalServiceValidation.h"
Songchun Fan3c82a302019-11-29 14:23:45 -080038#include "Metadata.pb.h"
39
40using namespace std::literals;
Songchun Fan1124fd32020-02-10 12:49:41 -080041namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080042
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070043constexpr const char* kDataUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070044constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070045
Songchun Fan3c82a302019-11-29 14:23:45 -080046namespace android::incremental {
47
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070048using content::pm::DataLoaderParamsParcel;
49using content::pm::FileSystemControlParcel;
50using content::pm::IDataLoader;
51
Songchun Fan3c82a302019-11-29 14:23:45 -080052namespace {
53
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070054using IncrementalFileSystemControlParcel = os::incremental::IncrementalFileSystemControlParcel;
Songchun Fan3c82a302019-11-29 14:23:45 -080055
56struct Constants {
57 static constexpr auto backing = "backing_store"sv;
58 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080059 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080060 static constexpr auto storagePrefix = "st"sv;
61 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
62 static constexpr auto infoMdName = ".info"sv;
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}
175} // namespace
176
177IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700178 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700179 dataLoaderStub->cleanupResources();
180 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700181 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700182 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800183 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
184 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700185 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800186 incrementalService.mVold->unmountIncFs(target);
187 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700188 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800189 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
190 cleanupFilesystem(root);
191}
192
193auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800194 std::string name;
195 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
196 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
197 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800198 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
199 constants().storagePrefix.data(), id, no);
200 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800201 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800202 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800203 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
204 } else if (err != EEXIST) {
205 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
206 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800207 }
208 }
209 nextStorageDirNo = 0;
210 return storages.end();
211}
212
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700213template <class Func>
214static auto makeCleanup(Func&& f) {
215 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700216 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700217 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
218}
219
220static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
221 return {::opendir(dir), ::closedir};
222}
223
224static auto openDir(std::string_view dir) {
225 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800226}
227
228static int rmDirContent(const char* path) {
229 auto dir = openDir(path);
230 if (!dir) {
231 return -EINVAL;
232 }
233 while (auto entry = ::readdir(dir.get())) {
234 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
235 continue;
236 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700237 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800238 if (entry->d_type == DT_DIR) {
239 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
240 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
241 return err;
242 }
243 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
244 PLOG(WARNING) << "Failed to rmdir " << fullPath;
245 return err;
246 }
247 } else {
248 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
249 PLOG(WARNING) << "Failed to delete " << fullPath;
250 return err;
251 }
252 }
253 }
254 return 0;
255}
256
Songchun Fan3c82a302019-11-29 14:23:45 -0800257void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800258 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800259 ::rmdir(path::join(root, constants().backing).c_str());
260 ::rmdir(path::join(root, constants().mount).c_str());
261 ::rmdir(path::c_str(root));
262}
263
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800264IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800265 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800266 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800267 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700268 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700269 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700270 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700271 mTimedQueue(sm.getTimedQueue()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800272 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700273 CHECK(mVold) << "Vold service is unavailable";
274 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
275 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
276 CHECK(mJni) << "JNI is unavailable";
277 CHECK(mLooper) << "Looper is unavailable";
278 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700279
280 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700281 mJobProcessor = std::thread([this]() {
282 mJni->initializeForCurrentThread();
283 runJobProcessing();
284 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700285 mCmdLooperThread = std::thread([this]() {
286 mJni->initializeForCurrentThread();
287 runCmdLooper();
288 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700289
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700290 const auto mountedRootNames = adoptMountedInstances();
291 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800292}
293
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700294IncrementalService::~IncrementalService() {
295 {
296 std::lock_guard lock(mJobMutex);
297 mRunning = false;
298 }
299 mJobCondition.notify_all();
300 mJobProcessor.join();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700301 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700302 mTimedQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700303 // Ensure that mounts are destroyed while the service is still valid.
304 mBindsByPath.clear();
305 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700306}
Songchun Fan3c82a302019-11-29 14:23:45 -0800307
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700308static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800309 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800310 case IncrementalService::BindKind::Temporary:
311 return "Temporary";
312 case IncrementalService::BindKind::Permanent:
313 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800314 }
315}
316
317void IncrementalService::onDump(int fd) {
318 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
319 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
320
321 std::unique_lock l(mLock);
322
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700323 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800324 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700325 const IncFsMount& mnt = *ifs;
326 dprintf(fd, " [%d]: {\n", id);
327 if (id != mnt.mountId) {
328 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
329 } else {
330 dprintf(fd, " mountId: %d\n", mnt.mountId);
331 dprintf(fd, " root: %s\n", mnt.root.c_str());
332 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
333 if (mnt.dataLoaderStub) {
334 mnt.dataLoaderStub->onDump(fd);
335 } else {
336 dprintf(fd, " dataLoader: null\n");
337 }
338 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
339 for (auto&& [storageId, storage] : mnt.storages) {
340 dprintf(fd, " [%d] -> [%s]\n", storageId, storage.name.c_str());
341 }
342 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800343
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700344 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
345 for (auto&& [target, bind] : mnt.bindPoints) {
346 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
347 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
348 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
349 dprintf(fd, " kind: %s\n", toString(bind.kind));
350 }
351 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800352 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700353 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800354 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700355 dprintf(fd, "}\n");
356 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800357 for (auto&& [target, mountPairIt] : mBindsByPath) {
358 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700359 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
360 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
361 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
362 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800363 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700364 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800365}
366
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700367void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800368 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700369 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800370 }
371
372 std::vector<IfsMountPtr> mounts;
373 {
374 std::lock_guard l(mLock);
375 mounts.reserve(mMounts.size());
376 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -0700377 if (ifs->mountId == id &&
378 ifs->dataLoaderStub->params().packageName == Constants::systemPackage) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800379 mounts.push_back(ifs);
380 }
381 }
382 }
383
Alex Buynytskyy69941662020-04-11 21:40:37 -0700384 if (mounts.empty()) {
385 return;
386 }
387
Songchun Fan3c82a302019-11-29 14:23:45 -0800388 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700389 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800390 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700391 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800392 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800393 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800394}
395
396auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
397 for (;;) {
398 if (mNextId == kMaxStorageId) {
399 mNextId = 0;
400 }
401 auto id = ++mNextId;
402 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
403 if (inserted) {
404 return it;
405 }
406 }
407}
408
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700409StorageId IncrementalService::createStorage(std::string_view mountPoint,
410 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
411 CreateOptions options,
412 const DataLoaderStatusListener& statusListener,
413 StorageHealthCheckParams&& healthCheckParams,
414 const StorageHealthListener& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800415 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
416 if (!path::isAbsolute(mountPoint)) {
417 LOG(ERROR) << "path is not absolute: " << mountPoint;
418 return kInvalidStorageId;
419 }
420
421 auto mountNorm = path::normalize(mountPoint);
422 {
423 const auto id = findStorageId(mountNorm);
424 if (id != kInvalidStorageId) {
425 if (options & CreateOptions::OpenExisting) {
426 LOG(INFO) << "Opened existing storage " << id;
427 return id;
428 }
429 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
430 return kInvalidStorageId;
431 }
432 }
433
434 if (!(options & CreateOptions::CreateNew)) {
435 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
436 return kInvalidStorageId;
437 }
438
439 if (!path::isEmptyDir(mountNorm)) {
440 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
441 return kInvalidStorageId;
442 }
443 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
444 if (mountRoot.empty()) {
445 LOG(ERROR) << "Bad mount point";
446 return kInvalidStorageId;
447 }
448 // Make sure the code removes all crap it may create while still failing.
449 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
450 auto firstCleanupOnFailure =
451 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
452
453 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800454 const auto backing = path::join(mountRoot, constants().backing);
455 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800456 return kInvalidStorageId;
457 }
458
Songchun Fan3c82a302019-11-29 14:23:45 -0800459 IncFsMount::Control control;
460 {
461 std::lock_guard l(mMountOperationLock);
462 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800463
464 if (auto err = rmDirContent(backing.c_str())) {
465 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
466 return kInvalidStorageId;
467 }
468 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
469 return kInvalidStorageId;
470 }
471 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800472 if (!status.isOk()) {
473 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
474 return kInvalidStorageId;
475 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800476 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
477 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800478 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
479 return kInvalidStorageId;
480 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800481 int cmd = controlParcel.cmd.release().release();
482 int pendingReads = controlParcel.pendingReads.release().release();
483 int logs = controlParcel.log.release().release();
484 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800485 }
486
487 std::unique_lock l(mLock);
488 const auto mountIt = getStorageSlotLocked();
489 const auto mountId = mountIt->first;
490 l.unlock();
491
492 auto ifs =
493 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
494 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
495 // is the removal of the |ifs|.
496 firstCleanupOnFailure.release();
497
498 auto secondCleanup = [this, &l](auto itPtr) {
499 if (!l.owns_lock()) {
500 l.lock();
501 }
502 mMounts.erase(*itPtr);
503 };
504 auto secondCleanupOnFailure =
505 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
506
507 const auto storageIt = ifs->makeStorage(ifs->mountId);
508 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800509 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800510 return kInvalidStorageId;
511 }
512
513 {
514 metadata::Mount m;
515 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700516 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700517 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
518 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
519 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800520 const auto metadata = m.SerializeAsString();
521 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800522 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800523 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800524 if (auto err =
525 mIncFs->makeFile(ifs->control,
526 path::join(ifs->root, constants().mount,
527 constants().infoMdName),
528 0777, idFromMetadata(metadata),
529 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800530 LOG(ERROR) << "Saving mount metadata failed: " << -err;
531 return kInvalidStorageId;
532 }
533 }
534
535 const auto bk =
536 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800537 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
538 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800539 err < 0) {
540 LOG(ERROR) << "adding bind mount failed: " << -err;
541 return kInvalidStorageId;
542 }
543
544 // Done here as well, all data structures are in good state.
545 secondCleanupOnFailure.release();
546
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700547 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
548 std::move(healthCheckParams), &healthListener);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700549 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800550
551 mountIt->second = std::move(ifs);
552 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700553
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700554 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700555 // failed to create data loader
556 LOG(ERROR) << "initializeDataLoader() failed";
557 deleteStorage(dataLoaderStub->id());
558 return kInvalidStorageId;
559 }
560
Songchun Fan3c82a302019-11-29 14:23:45 -0800561 LOG(INFO) << "created storage " << mountId;
562 return mountId;
563}
564
565StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
566 StorageId linkedStorage,
567 IncrementalService::CreateOptions options) {
568 if (!isValidMountTarget(mountPoint)) {
569 LOG(ERROR) << "Mount point is invalid or missing";
570 return kInvalidStorageId;
571 }
572
573 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700574 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800575 if (!ifs) {
576 LOG(ERROR) << "Ifs unavailable";
577 return kInvalidStorageId;
578 }
579
580 const auto mountIt = getStorageSlotLocked();
581 const auto storageId = mountIt->first;
582 const auto storageIt = ifs->makeStorage(storageId);
583 if (storageIt == ifs->storages.end()) {
584 LOG(ERROR) << "Can't create a new storage";
585 mMounts.erase(mountIt);
586 return kInvalidStorageId;
587 }
588
589 l.unlock();
590
591 const auto bk =
592 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800593 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
594 std::string(storageIt->second.name), path::normalize(mountPoint),
595 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800596 err < 0) {
597 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700598 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
599 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800600 return kInvalidStorageId;
601 }
602
603 mountIt->second = ifs;
604 return storageId;
605}
606
607IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
608 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700609 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800610}
611
612StorageId IncrementalService::findStorageId(std::string_view path) const {
613 std::lock_guard l(mLock);
614 auto it = findStorageLocked(path);
615 if (it == mBindsByPath.end()) {
616 return kInvalidStorageId;
617 }
618 return it->second->second.storage;
619}
620
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700621int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
622 const auto ifs = getIfs(storageId);
623 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700624 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700625 return -EINVAL;
626 }
627
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700628 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700629 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700630 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
631 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700632 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700633 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700634 return fromBinderStatus(status);
635 }
636 }
637
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700638 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
639 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
640 return fromBinderStatus(status);
641 }
642
643 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700644 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700645 }
646
647 return 0;
648}
649
650binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700651 os::incremental::IncrementalFileSystemControlParcel control;
652 control.cmd.reset(dup(ifs.control.cmd()));
653 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700654 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700655 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700656 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700657 }
658
659 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700660 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700661}
662
Songchun Fan3c82a302019-11-29 14:23:45 -0800663void IncrementalService::deleteStorage(StorageId storageId) {
664 const auto ifs = getIfs(storageId);
665 if (!ifs) {
666 return;
667 }
668 deleteStorage(*ifs);
669}
670
671void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
672 std::unique_lock l(ifs.lock);
673 deleteStorageLocked(ifs, std::move(l));
674}
675
676void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
677 std::unique_lock<std::mutex>&& ifsLock) {
678 const auto storages = std::move(ifs.storages);
679 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
680 const auto bindPoints = ifs.bindPoints;
681 ifsLock.unlock();
682
683 std::lock_guard l(mLock);
684 for (auto&& [id, _] : storages) {
685 if (id != ifs.mountId) {
686 mMounts.erase(id);
687 }
688 }
689 for (auto&& [path, _] : bindPoints) {
690 mBindsByPath.erase(path);
691 }
692 mMounts.erase(ifs.mountId);
693}
694
695StorageId IncrementalService::openStorage(std::string_view pathInMount) {
696 if (!path::isAbsolute(pathInMount)) {
697 return kInvalidStorageId;
698 }
699
700 return findStorageId(path::normalize(pathInMount));
701}
702
Songchun Fan3c82a302019-11-29 14:23:45 -0800703IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
704 std::lock_guard l(mLock);
705 return getIfsLocked(storage);
706}
707
708const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
709 auto it = mMounts.find(storage);
710 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700711 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700712 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800713 }
714 return it->second;
715}
716
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800717int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
718 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800719 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700720 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800721 return -EINVAL;
722 }
723
724 const auto ifs = getIfs(storage);
725 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700726 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800727 return -EINVAL;
728 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800729
Songchun Fan3c82a302019-11-29 14:23:45 -0800730 std::unique_lock l(ifs->lock);
731 const auto storageInfo = ifs->storages.find(storage);
732 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700733 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800734 return -EINVAL;
735 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700736 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700737 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700738 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700739 return -EINVAL;
740 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800741 l.unlock();
742 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800743 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
744 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800745}
746
747int IncrementalService::unbind(StorageId storage, std::string_view target) {
748 if (!path::isAbsolute(target)) {
749 return -EINVAL;
750 }
751
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700752 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800753
754 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
755 // otherwise there's a chance to unmount something completely unrelated
756 const auto norm = path::normalize(target);
757 std::unique_lock l(mLock);
758 const auto storageIt = mBindsByPath.find(norm);
759 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
760 return -EINVAL;
761 }
762 const auto bindIt = storageIt->second;
763 const auto storageId = bindIt->second.storage;
764 const auto ifs = getIfsLocked(storageId);
765 if (!ifs) {
766 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
767 << " is missing";
768 return -EFAULT;
769 }
770 mBindsByPath.erase(storageIt);
771 l.unlock();
772
773 mVold->unmountIncFs(bindIt->first);
774 std::unique_lock l2(ifs->lock);
775 if (ifs->bindPoints.size() <= 1) {
776 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700777 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800778 } else {
779 const std::string savedFile = std::move(bindIt->second.savedFilename);
780 ifs->bindPoints.erase(bindIt);
781 l2.unlock();
782 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800783 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800784 }
785 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700786
Songchun Fan3c82a302019-11-29 14:23:45 -0800787 return 0;
788}
789
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700790std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700791 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700792 std::string_view path) const {
793 if (!path::isAbsolute(path)) {
794 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700795 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700796 auto normPath = path::normalize(path);
797 if (path::startsWith(normPath, storageIt->second.name)) {
798 return normPath;
799 }
800 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700801 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
802 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700803 return {};
804 }
805 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700806}
807
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700808std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700809 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700810 std::unique_lock l(ifs.lock);
811 const auto storageInfo = ifs.storages.find(storage);
812 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800813 return {};
814 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700815 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800816}
817
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800818int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
819 incfs::NewFileParams params) {
820 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700821 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800822 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700823 LOG(ERROR) << "Internal error: storageId " << storage
824 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800825 return -EINVAL;
826 }
827 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800828 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700829 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800830 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800831 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800832 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800833 }
834 return -EINVAL;
835}
836
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800837int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800838 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700839 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800840 if (normPath.empty()) {
841 return -EINVAL;
842 }
843 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800844 }
845 return -EINVAL;
846}
847
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800848int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800849 const auto ifs = getIfs(storageId);
850 if (!ifs) {
851 return -EINVAL;
852 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700853 return makeDirs(*ifs, storageId, path, mode);
854}
855
856int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
857 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800858 std::string normPath = normalizePathToStorage(ifs, storageId, path);
859 if (normPath.empty()) {
860 return -EINVAL;
861 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700862 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800863}
864
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800865int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
866 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700867 std::unique_lock l(mLock);
868 auto ifsSrc = getIfsLocked(sourceStorageId);
869 if (!ifsSrc) {
870 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800871 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700872 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
873 return -EINVAL;
874 }
875 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700876 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
877 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700878 if (normOldPath.empty() || normNewPath.empty()) {
879 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
880 return -EINVAL;
881 }
882 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800883}
884
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800885int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800886 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700887 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800888 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800889 }
890 return -EINVAL;
891}
892
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800893int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
894 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800895 std::string&& target, BindKind kind,
896 std::unique_lock<std::mutex>& mainLock) {
897 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700898 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800899 return -EINVAL;
900 }
901
902 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700903 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800904 if (kind != BindKind::Temporary) {
905 metadata::BindPoint bp;
906 bp.set_storage_id(storage);
907 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800908 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800909 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800910 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800911 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800912 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700913 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
914 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
915 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800916 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700917 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800918 return int(node);
919 }
920 }
921
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700922 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
923 std::move(target), kind, mainLock);
924 if (res) {
925 mIncFs->unlink(ifs.control, metadataFullPath);
926 }
927 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800928}
929
930int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800931 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800932 std::string&& target, BindKind kind,
933 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800934 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800935 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800936 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800937 if (!status.isOk()) {
938 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
939 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
940 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
941 : status.serviceSpecificErrorCode() == 0
942 ? -EFAULT
943 : status.serviceSpecificErrorCode()
944 : -EIO;
945 }
946 }
947
948 if (!mainLock.owns_lock()) {
949 mainLock.lock();
950 }
951 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700952 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
953 std::move(target), kind);
954 return 0;
955}
956
957void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
958 std::string&& metadataName, std::string&& source,
959 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800960 const auto [it, _] =
961 ifs.bindPoints.insert_or_assign(target,
962 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800963 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800964 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700965}
966
967RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
968 const auto ifs = getIfs(storage);
969 if (!ifs) {
970 return {};
971 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700972 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700973 if (normPath.empty()) {
974 return {};
975 }
976 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800977}
978
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800979RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800980 const auto ifs = getIfs(storage);
981 if (!ifs) {
982 return {};
983 }
984 return mIncFs->getMetadata(ifs->control, node);
985}
986
Songchun Fan3c82a302019-11-29 14:23:45 -0800987bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700988 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700989 {
990 std::unique_lock l(mLock);
991 const auto& ifs = getIfsLocked(storage);
992 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800993 return false;
994 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700995 dataLoaderStub = ifs->dataLoaderStub;
996 if (!dataLoaderStub) {
997 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700998 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800999 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001000 dataLoaderStub->requestStart();
1001 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001002}
1003
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001004std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1005 std::unordered_set<std::string_view> mountedRootNames;
1006 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1007 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1008 for (auto [source, target] : binds) {
1009 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1010 LOG(INFO) << " " << path::join(root, source);
1011 }
1012
1013 // Ensure it's a kind of a mount that's managed by IncrementalService
1014 if (path::basename(root) != constants().mount ||
1015 path::basename(backingDir) != constants().backing) {
1016 return;
1017 }
1018 const auto expectedRoot = path::dirname(root);
1019 if (path::dirname(backingDir) != expectedRoot) {
1020 return;
1021 }
1022 if (path::dirname(expectedRoot) != mIncrementalDir) {
1023 return;
1024 }
1025 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1026 return;
1027 }
1028
1029 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1030
1031 // make sure we clean up the mount if it happens to be a bad one.
1032 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1033 auto cleanupFiles = makeCleanup([&]() {
1034 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1035 IncFsMount::cleanupFilesystem(expectedRoot);
1036 });
1037 auto cleanupMounts = makeCleanup([&]() {
1038 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1039 for (auto&& [_, target] : binds) {
1040 mVold->unmountIncFs(std::string(target));
1041 }
1042 mVold->unmountIncFs(std::string(root));
1043 });
1044
1045 auto control = mIncFs->openMount(root);
1046 if (!control) {
1047 LOG(INFO) << "failed to open mount " << root;
1048 return;
1049 }
1050
1051 auto mountRecord =
1052 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1053 path::join(root, constants().infoMdName));
1054 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1055 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1056 return;
1057 }
1058
1059 auto mountId = mountRecord.storage().id();
1060 mNextId = std::max(mNextId, mountId + 1);
1061
1062 DataLoaderParamsParcel dataLoaderParams;
1063 {
1064 const auto& loader = mountRecord.loader();
1065 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1066 dataLoaderParams.packageName = loader.package_name();
1067 dataLoaderParams.className = loader.class_name();
1068 dataLoaderParams.arguments = loader.arguments();
1069 }
1070
1071 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1072 std::move(control), *this);
1073 cleanupFiles.release(); // ifs will take care of that now
1074
1075 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1076 auto d = openDir(root);
1077 while (auto e = ::readdir(d.get())) {
1078 if (e->d_type == DT_REG) {
1079 auto name = std::string_view(e->d_name);
1080 if (name.starts_with(constants().mountpointMdPrefix)) {
1081 permanentBindPoints
1082 .emplace_back(name,
1083 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1084 ifs->control,
1085 path::join(root,
1086 name)));
1087 if (permanentBindPoints.back().second.dest_path().empty() ||
1088 permanentBindPoints.back().second.source_subdir().empty()) {
1089 permanentBindPoints.pop_back();
1090 mIncFs->unlink(ifs->control, path::join(root, name));
1091 } else {
1092 LOG(INFO) << "Permanent bind record: '"
1093 << permanentBindPoints.back().second.source_subdir() << "'->'"
1094 << permanentBindPoints.back().second.dest_path() << "'";
1095 }
1096 }
1097 } else if (e->d_type == DT_DIR) {
1098 if (e->d_name == "."sv || e->d_name == ".."sv) {
1099 continue;
1100 }
1101 auto name = std::string_view(e->d_name);
1102 if (name.starts_with(constants().storagePrefix)) {
1103 int storageId;
1104 const auto res =
1105 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1106 name.data() + name.size(), storageId);
1107 if (res.ec != std::errc{} || *res.ptr != '_') {
1108 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1109 << "' for mount " << expectedRoot;
1110 continue;
1111 }
1112 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1113 if (!inserted) {
1114 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1115 << " for mount " << expectedRoot;
1116 continue;
1117 }
1118 ifs->storages.insert_or_assign(storageId,
1119 IncFsMount::Storage{path::join(root, name)});
1120 mNextId = std::max(mNextId, storageId + 1);
1121 }
1122 }
1123 }
1124
1125 if (ifs->storages.empty()) {
1126 LOG(WARNING) << "No valid storages in mount " << root;
1127 return;
1128 }
1129
1130 // now match the mounted directories with what we expect to have in the metadata
1131 {
1132 std::unique_lock l(mLock, std::defer_lock);
1133 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1134 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1135 [&, bindRecord = bindRecord](auto&& bind) {
1136 return bind.second == bindRecord.dest_path() &&
1137 path::join(root, bind.first) ==
1138 bindRecord.source_subdir();
1139 });
1140 if (mountedIt != binds.end()) {
1141 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1142 << " to mount " << mountedIt->first;
1143 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1144 std::move(*bindRecord.mutable_source_subdir()),
1145 std::move(*bindRecord.mutable_dest_path()),
1146 BindKind::Permanent);
1147 if (mountedIt != binds.end() - 1) {
1148 std::iter_swap(mountedIt, binds.end() - 1);
1149 }
1150 binds = binds.first(binds.size() - 1);
1151 } else {
1152 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1153 << ", mounting";
1154 // doesn't exist - try mounting back
1155 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1156 std::move(*bindRecord.mutable_source_subdir()),
1157 std::move(*bindRecord.mutable_dest_path()),
1158 BindKind::Permanent, l)) {
1159 mIncFs->unlink(ifs->control, metadataFile);
1160 }
1161 }
1162 }
1163 }
1164
1165 // if anything stays in |binds| those are probably temporary binds; system restarted since
1166 // they were mounted - so let's unmount them all.
1167 for (auto&& [source, target] : binds) {
1168 if (source.empty()) {
1169 continue;
1170 }
1171 mVold->unmountIncFs(std::string(target));
1172 }
1173 cleanupMounts.release(); // ifs now manages everything
1174
1175 if (ifs->bindPoints.empty()) {
1176 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1177 deleteStorage(*ifs);
1178 return;
1179 }
1180
1181 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1182 CHECK(ifs->dataLoaderStub);
1183
1184 mountedRootNames.insert(path::basename(ifs->root));
1185
1186 // not locking here at all: we're still in the constructor, no other calls can happen
1187 mMounts[ifs->mountId] = std::move(ifs);
1188 });
1189
1190 return mountedRootNames;
1191}
1192
1193void IncrementalService::mountExistingImages(
1194 const std::unordered_set<std::string_view>& mountedRootNames) {
1195 auto dir = openDir(mIncrementalDir);
1196 if (!dir) {
1197 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1198 return;
1199 }
1200 while (auto entry = ::readdir(dir.get())) {
1201 if (entry->d_type != DT_DIR) {
1202 continue;
1203 }
1204 std::string_view name = entry->d_name;
1205 if (!name.starts_with(constants().mountKeyPrefix)) {
1206 continue;
1207 }
1208 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001209 continue;
1210 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001211 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001212 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001213 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001214 }
1215 }
1216}
1217
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001218bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001219 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001220 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001221
Songchun Fan3c82a302019-11-29 14:23:45 -08001222 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001223 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001224 if (!status.isOk()) {
1225 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1226 return false;
1227 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001228
1229 int cmd = controlParcel.cmd.release().release();
1230 int pendingReads = controlParcel.pendingReads.release().release();
1231 int logs = controlParcel.log.release().release();
1232 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001233
1234 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1235
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001236 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1237 path::join(mountTarget, constants().infoMdName));
1238 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001239 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1240 return false;
1241 }
1242
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001243 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001244 mNextId = std::max(mNextId, ifs->mountId + 1);
1245
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001246 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001247 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001248 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001249 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001250 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001251 dataLoaderParams.packageName = loader.package_name();
1252 dataLoaderParams.className = loader.class_name();
1253 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001254 }
1255
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001256 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001257 CHECK(ifs->dataLoaderStub);
1258
Songchun Fan3c82a302019-11-29 14:23:45 -08001259 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001260 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001261 while (auto e = ::readdir(d.get())) {
1262 if (e->d_type == DT_REG) {
1263 auto name = std::string_view(e->d_name);
1264 if (name.starts_with(constants().mountpointMdPrefix)) {
1265 bindPoints.emplace_back(name,
1266 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1267 ifs->control,
1268 path::join(mountTarget,
1269 name)));
1270 if (bindPoints.back().second.dest_path().empty() ||
1271 bindPoints.back().second.source_subdir().empty()) {
1272 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001273 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001274 }
1275 }
1276 } else if (e->d_type == DT_DIR) {
1277 if (e->d_name == "."sv || e->d_name == ".."sv) {
1278 continue;
1279 }
1280 auto name = std::string_view(e->d_name);
1281 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001282 int storageId;
1283 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1284 name.data() + name.size(), storageId);
1285 if (res.ec != std::errc{} || *res.ptr != '_') {
1286 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1287 << root;
1288 continue;
1289 }
1290 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001291 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001292 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001293 << " for mount " << root;
1294 continue;
1295 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001296 ifs->storages.insert_or_assign(storageId,
1297 IncFsMount::Storage{
1298 path::join(root, constants().mount, name)});
1299 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001300 }
1301 }
1302 }
1303
1304 if (ifs->storages.empty()) {
1305 LOG(WARNING) << "No valid storages in mount " << root;
1306 return false;
1307 }
1308
1309 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001310 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001311 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001312 for (auto&& bp : bindPoints) {
1313 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1314 std::move(*bp.second.mutable_source_subdir()),
1315 std::move(*bp.second.mutable_dest_path()),
1316 BindKind::Permanent, l);
1317 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001318 }
1319
1320 if (bindCount == 0) {
1321 LOG(WARNING) << "No valid bind points for mount " << root;
1322 deleteStorage(*ifs);
1323 return false;
1324 }
1325
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001326 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001327 mMounts[ifs->mountId] = std::move(ifs);
1328 return true;
1329}
1330
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001331void IncrementalService::runCmdLooper() {
1332 constexpr auto kTimeoutMsecs = 1000;
1333 while (mRunning.load(std::memory_order_relaxed)) {
1334 mLooper->pollAll(kTimeoutMsecs);
1335 }
1336}
1337
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001338IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001339 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001340 const DataLoaderStatusListener* statusListener,
1341 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001342 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001343 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1344 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001345 return ifs.dataLoaderStub;
1346}
1347
1348void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001349 const DataLoaderStatusListener* statusListener,
1350 StorageHealthCheckParams&& healthCheckParams,
1351 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001352 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001353 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001354 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001355 }
1356
Songchun Fan3c82a302019-11-29 14:23:45 -08001357 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001358 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001359 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1360 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1361 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001362 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001363
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001364 ifs.dataLoaderStub =
1365 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001366 statusListener, std::move(healthCheckParams), healthListener,
1367 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001368}
1369
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001370template <class Duration>
1371static long elapsedMcs(Duration start, Duration end) {
1372 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1373}
1374
1375// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001376bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1377 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001378 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001379 auto start = Clock::now();
1380
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001381 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001382 if (!ifs) {
1383 LOG(ERROR) << "Invalid storage " << storage;
1384 return false;
1385 }
1386
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001387 // First prepare target directories if they don't exist yet
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001388 if (auto res = makeDirs(*ifs, storage, libDirRelativePath, 0755)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001389 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1390 << " errno: " << res;
1391 return false;
1392 }
1393
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001394 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001395 ZipArchiveHandle zipFileHandle;
1396 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001397 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1398 return false;
1399 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001400
1401 // Need a shared pointer: will be passing it into all unpacking jobs.
1402 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001403 void* cookie = nullptr;
1404 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001405 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001406 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1407 return false;
1408 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001409 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001410 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1411
1412 auto openZipTs = Clock::now();
1413
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001414 std::vector<Job> jobQueue;
1415 ZipEntry entry;
1416 std::string_view fileName;
1417 while (!Next(cookie, &entry, &fileName)) {
1418 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001419 continue;
1420 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001421
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001422 if (!extractNativeLibs) {
1423 // ensure the file is properly aligned and unpacked
1424 if (entry.method != kCompressStored) {
1425 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1426 return false;
1427 }
1428 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1429 LOG(WARNING) << "Library " << fileName
1430 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1431 << entry.offset;
1432 return false;
1433 }
1434 continue;
1435 }
1436
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001437 auto startFileTs = Clock::now();
1438
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001439 const auto libName = path::basename(fileName);
Yurii Zubrytskyi510037b2020-04-22 15:46:21 -07001440 auto targetLibPath = path::join(libDirRelativePath, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001441 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001442 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001443 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001444 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001445 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1446 << "; skipping extraction, spent "
1447 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1448 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001449 continue;
1450 }
1451
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001452 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001453 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001454 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001455 .signature = {},
1456 // Metadata of the new lib file is its relative path
1457 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1458 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001459 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001460 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1461 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001462 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001463 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001464 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001465 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001466
1467 auto makeFileTs = Clock::now();
1468
Songchun Fanafaf6e92020-03-18 14:12:20 -07001469 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001470 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001471 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001472 LOG(INFO) << "incfs: Extracted " << libName
1473 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001474 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001475 continue;
1476 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001477
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001478 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1479 libFileId, libPath = std::move(targetLibPath),
1480 makeFileTs]() mutable {
1481 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001482 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001483
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001484 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001485 auto prepareJobTs = Clock::now();
1486 LOG(INFO) << "incfs: Processed " << libName << ": "
1487 << elapsedMcs(startFileTs, prepareJobTs)
1488 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1489 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001490 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001491 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001492
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001493 auto processedTs = Clock::now();
1494
1495 if (!jobQueue.empty()) {
1496 {
1497 std::lock_guard lock(mJobMutex);
1498 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001499 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001500 if (existingJobs.empty()) {
1501 existingJobs = std::move(jobQueue);
1502 } else {
1503 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1504 std::move_iterator(jobQueue.end()));
1505 }
1506 }
1507 }
1508 mJobCondition.notify_all();
1509 }
1510
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001511 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001512 auto end = Clock::now();
1513 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1514 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1515 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001516 << " make files: " << elapsedMcs(openZipTs, processedTs)
1517 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001518 }
1519
1520 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001521}
1522
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001523void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1524 ZipEntry& entry, const incfs::FileId& libFileId,
1525 std::string_view targetLibPath,
1526 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001527 if (!ifs) {
1528 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1529 return;
1530 }
1531
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001532 auto libName = path::basename(targetLibPath);
1533 auto startedTs = Clock::now();
1534
1535 // Write extracted data to new file
1536 // NOTE: don't zero-initialize memory, it may take a while for nothing
1537 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1538 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1539 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1540 return;
1541 }
1542
1543 auto extractFileTs = Clock::now();
1544
1545 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1546 if (!writeFd.ok()) {
1547 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1548 return;
1549 }
1550
1551 auto openFileTs = Clock::now();
1552 const int numBlocks =
1553 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1554 std::vector<IncFsDataBlock> instructions(numBlocks);
1555 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1556 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001557 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001558 instructions[i] = IncFsDataBlock{
1559 .fileFd = writeFd.get(),
1560 .pageIndex = static_cast<IncFsBlockIndex>(i),
1561 .compression = INCFS_COMPRESSION_KIND_NONE,
1562 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001563 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001564 .data = reinterpret_cast<const char*>(remainingData.data()),
1565 };
1566 remainingData = remainingData.subspan(blockSize);
1567 }
1568 auto prepareInstsTs = Clock::now();
1569
1570 size_t res = mIncFs->writeBlocks(instructions);
1571 if (res != instructions.size()) {
1572 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1573 return;
1574 }
1575
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001576 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001577 auto endFileTs = Clock::now();
1578 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1579 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1580 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1581 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1582 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1583 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1584 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1585 }
1586}
1587
1588bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001589 struct WaitPrinter {
1590 const Clock::time_point startTs = Clock::now();
1591 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001592 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001593 const auto endTs = Clock::now();
1594 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1595 << elapsedMcs(startTs, endTs) << "mcs";
1596 }
1597 }
1598 } waitPrinter;
1599
1600 MountId mount;
1601 {
1602 auto ifs = getIfs(storage);
1603 if (!ifs) {
1604 return true;
1605 }
1606 mount = ifs->mountId;
1607 }
1608
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001609 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001610 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001611 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001612 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001613 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001614 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001615}
1616
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001617bool IncrementalService::perfLoggingEnabled() {
1618 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1619 return enabled;
1620}
1621
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001622void IncrementalService::runJobProcessing() {
1623 for (;;) {
1624 std::unique_lock lock(mJobMutex);
1625 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1626 if (!mRunning) {
1627 return;
1628 }
1629
1630 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001631 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001632 auto queue = std::move(it->second);
1633 mJobQueue.erase(it);
1634 lock.unlock();
1635
1636 for (auto&& job : queue) {
1637 job();
1638 }
1639
1640 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001641 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001642 lock.unlock();
1643 mJobCondition.notify_all();
1644 }
1645}
1646
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001647void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001648 sp<IAppOpsCallback> listener;
1649 {
1650 std::unique_lock lock{mCallbacksLock};
1651 auto& cb = mCallbackRegistered[packageName];
1652 if (cb) {
1653 return;
1654 }
1655 cb = new AppOpsListener(*this, packageName);
1656 listener = cb;
1657 }
1658
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001659 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1660 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001661}
1662
1663bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1664 sp<IAppOpsCallback> listener;
1665 {
1666 std::unique_lock lock{mCallbacksLock};
1667 auto found = mCallbackRegistered.find(packageName);
1668 if (found == mCallbackRegistered.end()) {
1669 return false;
1670 }
1671 listener = found->second;
1672 mCallbackRegistered.erase(found);
1673 }
1674
1675 mAppOpsManager->stopWatchingMode(listener);
1676 return true;
1677}
1678
1679void IncrementalService::onAppOpChanged(const std::string& packageName) {
1680 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001681 return;
1682 }
1683
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001684 std::vector<IfsMountPtr> affected;
1685 {
1686 std::lock_guard l(mLock);
1687 affected.reserve(mMounts.size());
1688 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001689 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001690 affected.push_back(ifs);
1691 }
1692 }
1693 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001694 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001695 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001696 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001697}
1698
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07001699void IncrementalService::addTimedJob(MountId id, Milliseconds after, Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001700 if (id == kInvalidStorageId) {
1701 return;
1702 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07001703 mTimedQueue->addJob(id, after, std::move(what));
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001704}
1705
1706void IncrementalService::removeTimedJobs(MountId id) {
1707 if (id == kInvalidStorageId) {
1708 return;
1709 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07001710 mTimedQueue->removeJobs(id);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001711}
1712
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001713IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1714 DataLoaderParamsParcel&& params,
1715 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001716 const DataLoaderStatusListener* statusListener,
1717 StorageHealthCheckParams&& healthCheckParams,
1718 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001719 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001720 : mService(service),
1721 mId(id),
1722 mParams(std::move(params)),
1723 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001724 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
1725 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001726 mHealthPath(std::move(healthPath)),
1727 mHealthCheckParams(std::move(healthCheckParams)) {
1728 if (mHealthListener) {
1729 if (!isHealthParamsValid()) {
1730 mHealthListener = {};
1731 }
1732 } else {
1733 // Disable advanced health check statuses.
1734 mHealthCheckParams.blockedTimeoutMs = -1;
1735 }
1736 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001737}
1738
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001739IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001740 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001741 cleanupResources();
1742 }
1743}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001744
1745void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001746 auto now = Clock::now();
1747 {
1748 std::unique_lock lock(mMutex);
1749 mHealthPath.clear();
1750 unregisterFromPendingReads();
1751 resetHealthControl();
1752 mService.removeTimedJobs(mId);
1753 }
1754
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001755 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001756
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001757 {
1758 std::unique_lock lock(mMutex);
1759 mParams = {};
1760 mControl = {};
1761 mHealthControl = {};
1762 mHealthListener = {};
1763 mStatusCondition.wait_until(lock, now + 60s, [this] {
1764 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1765 });
1766 mStatusListener = {};
1767 mId = kInvalidStorageId;
1768 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001769}
1770
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001771sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1772 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001773 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001774 if (!status.isOk()) {
1775 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1776 return {};
1777 }
1778 if (!dataloader) {
1779 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1780 return {};
1781 }
1782 return dataloader;
1783}
1784
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001785bool IncrementalService::DataLoaderStub::requestCreate() {
1786 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1787}
1788
1789bool IncrementalService::DataLoaderStub::requestStart() {
1790 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1791}
1792
1793bool IncrementalService::DataLoaderStub::requestDestroy() {
1794 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1795}
1796
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001797bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001798 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001799 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001800 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001801 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001802 return fsmStep();
1803}
1804
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001805void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001806 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001807 mTargetStatus = status;
1808 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001809 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001810 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001811}
1812
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001813bool IncrementalService::DataLoaderStub::bind() {
1814 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001815 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001816 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001817 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001818 return false;
1819 }
1820 return true;
1821}
1822
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001823bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001824 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001825 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001826 return false;
1827 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001828 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001829 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001830 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001831 return false;
1832 }
1833 return true;
1834}
1835
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001836bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001837 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001838 if (!dataloader) {
1839 return false;
1840 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001841 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001842 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001843 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001844 return false;
1845 }
1846 return true;
1847}
1848
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001849bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001850 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001851}
1852
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001853bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001854 if (!isValid()) {
1855 return false;
1856 }
1857
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001858 int currentStatus;
1859 int targetStatus;
1860 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001861 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001862 currentStatus = mCurrentStatus;
1863 targetStatus = mTargetStatus;
1864 }
1865
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001866 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001867
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001868 if (currentStatus == targetStatus) {
1869 return true;
1870 }
1871
1872 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001873 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
1874 // Do nothing, this is a reset state.
1875 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001876 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1877 return destroy();
1878 }
1879 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1880 switch (currentStatus) {
1881 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1882 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1883 return start();
1884 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001885 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001886 }
1887 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1888 switch (currentStatus) {
1889 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001890 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001891 return bind();
1892 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001893 return create();
1894 }
1895 break;
1896 default:
1897 LOG(ERROR) << "Invalid target status: " << targetStatus
1898 << ", current status: " << currentStatus;
1899 break;
1900 }
1901 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001902}
1903
1904binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001905 if (!isValid()) {
1906 return binder::Status::
1907 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
1908 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001909 if (id() != mountId) {
1910 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001911 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
1912 }
1913
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001914 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001915 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001916 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001917 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001918 if (mCurrentStatus == newStatus) {
1919 return binder::Status::ok();
1920 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001921
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001922 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001923 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001924 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001925
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001926 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001927
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001928 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001929 // For unavailable, unbind from DataLoader to ensure proper re-commit.
1930 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001931 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001932 }
1933
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001934 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001935 << newStatus << " (target " << targetStatus << ")";
1936
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001937 if (listener) {
1938 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001939 }
1940
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001941 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08001942
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07001943 mStatusCondition.notify_all();
1944
Songchun Fan3c82a302019-11-29 14:23:45 -08001945 return binder::Status::ok();
1946}
1947
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001948bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
1949 return mHealthCheckParams.blockedTimeoutMs > 0 &&
1950 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001951}
1952
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001953void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
1954 int healthStatus) {
1955 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
1956 if (healthListener) {
1957 healthListener->onHealthStatus(id(), healthStatus);
1958 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001959}
1960
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001961void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
1962 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001963
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001964 int healthStatusToReport = -1;
1965 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001966
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001967 {
1968 std::unique_lock lock(mMutex);
1969 unregisterFromPendingReads();
1970
1971 healthListener = mHealthListener;
1972
1973 // Healthcheck depends on timestamp of the oldest pending read.
1974 // To get it, we need to re-open a pendingReads FD to get a full list of reads.
1975 // Additionally we need to re-register for epoll with fresh FDs in case there are no reads.
1976 const auto now = Clock::now();
1977 const auto kernelTsUs = getOldestPendingReadTs();
1978 if (baseline) {
1979 // Updating baseline only on looper/epoll callback, i.e. on new set of pending reads.
1980 mHealthBase = {now, kernelTsUs};
1981 }
1982
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07001983 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
1984 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001985 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
1986 registerForPendingReads();
1987 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
1988 lock.unlock();
1989 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001990 return;
1991 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001992
1993 resetHealthControl();
1994
1995 // Always make sure the data loader is started.
1996 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1997
1998 // Skip any further processing if health check params are invalid.
1999 if (!isHealthParamsValid()) {
2000 LOG(DEBUG) << id()
2001 << ": Skip any further processing if health check params are invalid.";
2002 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2003 lock.unlock();
2004 onHealthStatus(healthListener, healthStatusToReport);
2005 // Triggering data loader start. This is a one-time action.
2006 fsmStep();
2007 return;
2008 }
2009
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002010 // Don't schedule timer job less than 500ms in advance.
2011 static constexpr auto kTolerance = 500ms;
2012
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002013 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2014 const auto unhealthyTimeout =
2015 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2016 const auto unhealthyMonitoring =
2017 std::max(1000ms,
2018 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2019
2020 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2021 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002022 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002023
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002024 Milliseconds checkBackAfter;
2025 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002026 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002027 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002028 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002029 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002030 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002031 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002032 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2033 } else {
2034 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002035 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002036 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2037 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002038 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002039 << "secs";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002040 mService.addTimedJob(id(), checkBackAfter, [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002041 }
2042
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002043 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002044 if (healthStatusToReport != -1) {
2045 onHealthStatus(healthListener, healthStatusToReport);
2046 }
2047
2048 fsmStep();
2049}
2050
2051const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2052 if (mHealthPath.empty()) {
2053 resetHealthControl();
2054 return mHealthControl;
2055 }
2056 if (mHealthControl.pendingReads() < 0) {
2057 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2058 }
2059 if (mHealthControl.pendingReads() < 0) {
2060 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2061 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2062 << mHealthControl.logs() << ")";
2063 }
2064 return mHealthControl;
2065}
2066
2067void IncrementalService::DataLoaderStub::resetHealthControl() {
2068 mHealthControl = {};
2069}
2070
2071BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2072 auto result = kMaxBootClockTsUs;
2073
2074 const auto& control = initializeHealthControl();
2075 if (control.pendingReads() < 0) {
2076 return result;
2077 }
2078
2079 std::vector<incfs::ReadInfo> pendingReads;
2080 if (mService.mIncFs->waitForPendingReads(control, 0ms, &pendingReads) !=
2081 android::incfs::WaitResult::HaveData ||
2082 pendingReads.empty()) {
2083 return result;
2084 }
2085
2086 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
2087 << pendingReads.size() << ": " << pendingReads.front().bootClockTsUs;
2088
2089 for (auto&& pendingRead : pendingReads) {
2090 result = std::min(result, pendingRead.bootClockTsUs);
2091 }
2092 return result;
2093}
2094
2095void IncrementalService::DataLoaderStub::registerForPendingReads() {
2096 const auto pendingReadsFd = mHealthControl.pendingReads();
2097 if (pendingReadsFd < 0) {
2098 return;
2099 }
2100
2101 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2102
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002103 mService.mLooper->addFd(
2104 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2105 [](int, int, void* data) -> int {
2106 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002107 self->updateHealthStatus(/*baseline=*/true);
2108 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002109 },
2110 this);
2111 mService.mLooper->wake();
2112}
2113
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002114void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002115 const auto pendingReadsFd = mHealthControl.pendingReads();
2116 if (pendingReadsFd < 0) {
2117 return;
2118 }
2119
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002120 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2121
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002122 mService.mLooper->removeFd(pendingReadsFd);
2123 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002124}
2125
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002126void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002127 dprintf(fd, " dataLoader: {\n");
2128 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2129 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2130 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002131 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002132 dprintf(fd, " health: {\n");
2133 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2134 dprintf(fd, " base: %lldmcs (%lld)\n",
2135 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2136 (long long)mHealthBase.kernelTsUs);
2137 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2138 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2139 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2140 int(mHealthCheckParams.unhealthyMonitoringMs));
2141 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002142 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002143 dprintf(fd, " dataLoaderParams: {\n");
2144 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2145 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2146 dprintf(fd, " className: %s\n", params.className.c_str());
2147 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2148 dprintf(fd, " }\n");
2149 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002150}
2151
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002152void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2153 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002154}
2155
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002156binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2157 bool enableReadLogs, int32_t* _aidl_return) {
2158 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2159 return binder::Status::ok();
2160}
2161
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002162FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2163 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2164}
2165
Songchun Fan3c82a302019-11-29 14:23:45 -08002166} // namespace android::incremental