blob: bf859b9b914d9d1d54ef4c0cafd92b1b40ba18dc [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()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800271 mIncrementalDir(rootDir) {
272 if (!mVold) {
273 LOG(FATAL) << "Vold service is unavailable";
274 }
Songchun Fan68645c42020-02-27 15:57:35 -0800275 if (!mDataLoaderManager) {
276 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800277 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700278 if (!mAppOpsManager) {
279 LOG(FATAL) << "AppOpsManager is unavailable";
280 }
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700281 if (!mJni) {
282 LOG(FATAL) << "JNI is unavailable";
283 }
284 if (!mLooper) {
285 LOG(FATAL) << "Looper is unavailable";
286 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700287
288 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700289 mJobProcessor = std::thread([this]() {
290 mJni->initializeForCurrentThread();
291 runJobProcessing();
292 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700293 mCmdLooperThread = std::thread([this]() {
294 mJni->initializeForCurrentThread();
295 runCmdLooper();
296 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700297
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700298 const auto mountedRootNames = adoptMountedInstances();
299 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800300}
301
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700302IncrementalService::~IncrementalService() {
303 {
304 std::lock_guard lock(mJobMutex);
305 mRunning = false;
306 }
307 mJobCondition.notify_all();
308 mJobProcessor.join();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700309 mCmdLooperThread.join();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700310}
Songchun Fan3c82a302019-11-29 14:23:45 -0800311
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700312static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800313 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800314 case IncrementalService::BindKind::Temporary:
315 return "Temporary";
316 case IncrementalService::BindKind::Permanent:
317 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800318 }
319}
320
321void IncrementalService::onDump(int fd) {
322 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
323 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
324
325 std::unique_lock l(mLock);
326
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700327 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800328 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700329 const IncFsMount& mnt = *ifs;
330 dprintf(fd, " [%d]: {\n", id);
331 if (id != mnt.mountId) {
332 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
333 } else {
334 dprintf(fd, " mountId: %d\n", mnt.mountId);
335 dprintf(fd, " root: %s\n", mnt.root.c_str());
336 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
337 if (mnt.dataLoaderStub) {
338 mnt.dataLoaderStub->onDump(fd);
339 } else {
340 dprintf(fd, " dataLoader: null\n");
341 }
342 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
343 for (auto&& [storageId, storage] : mnt.storages) {
344 dprintf(fd, " [%d] -> [%s]\n", storageId, storage.name.c_str());
345 }
346 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800347
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700348 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
349 for (auto&& [target, bind] : mnt.bindPoints) {
350 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
351 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
352 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
353 dprintf(fd, " kind: %s\n", toString(bind.kind));
354 }
355 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800356 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700357 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800358 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700359 dprintf(fd, "}\n");
360 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800361 for (auto&& [target, mountPairIt] : mBindsByPath) {
362 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700363 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
364 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
365 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
366 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800367 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700368 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800369}
370
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700371void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800372 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700373 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800374 }
375
376 std::vector<IfsMountPtr> mounts;
377 {
378 std::lock_guard l(mLock);
379 mounts.reserve(mMounts.size());
380 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -0700381 if (ifs->mountId == id &&
382 ifs->dataLoaderStub->params().packageName == Constants::systemPackage) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800383 mounts.push_back(ifs);
384 }
385 }
386 }
387
Alex Buynytskyy69941662020-04-11 21:40:37 -0700388 if (mounts.empty()) {
389 return;
390 }
391
Songchun Fan3c82a302019-11-29 14:23:45 -0800392 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700393 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800394 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700395 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800396 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800397 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800398}
399
400auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
401 for (;;) {
402 if (mNextId == kMaxStorageId) {
403 mNextId = 0;
404 }
405 auto id = ++mNextId;
406 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
407 if (inserted) {
408 return it;
409 }
410 }
411}
412
Songchun Fan1124fd32020-02-10 12:49:41 -0800413StorageId IncrementalService::createStorage(
414 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
415 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800416 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
417 if (!path::isAbsolute(mountPoint)) {
418 LOG(ERROR) << "path is not absolute: " << mountPoint;
419 return kInvalidStorageId;
420 }
421
422 auto mountNorm = path::normalize(mountPoint);
423 {
424 const auto id = findStorageId(mountNorm);
425 if (id != kInvalidStorageId) {
426 if (options & CreateOptions::OpenExisting) {
427 LOG(INFO) << "Opened existing storage " << id;
428 return id;
429 }
430 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
431 return kInvalidStorageId;
432 }
433 }
434
435 if (!(options & CreateOptions::CreateNew)) {
436 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
437 return kInvalidStorageId;
438 }
439
440 if (!path::isEmptyDir(mountNorm)) {
441 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
442 return kInvalidStorageId;
443 }
444 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
445 if (mountRoot.empty()) {
446 LOG(ERROR) << "Bad mount point";
447 return kInvalidStorageId;
448 }
449 // Make sure the code removes all crap it may create while still failing.
450 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
451 auto firstCleanupOnFailure =
452 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
453
454 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800455 const auto backing = path::join(mountRoot, constants().backing);
456 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800457 return kInvalidStorageId;
458 }
459
Songchun Fan3c82a302019-11-29 14:23:45 -0800460 IncFsMount::Control control;
461 {
462 std::lock_guard l(mMountOperationLock);
463 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800464
465 if (auto err = rmDirContent(backing.c_str())) {
466 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
467 return kInvalidStorageId;
468 }
469 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
470 return kInvalidStorageId;
471 }
472 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800473 if (!status.isOk()) {
474 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
475 return kInvalidStorageId;
476 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800477 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
478 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800479 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
480 return kInvalidStorageId;
481 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800482 int cmd = controlParcel.cmd.release().release();
483 int pendingReads = controlParcel.pendingReads.release().release();
484 int logs = controlParcel.log.release().release();
485 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800486 }
487
488 std::unique_lock l(mLock);
489 const auto mountIt = getStorageSlotLocked();
490 const auto mountId = mountIt->first;
491 l.unlock();
492
493 auto ifs =
494 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
495 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
496 // is the removal of the |ifs|.
497 firstCleanupOnFailure.release();
498
499 auto secondCleanup = [this, &l](auto itPtr) {
500 if (!l.owns_lock()) {
501 l.lock();
502 }
503 mMounts.erase(*itPtr);
504 };
505 auto secondCleanupOnFailure =
506 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
507
508 const auto storageIt = ifs->makeStorage(ifs->mountId);
509 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800510 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800511 return kInvalidStorageId;
512 }
513
514 {
515 metadata::Mount m;
516 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700517 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700518 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
519 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
520 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800521 const auto metadata = m.SerializeAsString();
522 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800523 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800524 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800525 if (auto err =
526 mIncFs->makeFile(ifs->control,
527 path::join(ifs->root, constants().mount,
528 constants().infoMdName),
529 0777, idFromMetadata(metadata),
530 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800531 LOG(ERROR) << "Saving mount metadata failed: " << -err;
532 return kInvalidStorageId;
533 }
534 }
535
536 const auto bk =
537 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800538 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
539 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800540 err < 0) {
541 LOG(ERROR) << "adding bind mount failed: " << -err;
542 return kInvalidStorageId;
543 }
544
545 // Done here as well, all data structures are in good state.
546 secondCleanupOnFailure.release();
547
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700548 auto dataLoaderStub =
549 prepareDataLoader(*ifs, std::move(dataLoaderParams), &dataLoaderStatusListener);
550 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800551
552 mountIt->second = std::move(ifs);
553 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700554
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700555 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700556 // failed to create data loader
557 LOG(ERROR) << "initializeDataLoader() failed";
558 deleteStorage(dataLoaderStub->id());
559 return kInvalidStorageId;
560 }
561
Songchun Fan3c82a302019-11-29 14:23:45 -0800562 LOG(INFO) << "created storage " << mountId;
563 return mountId;
564}
565
566StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
567 StorageId linkedStorage,
568 IncrementalService::CreateOptions options) {
569 if (!isValidMountTarget(mountPoint)) {
570 LOG(ERROR) << "Mount point is invalid or missing";
571 return kInvalidStorageId;
572 }
573
574 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700575 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800576 if (!ifs) {
577 LOG(ERROR) << "Ifs unavailable";
578 return kInvalidStorageId;
579 }
580
581 const auto mountIt = getStorageSlotLocked();
582 const auto storageId = mountIt->first;
583 const auto storageIt = ifs->makeStorage(storageId);
584 if (storageIt == ifs->storages.end()) {
585 LOG(ERROR) << "Can't create a new storage";
586 mMounts.erase(mountIt);
587 return kInvalidStorageId;
588 }
589
590 l.unlock();
591
592 const auto bk =
593 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800594 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
595 std::string(storageIt->second.name), path::normalize(mountPoint),
596 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800597 err < 0) {
598 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700599 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
600 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800601 return kInvalidStorageId;
602 }
603
604 mountIt->second = ifs;
605 return storageId;
606}
607
608IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
609 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700610 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800611}
612
613StorageId IncrementalService::findStorageId(std::string_view path) const {
614 std::lock_guard l(mLock);
615 auto it = findStorageLocked(path);
616 if (it == mBindsByPath.end()) {
617 return kInvalidStorageId;
618 }
619 return it->second->second.storage;
620}
621
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700622int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
623 const auto ifs = getIfs(storageId);
624 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700625 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700626 return -EINVAL;
627 }
628
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700629 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700630 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700631 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
632 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700633 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700634 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700635 return fromBinderStatus(status);
636 }
637 }
638
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700639 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
640 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
641 return fromBinderStatus(status);
642 }
643
644 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700645 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700646 }
647
648 return 0;
649}
650
651binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700652 os::incremental::IncrementalFileSystemControlParcel control;
653 control.cmd.reset(dup(ifs.control.cmd()));
654 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700655 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700656 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700657 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700658 }
659
660 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700661 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700662}
663
Songchun Fan3c82a302019-11-29 14:23:45 -0800664void IncrementalService::deleteStorage(StorageId storageId) {
665 const auto ifs = getIfs(storageId);
666 if (!ifs) {
667 return;
668 }
669 deleteStorage(*ifs);
670}
671
672void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
673 std::unique_lock l(ifs.lock);
674 deleteStorageLocked(ifs, std::move(l));
675}
676
677void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
678 std::unique_lock<std::mutex>&& ifsLock) {
679 const auto storages = std::move(ifs.storages);
680 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
681 const auto bindPoints = ifs.bindPoints;
682 ifsLock.unlock();
683
684 std::lock_guard l(mLock);
685 for (auto&& [id, _] : storages) {
686 if (id != ifs.mountId) {
687 mMounts.erase(id);
688 }
689 }
690 for (auto&& [path, _] : bindPoints) {
691 mBindsByPath.erase(path);
692 }
693 mMounts.erase(ifs.mountId);
694}
695
696StorageId IncrementalService::openStorage(std::string_view pathInMount) {
697 if (!path::isAbsolute(pathInMount)) {
698 return kInvalidStorageId;
699 }
700
701 return findStorageId(path::normalize(pathInMount));
702}
703
Songchun Fan3c82a302019-11-29 14:23:45 -0800704IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
705 std::lock_guard l(mLock);
706 return getIfsLocked(storage);
707}
708
709const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
710 auto it = mMounts.find(storage);
711 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700712 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700713 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800714 }
715 return it->second;
716}
717
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800718int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
719 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800720 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700721 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800722 return -EINVAL;
723 }
724
725 const auto ifs = getIfs(storage);
726 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700727 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800728 return -EINVAL;
729 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800730
Songchun Fan3c82a302019-11-29 14:23:45 -0800731 std::unique_lock l(ifs->lock);
732 const auto storageInfo = ifs->storages.find(storage);
733 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700734 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800735 return -EINVAL;
736 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700737 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700738 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700739 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700740 return -EINVAL;
741 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800742 l.unlock();
743 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800744 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
745 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800746}
747
748int IncrementalService::unbind(StorageId storage, std::string_view target) {
749 if (!path::isAbsolute(target)) {
750 return -EINVAL;
751 }
752
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700753 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800754
755 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
756 // otherwise there's a chance to unmount something completely unrelated
757 const auto norm = path::normalize(target);
758 std::unique_lock l(mLock);
759 const auto storageIt = mBindsByPath.find(norm);
760 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
761 return -EINVAL;
762 }
763 const auto bindIt = storageIt->second;
764 const auto storageId = bindIt->second.storage;
765 const auto ifs = getIfsLocked(storageId);
766 if (!ifs) {
767 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
768 << " is missing";
769 return -EFAULT;
770 }
771 mBindsByPath.erase(storageIt);
772 l.unlock();
773
774 mVold->unmountIncFs(bindIt->first);
775 std::unique_lock l2(ifs->lock);
776 if (ifs->bindPoints.size() <= 1) {
777 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700778 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800779 } else {
780 const std::string savedFile = std::move(bindIt->second.savedFilename);
781 ifs->bindPoints.erase(bindIt);
782 l2.unlock();
783 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800784 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800785 }
786 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700787
Songchun Fan3c82a302019-11-29 14:23:45 -0800788 return 0;
789}
790
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700791std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700792 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700793 std::string_view path) const {
794 if (!path::isAbsolute(path)) {
795 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700796 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700797 auto normPath = path::normalize(path);
798 if (path::startsWith(normPath, storageIt->second.name)) {
799 return normPath;
800 }
801 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700802 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
803 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700804 return {};
805 }
806 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700807}
808
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700809std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700810 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700811 std::unique_lock l(ifs.lock);
812 const auto storageInfo = ifs.storages.find(storage);
813 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800814 return {};
815 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700816 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800817}
818
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800819int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
820 incfs::NewFileParams params) {
821 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700822 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800823 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700824 LOG(ERROR) << "Internal error: storageId " << storage
825 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800826 return -EINVAL;
827 }
828 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800829 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700830 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800831 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800832 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800833 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800834 }
835 return -EINVAL;
836}
837
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800838int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800839 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700840 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800841 if (normPath.empty()) {
842 return -EINVAL;
843 }
844 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800845 }
846 return -EINVAL;
847}
848
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800849int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800850 const auto ifs = getIfs(storageId);
851 if (!ifs) {
852 return -EINVAL;
853 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700854 return makeDirs(*ifs, storageId, path, mode);
855}
856
857int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
858 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800859 std::string normPath = normalizePathToStorage(ifs, storageId, path);
860 if (normPath.empty()) {
861 return -EINVAL;
862 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700863 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800864}
865
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800866int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
867 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700868 std::unique_lock l(mLock);
869 auto ifsSrc = getIfsLocked(sourceStorageId);
870 if (!ifsSrc) {
871 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800872 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700873 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
874 return -EINVAL;
875 }
876 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700877 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
878 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700879 if (normOldPath.empty() || normNewPath.empty()) {
880 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
881 return -EINVAL;
882 }
883 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800884}
885
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800886int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800887 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700888 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800889 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800890 }
891 return -EINVAL;
892}
893
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800894int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
895 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800896 std::string&& target, BindKind kind,
897 std::unique_lock<std::mutex>& mainLock) {
898 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700899 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800900 return -EINVAL;
901 }
902
903 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700904 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800905 if (kind != BindKind::Temporary) {
906 metadata::BindPoint bp;
907 bp.set_storage_id(storage);
908 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800909 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800910 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800911 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800912 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800913 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700914 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
915 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
916 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800917 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700918 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800919 return int(node);
920 }
921 }
922
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700923 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
924 std::move(target), kind, mainLock);
925 if (res) {
926 mIncFs->unlink(ifs.control, metadataFullPath);
927 }
928 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800929}
930
931int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800932 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800933 std::string&& target, BindKind kind,
934 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800935 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800936 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800937 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800938 if (!status.isOk()) {
939 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
940 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
941 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
942 : status.serviceSpecificErrorCode() == 0
943 ? -EFAULT
944 : status.serviceSpecificErrorCode()
945 : -EIO;
946 }
947 }
948
949 if (!mainLock.owns_lock()) {
950 mainLock.lock();
951 }
952 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700953 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
954 std::move(target), kind);
955 return 0;
956}
957
958void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
959 std::string&& metadataName, std::string&& source,
960 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800961 const auto [it, _] =
962 ifs.bindPoints.insert_or_assign(target,
963 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800964 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800965 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700966}
967
968RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
969 const auto ifs = getIfs(storage);
970 if (!ifs) {
971 return {};
972 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700973 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700974 if (normPath.empty()) {
975 return {};
976 }
977 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800978}
979
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800980RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800981 const auto ifs = getIfs(storage);
982 if (!ifs) {
983 return {};
984 }
985 return mIncFs->getMetadata(ifs->control, node);
986}
987
Songchun Fan3c82a302019-11-29 14:23:45 -0800988bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700989 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700990 {
991 std::unique_lock l(mLock);
992 const auto& ifs = getIfsLocked(storage);
993 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800994 return false;
995 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700996 dataLoaderStub = ifs->dataLoaderStub;
997 if (!dataLoaderStub) {
998 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700999 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001000 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001001 dataLoaderStub->requestStart();
1002 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001003}
1004
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001005std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1006 std::unordered_set<std::string_view> mountedRootNames;
1007 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1008 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1009 for (auto [source, target] : binds) {
1010 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1011 LOG(INFO) << " " << path::join(root, source);
1012 }
1013
1014 // Ensure it's a kind of a mount that's managed by IncrementalService
1015 if (path::basename(root) != constants().mount ||
1016 path::basename(backingDir) != constants().backing) {
1017 return;
1018 }
1019 const auto expectedRoot = path::dirname(root);
1020 if (path::dirname(backingDir) != expectedRoot) {
1021 return;
1022 }
1023 if (path::dirname(expectedRoot) != mIncrementalDir) {
1024 return;
1025 }
1026 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1027 return;
1028 }
1029
1030 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1031
1032 // make sure we clean up the mount if it happens to be a bad one.
1033 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1034 auto cleanupFiles = makeCleanup([&]() {
1035 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1036 IncFsMount::cleanupFilesystem(expectedRoot);
1037 });
1038 auto cleanupMounts = makeCleanup([&]() {
1039 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1040 for (auto&& [_, target] : binds) {
1041 mVold->unmountIncFs(std::string(target));
1042 }
1043 mVold->unmountIncFs(std::string(root));
1044 });
1045
1046 auto control = mIncFs->openMount(root);
1047 if (!control) {
1048 LOG(INFO) << "failed to open mount " << root;
1049 return;
1050 }
1051
1052 auto mountRecord =
1053 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1054 path::join(root, constants().infoMdName));
1055 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1056 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1057 return;
1058 }
1059
1060 auto mountId = mountRecord.storage().id();
1061 mNextId = std::max(mNextId, mountId + 1);
1062
1063 DataLoaderParamsParcel dataLoaderParams;
1064 {
1065 const auto& loader = mountRecord.loader();
1066 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1067 dataLoaderParams.packageName = loader.package_name();
1068 dataLoaderParams.className = loader.class_name();
1069 dataLoaderParams.arguments = loader.arguments();
1070 }
1071
1072 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1073 std::move(control), *this);
1074 cleanupFiles.release(); // ifs will take care of that now
1075
1076 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1077 auto d = openDir(root);
1078 while (auto e = ::readdir(d.get())) {
1079 if (e->d_type == DT_REG) {
1080 auto name = std::string_view(e->d_name);
1081 if (name.starts_with(constants().mountpointMdPrefix)) {
1082 permanentBindPoints
1083 .emplace_back(name,
1084 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1085 ifs->control,
1086 path::join(root,
1087 name)));
1088 if (permanentBindPoints.back().second.dest_path().empty() ||
1089 permanentBindPoints.back().second.source_subdir().empty()) {
1090 permanentBindPoints.pop_back();
1091 mIncFs->unlink(ifs->control, path::join(root, name));
1092 } else {
1093 LOG(INFO) << "Permanent bind record: '"
1094 << permanentBindPoints.back().second.source_subdir() << "'->'"
1095 << permanentBindPoints.back().second.dest_path() << "'";
1096 }
1097 }
1098 } else if (e->d_type == DT_DIR) {
1099 if (e->d_name == "."sv || e->d_name == ".."sv) {
1100 continue;
1101 }
1102 auto name = std::string_view(e->d_name);
1103 if (name.starts_with(constants().storagePrefix)) {
1104 int storageId;
1105 const auto res =
1106 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1107 name.data() + name.size(), storageId);
1108 if (res.ec != std::errc{} || *res.ptr != '_') {
1109 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1110 << "' for mount " << expectedRoot;
1111 continue;
1112 }
1113 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1114 if (!inserted) {
1115 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1116 << " for mount " << expectedRoot;
1117 continue;
1118 }
1119 ifs->storages.insert_or_assign(storageId,
1120 IncFsMount::Storage{path::join(root, name)});
1121 mNextId = std::max(mNextId, storageId + 1);
1122 }
1123 }
1124 }
1125
1126 if (ifs->storages.empty()) {
1127 LOG(WARNING) << "No valid storages in mount " << root;
1128 return;
1129 }
1130
1131 // now match the mounted directories with what we expect to have in the metadata
1132 {
1133 std::unique_lock l(mLock, std::defer_lock);
1134 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1135 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1136 [&, bindRecord = bindRecord](auto&& bind) {
1137 return bind.second == bindRecord.dest_path() &&
1138 path::join(root, bind.first) ==
1139 bindRecord.source_subdir();
1140 });
1141 if (mountedIt != binds.end()) {
1142 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1143 << " to mount " << mountedIt->first;
1144 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1145 std::move(*bindRecord.mutable_source_subdir()),
1146 std::move(*bindRecord.mutable_dest_path()),
1147 BindKind::Permanent);
1148 if (mountedIt != binds.end() - 1) {
1149 std::iter_swap(mountedIt, binds.end() - 1);
1150 }
1151 binds = binds.first(binds.size() - 1);
1152 } else {
1153 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1154 << ", mounting";
1155 // doesn't exist - try mounting back
1156 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1157 std::move(*bindRecord.mutable_source_subdir()),
1158 std::move(*bindRecord.mutable_dest_path()),
1159 BindKind::Permanent, l)) {
1160 mIncFs->unlink(ifs->control, metadataFile);
1161 }
1162 }
1163 }
1164 }
1165
1166 // if anything stays in |binds| those are probably temporary binds; system restarted since
1167 // they were mounted - so let's unmount them all.
1168 for (auto&& [source, target] : binds) {
1169 if (source.empty()) {
1170 continue;
1171 }
1172 mVold->unmountIncFs(std::string(target));
1173 }
1174 cleanupMounts.release(); // ifs now manages everything
1175
1176 if (ifs->bindPoints.empty()) {
1177 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1178 deleteStorage(*ifs);
1179 return;
1180 }
1181
1182 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1183 CHECK(ifs->dataLoaderStub);
1184
1185 mountedRootNames.insert(path::basename(ifs->root));
1186
1187 // not locking here at all: we're still in the constructor, no other calls can happen
1188 mMounts[ifs->mountId] = std::move(ifs);
1189 });
1190
1191 return mountedRootNames;
1192}
1193
1194void IncrementalService::mountExistingImages(
1195 const std::unordered_set<std::string_view>& mountedRootNames) {
1196 auto dir = openDir(mIncrementalDir);
1197 if (!dir) {
1198 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1199 return;
1200 }
1201 while (auto entry = ::readdir(dir.get())) {
1202 if (entry->d_type != DT_DIR) {
1203 continue;
1204 }
1205 std::string_view name = entry->d_name;
1206 if (!name.starts_with(constants().mountKeyPrefix)) {
1207 continue;
1208 }
1209 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001210 continue;
1211 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001212 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001213 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001214 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001215 }
1216 }
1217}
1218
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001219bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001220 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001221 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001222
Songchun Fan3c82a302019-11-29 14:23:45 -08001223 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001224 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001225 if (!status.isOk()) {
1226 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1227 return false;
1228 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001229
1230 int cmd = controlParcel.cmd.release().release();
1231 int pendingReads = controlParcel.pendingReads.release().release();
1232 int logs = controlParcel.log.release().release();
1233 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001234
1235 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1236
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001237 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1238 path::join(mountTarget, constants().infoMdName));
1239 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001240 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1241 return false;
1242 }
1243
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001244 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001245 mNextId = std::max(mNextId, ifs->mountId + 1);
1246
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001247 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001248 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001249 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001250 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001251 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001252 dataLoaderParams.packageName = loader.package_name();
1253 dataLoaderParams.className = loader.class_name();
1254 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001255 }
1256
Alex Buynytskyy69941662020-04-11 21:40:37 -07001257 prepareDataLoader(*ifs, std::move(dataLoaderParams), nullptr);
1258 CHECK(ifs->dataLoaderStub);
1259
Songchun Fan3c82a302019-11-29 14:23:45 -08001260 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001261 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001262 while (auto e = ::readdir(d.get())) {
1263 if (e->d_type == DT_REG) {
1264 auto name = std::string_view(e->d_name);
1265 if (name.starts_with(constants().mountpointMdPrefix)) {
1266 bindPoints.emplace_back(name,
1267 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1268 ifs->control,
1269 path::join(mountTarget,
1270 name)));
1271 if (bindPoints.back().second.dest_path().empty() ||
1272 bindPoints.back().second.source_subdir().empty()) {
1273 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001274 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001275 }
1276 }
1277 } else if (e->d_type == DT_DIR) {
1278 if (e->d_name == "."sv || e->d_name == ".."sv) {
1279 continue;
1280 }
1281 auto name = std::string_view(e->d_name);
1282 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001283 int storageId;
1284 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1285 name.data() + name.size(), storageId);
1286 if (res.ec != std::errc{} || *res.ptr != '_') {
1287 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1288 << root;
1289 continue;
1290 }
1291 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001292 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001293 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001294 << " for mount " << root;
1295 continue;
1296 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001297 ifs->storages.insert_or_assign(storageId,
1298 IncFsMount::Storage{
1299 path::join(root, constants().mount, name)});
1300 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001301 }
1302 }
1303 }
1304
1305 if (ifs->storages.empty()) {
1306 LOG(WARNING) << "No valid storages in mount " << root;
1307 return false;
1308 }
1309
1310 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001311 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001312 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001313 for (auto&& bp : bindPoints) {
1314 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1315 std::move(*bp.second.mutable_source_subdir()),
1316 std::move(*bp.second.mutable_dest_path()),
1317 BindKind::Permanent, l);
1318 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001319 }
1320
1321 if (bindCount == 0) {
1322 LOG(WARNING) << "No valid bind points for mount " << root;
1323 deleteStorage(*ifs);
1324 return false;
1325 }
1326
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001327 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001328 mMounts[ifs->mountId] = std::move(ifs);
1329 return true;
1330}
1331
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001332void IncrementalService::runCmdLooper() {
1333 constexpr auto kTimeoutMsecs = 1000;
1334 while (mRunning.load(std::memory_order_relaxed)) {
1335 mLooper->pollAll(kTimeoutMsecs);
1336 }
1337}
1338
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001339IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001340 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001341 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001342 std::unique_lock l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001343 prepareDataLoaderLocked(ifs, std::move(params), externalListener);
1344 return ifs.dataLoaderStub;
1345}
1346
1347void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
1348 const DataLoaderStatusListener* externalListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001349 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001350 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001351 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001352 }
1353
Songchun Fan3c82a302019-11-29 14:23:45 -08001354 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001355 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001356 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1357 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1358 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001359 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001360
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001361 ifs.dataLoaderStub =
1362 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001363 externalListener, path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001364}
1365
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001366template <class Duration>
1367static long elapsedMcs(Duration start, Duration end) {
1368 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1369}
1370
1371// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001372bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1373 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001374 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001375 auto start = Clock::now();
1376
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001377 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001378 if (!ifs) {
1379 LOG(ERROR) << "Invalid storage " << storage;
1380 return false;
1381 }
1382
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001383 // First prepare target directories if they don't exist yet
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001384 if (auto res = makeDirs(*ifs, storage, libDirRelativePath, 0755)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001385 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1386 << " errno: " << res;
1387 return false;
1388 }
1389
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001390 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001391 ZipArchiveHandle zipFileHandle;
1392 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001393 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1394 return false;
1395 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001396
1397 // Need a shared pointer: will be passing it into all unpacking jobs.
1398 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001399 void* cookie = nullptr;
1400 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001401 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001402 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1403 return false;
1404 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001405 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001406 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1407
1408 auto openZipTs = Clock::now();
1409
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001410 std::vector<Job> jobQueue;
1411 ZipEntry entry;
1412 std::string_view fileName;
1413 while (!Next(cookie, &entry, &fileName)) {
1414 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001415 continue;
1416 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001417
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001418 if (!extractNativeLibs) {
1419 // ensure the file is properly aligned and unpacked
1420 if (entry.method != kCompressStored) {
1421 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1422 return false;
1423 }
1424 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1425 LOG(WARNING) << "Library " << fileName
1426 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1427 << entry.offset;
1428 return false;
1429 }
1430 continue;
1431 }
1432
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001433 auto startFileTs = Clock::now();
1434
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001435 const auto libName = path::basename(fileName);
Yurii Zubrytskyi510037b2020-04-22 15:46:21 -07001436 auto targetLibPath = path::join(libDirRelativePath, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001437 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001438 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001439 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001440 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001441 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1442 << "; skipping extraction, spent "
1443 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1444 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001445 continue;
1446 }
1447
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001448 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001449 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001450 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001451 .signature = {},
1452 // Metadata of the new lib file is its relative path
1453 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1454 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001455 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001456 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1457 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001458 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001459 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001460 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001461 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001462
1463 auto makeFileTs = Clock::now();
1464
Songchun Fanafaf6e92020-03-18 14:12:20 -07001465 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001466 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001467 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001468 LOG(INFO) << "incfs: Extracted " << libName
1469 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001470 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001471 continue;
1472 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001473
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001474 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1475 libFileId, libPath = std::move(targetLibPath),
1476 makeFileTs]() mutable {
1477 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001478 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001479
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001480 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001481 auto prepareJobTs = Clock::now();
1482 LOG(INFO) << "incfs: Processed " << libName << ": "
1483 << elapsedMcs(startFileTs, prepareJobTs)
1484 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1485 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001486 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001487 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001488
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001489 auto processedTs = Clock::now();
1490
1491 if (!jobQueue.empty()) {
1492 {
1493 std::lock_guard lock(mJobMutex);
1494 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001495 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001496 if (existingJobs.empty()) {
1497 existingJobs = std::move(jobQueue);
1498 } else {
1499 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1500 std::move_iterator(jobQueue.end()));
1501 }
1502 }
1503 }
1504 mJobCondition.notify_all();
1505 }
1506
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001507 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001508 auto end = Clock::now();
1509 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1510 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1511 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001512 << " make files: " << elapsedMcs(openZipTs, processedTs)
1513 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001514 }
1515
1516 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001517}
1518
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001519void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1520 ZipEntry& entry, const incfs::FileId& libFileId,
1521 std::string_view targetLibPath,
1522 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001523 if (!ifs) {
1524 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1525 return;
1526 }
1527
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001528 auto libName = path::basename(targetLibPath);
1529 auto startedTs = Clock::now();
1530
1531 // Write extracted data to new file
1532 // NOTE: don't zero-initialize memory, it may take a while for nothing
1533 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1534 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1535 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1536 return;
1537 }
1538
1539 auto extractFileTs = Clock::now();
1540
1541 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1542 if (!writeFd.ok()) {
1543 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1544 return;
1545 }
1546
1547 auto openFileTs = Clock::now();
1548 const int numBlocks =
1549 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1550 std::vector<IncFsDataBlock> instructions(numBlocks);
1551 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1552 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001553 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001554 instructions[i] = IncFsDataBlock{
1555 .fileFd = writeFd.get(),
1556 .pageIndex = static_cast<IncFsBlockIndex>(i),
1557 .compression = INCFS_COMPRESSION_KIND_NONE,
1558 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001559 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001560 .data = reinterpret_cast<const char*>(remainingData.data()),
1561 };
1562 remainingData = remainingData.subspan(blockSize);
1563 }
1564 auto prepareInstsTs = Clock::now();
1565
1566 size_t res = mIncFs->writeBlocks(instructions);
1567 if (res != instructions.size()) {
1568 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1569 return;
1570 }
1571
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001572 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001573 auto endFileTs = Clock::now();
1574 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1575 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1576 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1577 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1578 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1579 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1580 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1581 }
1582}
1583
1584bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001585 struct WaitPrinter {
1586 const Clock::time_point startTs = Clock::now();
1587 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001588 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001589 const auto endTs = Clock::now();
1590 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1591 << elapsedMcs(startTs, endTs) << "mcs";
1592 }
1593 }
1594 } waitPrinter;
1595
1596 MountId mount;
1597 {
1598 auto ifs = getIfs(storage);
1599 if (!ifs) {
1600 return true;
1601 }
1602 mount = ifs->mountId;
1603 }
1604
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001605 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001606 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001607 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001608 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001609 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001610 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001611}
1612
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001613bool IncrementalService::perfLoggingEnabled() {
1614 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1615 return enabled;
1616}
1617
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001618void IncrementalService::runJobProcessing() {
1619 for (;;) {
1620 std::unique_lock lock(mJobMutex);
1621 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1622 if (!mRunning) {
1623 return;
1624 }
1625
1626 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001627 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001628 auto queue = std::move(it->second);
1629 mJobQueue.erase(it);
1630 lock.unlock();
1631
1632 for (auto&& job : queue) {
1633 job();
1634 }
1635
1636 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001637 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001638 lock.unlock();
1639 mJobCondition.notify_all();
1640 }
1641}
1642
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001643void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001644 sp<IAppOpsCallback> listener;
1645 {
1646 std::unique_lock lock{mCallbacksLock};
1647 auto& cb = mCallbackRegistered[packageName];
1648 if (cb) {
1649 return;
1650 }
1651 cb = new AppOpsListener(*this, packageName);
1652 listener = cb;
1653 }
1654
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001655 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1656 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001657}
1658
1659bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1660 sp<IAppOpsCallback> listener;
1661 {
1662 std::unique_lock lock{mCallbacksLock};
1663 auto found = mCallbackRegistered.find(packageName);
1664 if (found == mCallbackRegistered.end()) {
1665 return false;
1666 }
1667 listener = found->second;
1668 mCallbackRegistered.erase(found);
1669 }
1670
1671 mAppOpsManager->stopWatchingMode(listener);
1672 return true;
1673}
1674
1675void IncrementalService::onAppOpChanged(const std::string& packageName) {
1676 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001677 return;
1678 }
1679
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001680 std::vector<IfsMountPtr> affected;
1681 {
1682 std::lock_guard l(mLock);
1683 affected.reserve(mMounts.size());
1684 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001685 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001686 affected.push_back(ifs);
1687 }
1688 }
1689 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001690 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001691 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001692 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001693}
1694
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001695IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1696 DataLoaderParamsParcel&& params,
1697 FileSystemControlParcel&& control,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001698 const DataLoaderStatusListener* externalListener,
1699 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001700 : mService(service),
1701 mId(id),
1702 mParams(std::move(params)),
1703 mControl(std::move(control)),
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001704 mListener(externalListener ? *externalListener : DataLoaderStatusListener()),
1705 mHealthPath(std::move(healthPath)) {
1706 healthStatusOk();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001707}
1708
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001709IncrementalService::DataLoaderStub::~DataLoaderStub() {
1710 if (mId != kInvalidStorageId) {
1711 cleanupResources();
1712 }
1713}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001714
1715void IncrementalService::DataLoaderStub::cleanupResources() {
1716 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001717
1718 auto now = Clock::now();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001719 std::unique_lock lock(mMutex);
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001720
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001721 unregisterFromPendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001722
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001723 mParams = {};
1724 mControl = {};
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001725 mStatusCondition.wait_until(lock, now + 60s, [this] {
1726 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1727 });
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001728 mListener = {};
1729 mId = kInvalidStorageId;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001730}
1731
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001732sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1733 sp<IDataLoader> dataloader;
1734 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1735 if (!status.isOk()) {
1736 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1737 return {};
1738 }
1739 if (!dataloader) {
1740 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1741 return {};
1742 }
1743 return dataloader;
1744}
1745
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001746bool IncrementalService::DataLoaderStub::requestCreate() {
1747 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1748}
1749
1750bool IncrementalService::DataLoaderStub::requestStart() {
1751 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1752}
1753
1754bool IncrementalService::DataLoaderStub::requestDestroy() {
1755 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1756}
1757
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001758bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001759 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001760 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001761 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001762 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001763 return fsmStep();
1764}
1765
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001766void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001767 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001768 mTargetStatus = status;
1769 mTargetStatusTs = Clock::now();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001770 LOG(DEBUG) << "Target status update for DataLoader " << mId << ": " << oldStatus << " -> "
1771 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001772}
1773
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001774bool IncrementalService::DataLoaderStub::bind() {
1775 bool result = false;
1776 auto status = mService.mDataLoaderManager->bindToDataLoader(mId, mParams, this, &result);
1777 if (!status.isOk() || !result) {
1778 LOG(ERROR) << "Failed to bind a data loader for mount " << mId;
1779 return false;
1780 }
1781 return true;
1782}
1783
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001784bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001785 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001786 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001787 return false;
1788 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001789 auto status = dataloader->create(mId, mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001790 if (!status.isOk()) {
1791 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001792 return false;
1793 }
1794 return true;
1795}
1796
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001797bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001798 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001799 if (!dataloader) {
1800 return false;
1801 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001802 auto status = dataloader->start(mId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001803 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001804 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001805 return false;
1806 }
1807 return true;
1808}
1809
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001810bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001811 return mService.mDataLoaderManager->unbindFromDataLoader(mId).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001812}
1813
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001814bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001815 if (!isValid()) {
1816 return false;
1817 }
1818
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001819 int currentStatus;
1820 int targetStatus;
1821 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001822 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001823 currentStatus = mCurrentStatus;
1824 targetStatus = mTargetStatus;
1825 }
1826
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001827 LOG(DEBUG) << "fsmStep: " << mId << ": " << currentStatus << " -> " << targetStatus;
1828
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001829 if (currentStatus == targetStatus) {
1830 return true;
1831 }
1832
1833 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001834 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
1835 // Do nothing, this is a reset state.
1836 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001837 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1838 return destroy();
1839 }
1840 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1841 switch (currentStatus) {
1842 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1843 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1844 return start();
1845 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001846 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001847 }
1848 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1849 switch (currentStatus) {
1850 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001851 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001852 return bind();
1853 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001854 return create();
1855 }
1856 break;
1857 default:
1858 LOG(ERROR) << "Invalid target status: " << targetStatus
1859 << ", current status: " << currentStatus;
1860 break;
1861 }
1862 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001863}
1864
1865binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001866 if (!isValid()) {
1867 return binder::Status::
1868 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
1869 }
1870 if (mId != mountId) {
1871 LOG(ERROR) << "Mount ID mismatch: expected " << mId << ", but got: " << mountId;
1872 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
1873 }
1874
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001875 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001876 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001877 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001878 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001879 if (mCurrentStatus == newStatus) {
1880 return binder::Status::ok();
1881 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001882
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001883 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001884 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001885 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001886
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001887 listener = mListener;
1888
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001889 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001890 // For unavailable, unbind from DataLoader to ensure proper re-commit.
1891 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001892 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001893 }
1894
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001895 LOG(DEBUG) << "Current status update for DataLoader " << mId << ": " << oldStatus << " -> "
1896 << newStatus << " (target " << targetStatus << ")";
1897
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001898 if (listener) {
1899 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001900 }
1901
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001902 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08001903
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07001904 mStatusCondition.notify_all();
1905
Songchun Fan3c82a302019-11-29 14:23:45 -08001906 return binder::Status::ok();
1907}
1908
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001909void IncrementalService::DataLoaderStub::healthStatusOk() {
1910 LOG(DEBUG) << "healthStatusOk: " << mId;
1911 std::unique_lock lock(mMutex);
1912 registerForPendingReads();
1913}
1914
1915void IncrementalService::DataLoaderStub::healthStatusReadsPending() {
1916 LOG(DEBUG) << "healthStatusReadsPending: " << mId;
1917 requestStart();
1918
1919 std::unique_lock lock(mMutex);
1920 unregisterFromPendingReads();
1921}
1922
1923void IncrementalService::DataLoaderStub::healthStatusBlocked() {}
1924
1925void IncrementalService::DataLoaderStub::healthStatusUnhealthy() {}
1926
1927void IncrementalService::DataLoaderStub::registerForPendingReads() {
1928 auto pendingReadsFd = mHealthControl.pendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001929 if (pendingReadsFd < 0) {
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001930 mHealthControl = mService.mIncFs->openMount(mHealthPath);
1931 pendingReadsFd = mHealthControl.pendingReads();
1932 if (pendingReadsFd < 0) {
1933 LOG(ERROR) << "Failed to open health control for: " << mId << ", path: " << mHealthPath
1934 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
1935 << mHealthControl.logs() << ")";
1936 return;
1937 }
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001938 }
1939
1940 mService.mLooper->addFd(
1941 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
1942 [](int, int, void* data) -> int {
1943 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001944 return self->onPendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001945 },
1946 this);
1947 mService.mLooper->wake();
1948}
1949
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001950void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001951 const auto pendingReadsFd = mHealthControl.pendingReads();
1952 if (pendingReadsFd < 0) {
1953 return;
1954 }
1955
1956 mService.mLooper->removeFd(pendingReadsFd);
1957 mService.mLooper->wake();
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001958
1959 mHealthControl = {};
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001960}
1961
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001962int IncrementalService::DataLoaderStub::onPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001963 if (!mService.mRunning.load(std::memory_order_relaxed)) {
1964 return 0;
1965 }
1966
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001967 healthStatusReadsPending();
1968 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001969}
1970
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001971void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001972 dprintf(fd, " dataLoader: {\n");
1973 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
1974 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
1975 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001976 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
1977 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001978 dprintf(fd, " dataLoaderParams: {\n");
1979 dprintf(fd, " type: %s\n", toString(params.type).c_str());
1980 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
1981 dprintf(fd, " className: %s\n", params.className.c_str());
1982 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
1983 dprintf(fd, " }\n");
1984 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001985}
1986
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001987void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1988 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001989}
1990
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001991binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1992 bool enableReadLogs, int32_t* _aidl_return) {
1993 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1994 return binder::Status::ok();
1995}
1996
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001997FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
1998 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
1999}
2000
Songchun Fan3c82a302019-11-29 14:23:45 -08002001} // namespace android::incremental