blob: 66c7717d79876be950b8345c4caa3713bc8c14c0 [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
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700413StorageId IncrementalService::createStorage(std::string_view mountPoint,
414 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
415 CreateOptions options,
416 const DataLoaderStatusListener& statusListener,
417 StorageHealthCheckParams&& healthCheckParams,
418 const StorageHealthListener& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800419 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
420 if (!path::isAbsolute(mountPoint)) {
421 LOG(ERROR) << "path is not absolute: " << mountPoint;
422 return kInvalidStorageId;
423 }
424
425 auto mountNorm = path::normalize(mountPoint);
426 {
427 const auto id = findStorageId(mountNorm);
428 if (id != kInvalidStorageId) {
429 if (options & CreateOptions::OpenExisting) {
430 LOG(INFO) << "Opened existing storage " << id;
431 return id;
432 }
433 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
434 return kInvalidStorageId;
435 }
436 }
437
438 if (!(options & CreateOptions::CreateNew)) {
439 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
440 return kInvalidStorageId;
441 }
442
443 if (!path::isEmptyDir(mountNorm)) {
444 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
445 return kInvalidStorageId;
446 }
447 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
448 if (mountRoot.empty()) {
449 LOG(ERROR) << "Bad mount point";
450 return kInvalidStorageId;
451 }
452 // Make sure the code removes all crap it may create while still failing.
453 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
454 auto firstCleanupOnFailure =
455 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
456
457 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800458 const auto backing = path::join(mountRoot, constants().backing);
459 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800460 return kInvalidStorageId;
461 }
462
Songchun Fan3c82a302019-11-29 14:23:45 -0800463 IncFsMount::Control control;
464 {
465 std::lock_guard l(mMountOperationLock);
466 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800467
468 if (auto err = rmDirContent(backing.c_str())) {
469 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
470 return kInvalidStorageId;
471 }
472 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
473 return kInvalidStorageId;
474 }
475 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800476 if (!status.isOk()) {
477 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
478 return kInvalidStorageId;
479 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800480 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
481 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800482 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
483 return kInvalidStorageId;
484 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800485 int cmd = controlParcel.cmd.release().release();
486 int pendingReads = controlParcel.pendingReads.release().release();
487 int logs = controlParcel.log.release().release();
488 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800489 }
490
491 std::unique_lock l(mLock);
492 const auto mountIt = getStorageSlotLocked();
493 const auto mountId = mountIt->first;
494 l.unlock();
495
496 auto ifs =
497 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
498 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
499 // is the removal of the |ifs|.
500 firstCleanupOnFailure.release();
501
502 auto secondCleanup = [this, &l](auto itPtr) {
503 if (!l.owns_lock()) {
504 l.lock();
505 }
506 mMounts.erase(*itPtr);
507 };
508 auto secondCleanupOnFailure =
509 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
510
511 const auto storageIt = ifs->makeStorage(ifs->mountId);
512 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800513 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800514 return kInvalidStorageId;
515 }
516
517 {
518 metadata::Mount m;
519 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700520 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700521 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
522 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
523 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800524 const auto metadata = m.SerializeAsString();
525 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800526 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800527 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800528 if (auto err =
529 mIncFs->makeFile(ifs->control,
530 path::join(ifs->root, constants().mount,
531 constants().infoMdName),
532 0777, idFromMetadata(metadata),
533 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800534 LOG(ERROR) << "Saving mount metadata failed: " << -err;
535 return kInvalidStorageId;
536 }
537 }
538
539 const auto bk =
540 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800541 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
542 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800543 err < 0) {
544 LOG(ERROR) << "adding bind mount failed: " << -err;
545 return kInvalidStorageId;
546 }
547
548 // Done here as well, all data structures are in good state.
549 secondCleanupOnFailure.release();
550
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700551 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
552 std::move(healthCheckParams), &healthListener);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700553 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800554
555 mountIt->second = std::move(ifs);
556 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700557
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700558 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700559 // failed to create data loader
560 LOG(ERROR) << "initializeDataLoader() failed";
561 deleteStorage(dataLoaderStub->id());
562 return kInvalidStorageId;
563 }
564
Songchun Fan3c82a302019-11-29 14:23:45 -0800565 LOG(INFO) << "created storage " << mountId;
566 return mountId;
567}
568
569StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
570 StorageId linkedStorage,
571 IncrementalService::CreateOptions options) {
572 if (!isValidMountTarget(mountPoint)) {
573 LOG(ERROR) << "Mount point is invalid or missing";
574 return kInvalidStorageId;
575 }
576
577 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700578 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800579 if (!ifs) {
580 LOG(ERROR) << "Ifs unavailable";
581 return kInvalidStorageId;
582 }
583
584 const auto mountIt = getStorageSlotLocked();
585 const auto storageId = mountIt->first;
586 const auto storageIt = ifs->makeStorage(storageId);
587 if (storageIt == ifs->storages.end()) {
588 LOG(ERROR) << "Can't create a new storage";
589 mMounts.erase(mountIt);
590 return kInvalidStorageId;
591 }
592
593 l.unlock();
594
595 const auto bk =
596 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800597 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
598 std::string(storageIt->second.name), path::normalize(mountPoint),
599 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800600 err < 0) {
601 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700602 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
603 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800604 return kInvalidStorageId;
605 }
606
607 mountIt->second = ifs;
608 return storageId;
609}
610
611IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
612 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700613 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800614}
615
616StorageId IncrementalService::findStorageId(std::string_view path) const {
617 std::lock_guard l(mLock);
618 auto it = findStorageLocked(path);
619 if (it == mBindsByPath.end()) {
620 return kInvalidStorageId;
621 }
622 return it->second->second.storage;
623}
624
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700625int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
626 const auto ifs = getIfs(storageId);
627 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700628 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700629 return -EINVAL;
630 }
631
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700632 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700633 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700634 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
635 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700636 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700637 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700638 return fromBinderStatus(status);
639 }
640 }
641
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700642 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
643 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
644 return fromBinderStatus(status);
645 }
646
647 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700648 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700649 }
650
651 return 0;
652}
653
654binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700655 os::incremental::IncrementalFileSystemControlParcel control;
656 control.cmd.reset(dup(ifs.control.cmd()));
657 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700658 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700659 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700660 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700661 }
662
663 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700664 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700665}
666
Songchun Fan3c82a302019-11-29 14:23:45 -0800667void IncrementalService::deleteStorage(StorageId storageId) {
668 const auto ifs = getIfs(storageId);
669 if (!ifs) {
670 return;
671 }
672 deleteStorage(*ifs);
673}
674
675void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
676 std::unique_lock l(ifs.lock);
677 deleteStorageLocked(ifs, std::move(l));
678}
679
680void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
681 std::unique_lock<std::mutex>&& ifsLock) {
682 const auto storages = std::move(ifs.storages);
683 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
684 const auto bindPoints = ifs.bindPoints;
685 ifsLock.unlock();
686
687 std::lock_guard l(mLock);
688 for (auto&& [id, _] : storages) {
689 if (id != ifs.mountId) {
690 mMounts.erase(id);
691 }
692 }
693 for (auto&& [path, _] : bindPoints) {
694 mBindsByPath.erase(path);
695 }
696 mMounts.erase(ifs.mountId);
697}
698
699StorageId IncrementalService::openStorage(std::string_view pathInMount) {
700 if (!path::isAbsolute(pathInMount)) {
701 return kInvalidStorageId;
702 }
703
704 return findStorageId(path::normalize(pathInMount));
705}
706
Songchun Fan3c82a302019-11-29 14:23:45 -0800707IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
708 std::lock_guard l(mLock);
709 return getIfsLocked(storage);
710}
711
712const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
713 auto it = mMounts.find(storage);
714 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700715 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700716 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800717 }
718 return it->second;
719}
720
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800721int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
722 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800723 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700724 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800725 return -EINVAL;
726 }
727
728 const auto ifs = getIfs(storage);
729 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700730 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800731 return -EINVAL;
732 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800733
Songchun Fan3c82a302019-11-29 14:23:45 -0800734 std::unique_lock l(ifs->lock);
735 const auto storageInfo = ifs->storages.find(storage);
736 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700737 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800738 return -EINVAL;
739 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700740 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700741 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700742 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700743 return -EINVAL;
744 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800745 l.unlock();
746 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800747 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
748 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800749}
750
751int IncrementalService::unbind(StorageId storage, std::string_view target) {
752 if (!path::isAbsolute(target)) {
753 return -EINVAL;
754 }
755
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700756 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800757
758 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
759 // otherwise there's a chance to unmount something completely unrelated
760 const auto norm = path::normalize(target);
761 std::unique_lock l(mLock);
762 const auto storageIt = mBindsByPath.find(norm);
763 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
764 return -EINVAL;
765 }
766 const auto bindIt = storageIt->second;
767 const auto storageId = bindIt->second.storage;
768 const auto ifs = getIfsLocked(storageId);
769 if (!ifs) {
770 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
771 << " is missing";
772 return -EFAULT;
773 }
774 mBindsByPath.erase(storageIt);
775 l.unlock();
776
777 mVold->unmountIncFs(bindIt->first);
778 std::unique_lock l2(ifs->lock);
779 if (ifs->bindPoints.size() <= 1) {
780 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700781 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800782 } else {
783 const std::string savedFile = std::move(bindIt->second.savedFilename);
784 ifs->bindPoints.erase(bindIt);
785 l2.unlock();
786 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800787 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800788 }
789 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700790
Songchun Fan3c82a302019-11-29 14:23:45 -0800791 return 0;
792}
793
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700794std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700795 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700796 std::string_view path) const {
797 if (!path::isAbsolute(path)) {
798 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700799 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700800 auto normPath = path::normalize(path);
801 if (path::startsWith(normPath, storageIt->second.name)) {
802 return normPath;
803 }
804 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700805 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
806 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700807 return {};
808 }
809 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700810}
811
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700812std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700813 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700814 std::unique_lock l(ifs.lock);
815 const auto storageInfo = ifs.storages.find(storage);
816 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800817 return {};
818 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700819 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800820}
821
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800822int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
823 incfs::NewFileParams params) {
824 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700825 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800826 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700827 LOG(ERROR) << "Internal error: storageId " << storage
828 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800829 return -EINVAL;
830 }
831 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800832 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700833 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800834 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800835 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800836 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800837 }
838 return -EINVAL;
839}
840
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800841int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800842 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700843 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800844 if (normPath.empty()) {
845 return -EINVAL;
846 }
847 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800848 }
849 return -EINVAL;
850}
851
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800852int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800853 const auto ifs = getIfs(storageId);
854 if (!ifs) {
855 return -EINVAL;
856 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700857 return makeDirs(*ifs, storageId, path, mode);
858}
859
860int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
861 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800862 std::string normPath = normalizePathToStorage(ifs, storageId, path);
863 if (normPath.empty()) {
864 return -EINVAL;
865 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700866 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800867}
868
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800869int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
870 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700871 std::unique_lock l(mLock);
872 auto ifsSrc = getIfsLocked(sourceStorageId);
873 if (!ifsSrc) {
874 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800875 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700876 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
877 return -EINVAL;
878 }
879 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700880 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
881 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700882 if (normOldPath.empty() || normNewPath.empty()) {
883 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
884 return -EINVAL;
885 }
886 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800887}
888
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800889int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800890 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700891 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800892 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800893 }
894 return -EINVAL;
895}
896
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800897int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
898 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800899 std::string&& target, BindKind kind,
900 std::unique_lock<std::mutex>& mainLock) {
901 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700902 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800903 return -EINVAL;
904 }
905
906 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700907 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800908 if (kind != BindKind::Temporary) {
909 metadata::BindPoint bp;
910 bp.set_storage_id(storage);
911 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800912 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800913 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800914 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800915 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800916 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700917 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
918 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
919 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800920 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700921 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800922 return int(node);
923 }
924 }
925
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700926 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
927 std::move(target), kind, mainLock);
928 if (res) {
929 mIncFs->unlink(ifs.control, metadataFullPath);
930 }
931 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800932}
933
934int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800935 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800936 std::string&& target, BindKind kind,
937 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800938 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800939 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800940 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800941 if (!status.isOk()) {
942 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
943 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
944 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
945 : status.serviceSpecificErrorCode() == 0
946 ? -EFAULT
947 : status.serviceSpecificErrorCode()
948 : -EIO;
949 }
950 }
951
952 if (!mainLock.owns_lock()) {
953 mainLock.lock();
954 }
955 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700956 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
957 std::move(target), kind);
958 return 0;
959}
960
961void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
962 std::string&& metadataName, std::string&& source,
963 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800964 const auto [it, _] =
965 ifs.bindPoints.insert_or_assign(target,
966 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800967 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800968 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700969}
970
971RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
972 const auto ifs = getIfs(storage);
973 if (!ifs) {
974 return {};
975 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700976 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700977 if (normPath.empty()) {
978 return {};
979 }
980 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800981}
982
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800983RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800984 const auto ifs = getIfs(storage);
985 if (!ifs) {
986 return {};
987 }
988 return mIncFs->getMetadata(ifs->control, node);
989}
990
Songchun Fan3c82a302019-11-29 14:23:45 -0800991bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700992 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700993 {
994 std::unique_lock l(mLock);
995 const auto& ifs = getIfsLocked(storage);
996 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800997 return false;
998 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700999 dataLoaderStub = ifs->dataLoaderStub;
1000 if (!dataLoaderStub) {
1001 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001002 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001003 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001004 dataLoaderStub->requestStart();
1005 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001006}
1007
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001008std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1009 std::unordered_set<std::string_view> mountedRootNames;
1010 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1011 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1012 for (auto [source, target] : binds) {
1013 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1014 LOG(INFO) << " " << path::join(root, source);
1015 }
1016
1017 // Ensure it's a kind of a mount that's managed by IncrementalService
1018 if (path::basename(root) != constants().mount ||
1019 path::basename(backingDir) != constants().backing) {
1020 return;
1021 }
1022 const auto expectedRoot = path::dirname(root);
1023 if (path::dirname(backingDir) != expectedRoot) {
1024 return;
1025 }
1026 if (path::dirname(expectedRoot) != mIncrementalDir) {
1027 return;
1028 }
1029 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1030 return;
1031 }
1032
1033 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1034
1035 // make sure we clean up the mount if it happens to be a bad one.
1036 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1037 auto cleanupFiles = makeCleanup([&]() {
1038 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1039 IncFsMount::cleanupFilesystem(expectedRoot);
1040 });
1041 auto cleanupMounts = makeCleanup([&]() {
1042 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1043 for (auto&& [_, target] : binds) {
1044 mVold->unmountIncFs(std::string(target));
1045 }
1046 mVold->unmountIncFs(std::string(root));
1047 });
1048
1049 auto control = mIncFs->openMount(root);
1050 if (!control) {
1051 LOG(INFO) << "failed to open mount " << root;
1052 return;
1053 }
1054
1055 auto mountRecord =
1056 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1057 path::join(root, constants().infoMdName));
1058 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1059 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1060 return;
1061 }
1062
1063 auto mountId = mountRecord.storage().id();
1064 mNextId = std::max(mNextId, mountId + 1);
1065
1066 DataLoaderParamsParcel dataLoaderParams;
1067 {
1068 const auto& loader = mountRecord.loader();
1069 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1070 dataLoaderParams.packageName = loader.package_name();
1071 dataLoaderParams.className = loader.class_name();
1072 dataLoaderParams.arguments = loader.arguments();
1073 }
1074
1075 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1076 std::move(control), *this);
1077 cleanupFiles.release(); // ifs will take care of that now
1078
1079 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1080 auto d = openDir(root);
1081 while (auto e = ::readdir(d.get())) {
1082 if (e->d_type == DT_REG) {
1083 auto name = std::string_view(e->d_name);
1084 if (name.starts_with(constants().mountpointMdPrefix)) {
1085 permanentBindPoints
1086 .emplace_back(name,
1087 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1088 ifs->control,
1089 path::join(root,
1090 name)));
1091 if (permanentBindPoints.back().second.dest_path().empty() ||
1092 permanentBindPoints.back().second.source_subdir().empty()) {
1093 permanentBindPoints.pop_back();
1094 mIncFs->unlink(ifs->control, path::join(root, name));
1095 } else {
1096 LOG(INFO) << "Permanent bind record: '"
1097 << permanentBindPoints.back().second.source_subdir() << "'->'"
1098 << permanentBindPoints.back().second.dest_path() << "'";
1099 }
1100 }
1101 } else if (e->d_type == DT_DIR) {
1102 if (e->d_name == "."sv || e->d_name == ".."sv) {
1103 continue;
1104 }
1105 auto name = std::string_view(e->d_name);
1106 if (name.starts_with(constants().storagePrefix)) {
1107 int storageId;
1108 const auto res =
1109 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1110 name.data() + name.size(), storageId);
1111 if (res.ec != std::errc{} || *res.ptr != '_') {
1112 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1113 << "' for mount " << expectedRoot;
1114 continue;
1115 }
1116 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1117 if (!inserted) {
1118 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1119 << " for mount " << expectedRoot;
1120 continue;
1121 }
1122 ifs->storages.insert_or_assign(storageId,
1123 IncFsMount::Storage{path::join(root, name)});
1124 mNextId = std::max(mNextId, storageId + 1);
1125 }
1126 }
1127 }
1128
1129 if (ifs->storages.empty()) {
1130 LOG(WARNING) << "No valid storages in mount " << root;
1131 return;
1132 }
1133
1134 // now match the mounted directories with what we expect to have in the metadata
1135 {
1136 std::unique_lock l(mLock, std::defer_lock);
1137 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1138 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1139 [&, bindRecord = bindRecord](auto&& bind) {
1140 return bind.second == bindRecord.dest_path() &&
1141 path::join(root, bind.first) ==
1142 bindRecord.source_subdir();
1143 });
1144 if (mountedIt != binds.end()) {
1145 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1146 << " to mount " << mountedIt->first;
1147 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1148 std::move(*bindRecord.mutable_source_subdir()),
1149 std::move(*bindRecord.mutable_dest_path()),
1150 BindKind::Permanent);
1151 if (mountedIt != binds.end() - 1) {
1152 std::iter_swap(mountedIt, binds.end() - 1);
1153 }
1154 binds = binds.first(binds.size() - 1);
1155 } else {
1156 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1157 << ", mounting";
1158 // doesn't exist - try mounting back
1159 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1160 std::move(*bindRecord.mutable_source_subdir()),
1161 std::move(*bindRecord.mutable_dest_path()),
1162 BindKind::Permanent, l)) {
1163 mIncFs->unlink(ifs->control, metadataFile);
1164 }
1165 }
1166 }
1167 }
1168
1169 // if anything stays in |binds| those are probably temporary binds; system restarted since
1170 // they were mounted - so let's unmount them all.
1171 for (auto&& [source, target] : binds) {
1172 if (source.empty()) {
1173 continue;
1174 }
1175 mVold->unmountIncFs(std::string(target));
1176 }
1177 cleanupMounts.release(); // ifs now manages everything
1178
1179 if (ifs->bindPoints.empty()) {
1180 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1181 deleteStorage(*ifs);
1182 return;
1183 }
1184
1185 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1186 CHECK(ifs->dataLoaderStub);
1187
1188 mountedRootNames.insert(path::basename(ifs->root));
1189
1190 // not locking here at all: we're still in the constructor, no other calls can happen
1191 mMounts[ifs->mountId] = std::move(ifs);
1192 });
1193
1194 return mountedRootNames;
1195}
1196
1197void IncrementalService::mountExistingImages(
1198 const std::unordered_set<std::string_view>& mountedRootNames) {
1199 auto dir = openDir(mIncrementalDir);
1200 if (!dir) {
1201 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1202 return;
1203 }
1204 while (auto entry = ::readdir(dir.get())) {
1205 if (entry->d_type != DT_DIR) {
1206 continue;
1207 }
1208 std::string_view name = entry->d_name;
1209 if (!name.starts_with(constants().mountKeyPrefix)) {
1210 continue;
1211 }
1212 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001213 continue;
1214 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001215 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001216 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001217 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001218 }
1219 }
1220}
1221
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001222bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001223 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001224 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001225
Songchun Fan3c82a302019-11-29 14:23:45 -08001226 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001227 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001228 if (!status.isOk()) {
1229 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1230 return false;
1231 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001232
1233 int cmd = controlParcel.cmd.release().release();
1234 int pendingReads = controlParcel.pendingReads.release().release();
1235 int logs = controlParcel.log.release().release();
1236 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001237
1238 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1239
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001240 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1241 path::join(mountTarget, constants().infoMdName));
1242 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001243 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1244 return false;
1245 }
1246
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001247 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001248 mNextId = std::max(mNextId, ifs->mountId + 1);
1249
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001250 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001251 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001252 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001253 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001254 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001255 dataLoaderParams.packageName = loader.package_name();
1256 dataLoaderParams.className = loader.class_name();
1257 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001258 }
1259
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001260 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001261 CHECK(ifs->dataLoaderStub);
1262
Songchun Fan3c82a302019-11-29 14:23:45 -08001263 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001264 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001265 while (auto e = ::readdir(d.get())) {
1266 if (e->d_type == DT_REG) {
1267 auto name = std::string_view(e->d_name);
1268 if (name.starts_with(constants().mountpointMdPrefix)) {
1269 bindPoints.emplace_back(name,
1270 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1271 ifs->control,
1272 path::join(mountTarget,
1273 name)));
1274 if (bindPoints.back().second.dest_path().empty() ||
1275 bindPoints.back().second.source_subdir().empty()) {
1276 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001277 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001278 }
1279 }
1280 } else if (e->d_type == DT_DIR) {
1281 if (e->d_name == "."sv || e->d_name == ".."sv) {
1282 continue;
1283 }
1284 auto name = std::string_view(e->d_name);
1285 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001286 int storageId;
1287 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1288 name.data() + name.size(), storageId);
1289 if (res.ec != std::errc{} || *res.ptr != '_') {
1290 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1291 << root;
1292 continue;
1293 }
1294 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001295 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001296 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001297 << " for mount " << root;
1298 continue;
1299 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001300 ifs->storages.insert_or_assign(storageId,
1301 IncFsMount::Storage{
1302 path::join(root, constants().mount, name)});
1303 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001304 }
1305 }
1306 }
1307
1308 if (ifs->storages.empty()) {
1309 LOG(WARNING) << "No valid storages in mount " << root;
1310 return false;
1311 }
1312
1313 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001314 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001315 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001316 for (auto&& bp : bindPoints) {
1317 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1318 std::move(*bp.second.mutable_source_subdir()),
1319 std::move(*bp.second.mutable_dest_path()),
1320 BindKind::Permanent, l);
1321 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001322 }
1323
1324 if (bindCount == 0) {
1325 LOG(WARNING) << "No valid bind points for mount " << root;
1326 deleteStorage(*ifs);
1327 return false;
1328 }
1329
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001330 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001331 mMounts[ifs->mountId] = std::move(ifs);
1332 return true;
1333}
1334
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001335void IncrementalService::runCmdLooper() {
1336 constexpr auto kTimeoutMsecs = 1000;
1337 while (mRunning.load(std::memory_order_relaxed)) {
1338 mLooper->pollAll(kTimeoutMsecs);
1339 }
1340}
1341
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001342IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001343 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001344 const DataLoaderStatusListener* statusListener,
1345 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001346 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001347 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1348 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001349 return ifs.dataLoaderStub;
1350}
1351
1352void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001353 const DataLoaderStatusListener* statusListener,
1354 StorageHealthCheckParams&& healthCheckParams,
1355 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001356 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001357 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001358 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001359 }
1360
Songchun Fan3c82a302019-11-29 14:23:45 -08001361 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001362 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001363 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1364 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1365 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001366 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001367
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001368 ifs.dataLoaderStub =
1369 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001370 statusListener, std::move(healthCheckParams), healthListener,
1371 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001372}
1373
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001374template <class Duration>
1375static long elapsedMcs(Duration start, Duration end) {
1376 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1377}
1378
1379// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001380bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1381 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001382 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001383 auto start = Clock::now();
1384
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001385 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001386 if (!ifs) {
1387 LOG(ERROR) << "Invalid storage " << storage;
1388 return false;
1389 }
1390
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001391 // First prepare target directories if they don't exist yet
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001392 if (auto res = makeDirs(*ifs, storage, libDirRelativePath, 0755)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001393 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1394 << " errno: " << res;
1395 return false;
1396 }
1397
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001398 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001399 ZipArchiveHandle zipFileHandle;
1400 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001401 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1402 return false;
1403 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001404
1405 // Need a shared pointer: will be passing it into all unpacking jobs.
1406 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001407 void* cookie = nullptr;
1408 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001409 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001410 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1411 return false;
1412 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001413 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001414 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1415
1416 auto openZipTs = Clock::now();
1417
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001418 std::vector<Job> jobQueue;
1419 ZipEntry entry;
1420 std::string_view fileName;
1421 while (!Next(cookie, &entry, &fileName)) {
1422 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001423 continue;
1424 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001425
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001426 if (!extractNativeLibs) {
1427 // ensure the file is properly aligned and unpacked
1428 if (entry.method != kCompressStored) {
1429 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1430 return false;
1431 }
1432 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1433 LOG(WARNING) << "Library " << fileName
1434 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1435 << entry.offset;
1436 return false;
1437 }
1438 continue;
1439 }
1440
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001441 auto startFileTs = Clock::now();
1442
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001443 const auto libName = path::basename(fileName);
Yurii Zubrytskyi510037b2020-04-22 15:46:21 -07001444 auto targetLibPath = path::join(libDirRelativePath, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001445 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001446 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001447 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001448 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001449 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1450 << "; skipping extraction, spent "
1451 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1452 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001453 continue;
1454 }
1455
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001456 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001457 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001458 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001459 .signature = {},
1460 // Metadata of the new lib file is its relative path
1461 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1462 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001463 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001464 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1465 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001466 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001467 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001468 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001469 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001470
1471 auto makeFileTs = Clock::now();
1472
Songchun Fanafaf6e92020-03-18 14:12:20 -07001473 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001474 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001475 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001476 LOG(INFO) << "incfs: Extracted " << libName
1477 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001478 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001479 continue;
1480 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001481
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001482 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1483 libFileId, libPath = std::move(targetLibPath),
1484 makeFileTs]() mutable {
1485 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001486 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001487
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001488 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001489 auto prepareJobTs = Clock::now();
1490 LOG(INFO) << "incfs: Processed " << libName << ": "
1491 << elapsedMcs(startFileTs, prepareJobTs)
1492 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1493 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001494 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001495 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001496
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001497 auto processedTs = Clock::now();
1498
1499 if (!jobQueue.empty()) {
1500 {
1501 std::lock_guard lock(mJobMutex);
1502 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001503 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001504 if (existingJobs.empty()) {
1505 existingJobs = std::move(jobQueue);
1506 } else {
1507 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1508 std::move_iterator(jobQueue.end()));
1509 }
1510 }
1511 }
1512 mJobCondition.notify_all();
1513 }
1514
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001515 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001516 auto end = Clock::now();
1517 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1518 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1519 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001520 << " make files: " << elapsedMcs(openZipTs, processedTs)
1521 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001522 }
1523
1524 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001525}
1526
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001527void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1528 ZipEntry& entry, const incfs::FileId& libFileId,
1529 std::string_view targetLibPath,
1530 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001531 if (!ifs) {
1532 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1533 return;
1534 }
1535
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001536 auto libName = path::basename(targetLibPath);
1537 auto startedTs = Clock::now();
1538
1539 // Write extracted data to new file
1540 // NOTE: don't zero-initialize memory, it may take a while for nothing
1541 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1542 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1543 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1544 return;
1545 }
1546
1547 auto extractFileTs = Clock::now();
1548
1549 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1550 if (!writeFd.ok()) {
1551 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1552 return;
1553 }
1554
1555 auto openFileTs = Clock::now();
1556 const int numBlocks =
1557 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1558 std::vector<IncFsDataBlock> instructions(numBlocks);
1559 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1560 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001561 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001562 instructions[i] = IncFsDataBlock{
1563 .fileFd = writeFd.get(),
1564 .pageIndex = static_cast<IncFsBlockIndex>(i),
1565 .compression = INCFS_COMPRESSION_KIND_NONE,
1566 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001567 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001568 .data = reinterpret_cast<const char*>(remainingData.data()),
1569 };
1570 remainingData = remainingData.subspan(blockSize);
1571 }
1572 auto prepareInstsTs = Clock::now();
1573
1574 size_t res = mIncFs->writeBlocks(instructions);
1575 if (res != instructions.size()) {
1576 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1577 return;
1578 }
1579
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001580 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001581 auto endFileTs = Clock::now();
1582 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1583 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1584 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1585 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1586 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1587 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1588 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1589 }
1590}
1591
1592bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001593 struct WaitPrinter {
1594 const Clock::time_point startTs = Clock::now();
1595 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001596 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001597 const auto endTs = Clock::now();
1598 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1599 << elapsedMcs(startTs, endTs) << "mcs";
1600 }
1601 }
1602 } waitPrinter;
1603
1604 MountId mount;
1605 {
1606 auto ifs = getIfs(storage);
1607 if (!ifs) {
1608 return true;
1609 }
1610 mount = ifs->mountId;
1611 }
1612
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001613 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001614 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001615 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001616 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001617 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001618 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001619}
1620
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001621bool IncrementalService::perfLoggingEnabled() {
1622 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1623 return enabled;
1624}
1625
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001626void IncrementalService::runJobProcessing() {
1627 for (;;) {
1628 std::unique_lock lock(mJobMutex);
1629 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1630 if (!mRunning) {
1631 return;
1632 }
1633
1634 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001635 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001636 auto queue = std::move(it->second);
1637 mJobQueue.erase(it);
1638 lock.unlock();
1639
1640 for (auto&& job : queue) {
1641 job();
1642 }
1643
1644 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001645 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001646 lock.unlock();
1647 mJobCondition.notify_all();
1648 }
1649}
1650
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001651void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001652 sp<IAppOpsCallback> listener;
1653 {
1654 std::unique_lock lock{mCallbacksLock};
1655 auto& cb = mCallbackRegistered[packageName];
1656 if (cb) {
1657 return;
1658 }
1659 cb = new AppOpsListener(*this, packageName);
1660 listener = cb;
1661 }
1662
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001663 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1664 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001665}
1666
1667bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1668 sp<IAppOpsCallback> listener;
1669 {
1670 std::unique_lock lock{mCallbacksLock};
1671 auto found = mCallbackRegistered.find(packageName);
1672 if (found == mCallbackRegistered.end()) {
1673 return false;
1674 }
1675 listener = found->second;
1676 mCallbackRegistered.erase(found);
1677 }
1678
1679 mAppOpsManager->stopWatchingMode(listener);
1680 return true;
1681}
1682
1683void IncrementalService::onAppOpChanged(const std::string& packageName) {
1684 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001685 return;
1686 }
1687
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001688 std::vector<IfsMountPtr> affected;
1689 {
1690 std::lock_guard l(mLock);
1691 affected.reserve(mMounts.size());
1692 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001693 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001694 affected.push_back(ifs);
1695 }
1696 }
1697 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001698 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001699 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001700 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001701}
1702
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001703IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1704 DataLoaderParamsParcel&& params,
1705 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001706 const DataLoaderStatusListener* statusListener,
1707 StorageHealthCheckParams&& healthCheckParams,
1708 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001709 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001710 : mService(service),
1711 mId(id),
1712 mParams(std::move(params)),
1713 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001714 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
1715 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001716 mHealthPath(std::move(healthPath)) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001717 // TODO(b/153874006): enable external health listener.
1718 mHealthListener = {};
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001719 healthStatusOk();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001720}
1721
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001722IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001723 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001724 cleanupResources();
1725 }
1726}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001727
1728void IncrementalService::DataLoaderStub::cleanupResources() {
1729 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001730
1731 auto now = Clock::now();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001732 std::unique_lock lock(mMutex);
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001733
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001734 unregisterFromPendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001735
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001736 mParams = {};
1737 mControl = {};
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001738 mStatusCondition.wait_until(lock, now + 60s, [this] {
1739 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1740 });
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001741 mStatusListener = {};
1742 mHealthListener = {};
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001743 mId = kInvalidStorageId;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001744}
1745
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001746sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1747 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001748 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001749 if (!status.isOk()) {
1750 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1751 return {};
1752 }
1753 if (!dataloader) {
1754 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1755 return {};
1756 }
1757 return dataloader;
1758}
1759
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001760bool IncrementalService::DataLoaderStub::requestCreate() {
1761 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1762}
1763
1764bool IncrementalService::DataLoaderStub::requestStart() {
1765 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1766}
1767
1768bool IncrementalService::DataLoaderStub::requestDestroy() {
1769 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1770}
1771
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001772bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001773 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001774 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001775 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001776 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001777 return fsmStep();
1778}
1779
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001780void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001781 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001782 mTargetStatus = status;
1783 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001784 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001785 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001786}
1787
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001788bool IncrementalService::DataLoaderStub::bind() {
1789 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001790 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001791 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001792 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001793 return false;
1794 }
1795 return true;
1796}
1797
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001798bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001799 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001800 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001801 return false;
1802 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001803 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001804 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001805 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001806 return false;
1807 }
1808 return true;
1809}
1810
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001811bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001812 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001813 if (!dataloader) {
1814 return false;
1815 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001816 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001817 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001818 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001819 return false;
1820 }
1821 return true;
1822}
1823
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001824bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001825 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001826}
1827
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001828bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001829 if (!isValid()) {
1830 return false;
1831 }
1832
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001833 int currentStatus;
1834 int targetStatus;
1835 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001836 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001837 currentStatus = mCurrentStatus;
1838 targetStatus = mTargetStatus;
1839 }
1840
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001841 LOG(DEBUG) << "fsmStep: " << mId << ": " << currentStatus << " -> " << targetStatus;
1842
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001843 if (currentStatus == targetStatus) {
1844 return true;
1845 }
1846
1847 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001848 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
1849 // Do nothing, this is a reset state.
1850 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001851 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1852 return destroy();
1853 }
1854 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1855 switch (currentStatus) {
1856 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1857 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1858 return start();
1859 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001860 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001861 }
1862 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1863 switch (currentStatus) {
1864 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001865 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001866 return bind();
1867 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001868 return create();
1869 }
1870 break;
1871 default:
1872 LOG(ERROR) << "Invalid target status: " << targetStatus
1873 << ", current status: " << currentStatus;
1874 break;
1875 }
1876 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001877}
1878
1879binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001880 if (!isValid()) {
1881 return binder::Status::
1882 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
1883 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001884 if (id() != mountId) {
1885 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001886 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
1887 }
1888
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001889 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001890 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001891 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001892 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001893 if (mCurrentStatus == newStatus) {
1894 return binder::Status::ok();
1895 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001896
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001897 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001898 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001899 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001900
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001901 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001902
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001903 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001904 // For unavailable, unbind from DataLoader to ensure proper re-commit.
1905 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001906 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001907 }
1908
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001909 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001910 << newStatus << " (target " << targetStatus << ")";
1911
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001912 if (listener) {
1913 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001914 }
1915
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001916 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08001917
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07001918 mStatusCondition.notify_all();
1919
Songchun Fan3c82a302019-11-29 14:23:45 -08001920 return binder::Status::ok();
1921}
1922
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001923void IncrementalService::DataLoaderStub::healthStatusOk() {
1924 LOG(DEBUG) << "healthStatusOk: " << mId;
1925 std::unique_lock lock(mMutex);
1926 registerForPendingReads();
1927}
1928
1929void IncrementalService::DataLoaderStub::healthStatusReadsPending() {
1930 LOG(DEBUG) << "healthStatusReadsPending: " << mId;
1931 requestStart();
1932
1933 std::unique_lock lock(mMutex);
1934 unregisterFromPendingReads();
1935}
1936
1937void IncrementalService::DataLoaderStub::healthStatusBlocked() {}
1938
1939void IncrementalService::DataLoaderStub::healthStatusUnhealthy() {}
1940
1941void IncrementalService::DataLoaderStub::registerForPendingReads() {
1942 auto pendingReadsFd = mHealthControl.pendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001943 if (pendingReadsFd < 0) {
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001944 mHealthControl = mService.mIncFs->openMount(mHealthPath);
1945 pendingReadsFd = mHealthControl.pendingReads();
1946 if (pendingReadsFd < 0) {
1947 LOG(ERROR) << "Failed to open health control for: " << mId << ", path: " << mHealthPath
1948 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
1949 << mHealthControl.logs() << ")";
1950 return;
1951 }
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001952 }
1953
1954 mService.mLooper->addFd(
1955 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
1956 [](int, int, void* data) -> int {
1957 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001958 return self->onPendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001959 },
1960 this);
1961 mService.mLooper->wake();
1962}
1963
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001964void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001965 const auto pendingReadsFd = mHealthControl.pendingReads();
1966 if (pendingReadsFd < 0) {
1967 return;
1968 }
1969
1970 mService.mLooper->removeFd(pendingReadsFd);
1971 mService.mLooper->wake();
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001972
1973 mHealthControl = {};
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001974}
1975
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001976int IncrementalService::DataLoaderStub::onPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001977 if (!mService.mRunning.load(std::memory_order_relaxed)) {
1978 return 0;
1979 }
1980
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001981 healthStatusReadsPending();
1982 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001983}
1984
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001985void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001986 dprintf(fd, " dataLoader: {\n");
1987 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
1988 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
1989 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001990 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
1991 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001992 dprintf(fd, " dataLoaderParams: {\n");
1993 dprintf(fd, " type: %s\n", toString(params.type).c_str());
1994 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
1995 dprintf(fd, " className: %s\n", params.className.c_str());
1996 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
1997 dprintf(fd, " }\n");
1998 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001999}
2000
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002001void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2002 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002003}
2004
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002005binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2006 bool enableReadLogs, int32_t* _aidl_return) {
2007 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2008 return binder::Status::ok();
2009}
2010
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002011FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2012 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2013}
2014
Songchun Fan3c82a302019-11-29 14:23:45 -08002015} // namespace android::incremental