blob: b03d1eae8ca096abdd7813e22673b442ad26e982 [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,
1382 std::string_view abi) {
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
1426 auto startFileTs = Clock::now();
1427
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001428 const auto libName = path::basename(fileName);
Yurii Zubrytskyi510037b2020-04-22 15:46:21 -07001429 auto targetLibPath = path::join(libDirRelativePath, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001430 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001431 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001432 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001433 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001434 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1435 << "; skipping extraction, spent "
1436 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1437 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001438 continue;
1439 }
1440
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001441 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001442 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001443 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001444 .signature = {},
1445 // Metadata of the new lib file is its relative path
1446 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1447 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001448 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001449 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1450 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001451 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001452 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001453 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001454 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001455
1456 auto makeFileTs = Clock::now();
1457
Songchun Fanafaf6e92020-03-18 14:12:20 -07001458 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001459 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001460 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001461 LOG(INFO) << "incfs: Extracted " << libName
1462 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001463 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001464 continue;
1465 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001466
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001467 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1468 libFileId, libPath = std::move(targetLibPath),
1469 makeFileTs]() mutable {
1470 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001471 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001472
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001473 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001474 auto prepareJobTs = Clock::now();
1475 LOG(INFO) << "incfs: Processed " << libName << ": "
1476 << elapsedMcs(startFileTs, prepareJobTs)
1477 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1478 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001479 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001480 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001481
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001482 auto processedTs = Clock::now();
1483
1484 if (!jobQueue.empty()) {
1485 {
1486 std::lock_guard lock(mJobMutex);
1487 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001488 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001489 if (existingJobs.empty()) {
1490 existingJobs = std::move(jobQueue);
1491 } else {
1492 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1493 std::move_iterator(jobQueue.end()));
1494 }
1495 }
1496 }
1497 mJobCondition.notify_all();
1498 }
1499
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001500 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001501 auto end = Clock::now();
1502 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1503 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1504 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001505 << " make files: " << elapsedMcs(openZipTs, processedTs)
1506 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001507 }
1508
1509 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001510}
1511
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001512void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1513 ZipEntry& entry, const incfs::FileId& libFileId,
1514 std::string_view targetLibPath,
1515 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001516 if (!ifs) {
1517 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1518 return;
1519 }
1520
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001521 auto libName = path::basename(targetLibPath);
1522 auto startedTs = Clock::now();
1523
1524 // Write extracted data to new file
1525 // NOTE: don't zero-initialize memory, it may take a while for nothing
1526 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1527 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1528 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1529 return;
1530 }
1531
1532 auto extractFileTs = Clock::now();
1533
1534 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1535 if (!writeFd.ok()) {
1536 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1537 return;
1538 }
1539
1540 auto openFileTs = Clock::now();
1541 const int numBlocks =
1542 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1543 std::vector<IncFsDataBlock> instructions(numBlocks);
1544 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1545 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001546 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001547 instructions[i] = IncFsDataBlock{
1548 .fileFd = writeFd.get(),
1549 .pageIndex = static_cast<IncFsBlockIndex>(i),
1550 .compression = INCFS_COMPRESSION_KIND_NONE,
1551 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001552 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001553 .data = reinterpret_cast<const char*>(remainingData.data()),
1554 };
1555 remainingData = remainingData.subspan(blockSize);
1556 }
1557 auto prepareInstsTs = Clock::now();
1558
1559 size_t res = mIncFs->writeBlocks(instructions);
1560 if (res != instructions.size()) {
1561 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1562 return;
1563 }
1564
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001565 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001566 auto endFileTs = Clock::now();
1567 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1568 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1569 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1570 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1571 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1572 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1573 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1574 }
1575}
1576
1577bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001578 struct WaitPrinter {
1579 const Clock::time_point startTs = Clock::now();
1580 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001581 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001582 const auto endTs = Clock::now();
1583 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1584 << elapsedMcs(startTs, endTs) << "mcs";
1585 }
1586 }
1587 } waitPrinter;
1588
1589 MountId mount;
1590 {
1591 auto ifs = getIfs(storage);
1592 if (!ifs) {
1593 return true;
1594 }
1595 mount = ifs->mountId;
1596 }
1597
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001598 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001599 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001600 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001601 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001602 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001603 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001604}
1605
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001606bool IncrementalService::perfLoggingEnabled() {
1607 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1608 return enabled;
1609}
1610
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001611void IncrementalService::runJobProcessing() {
1612 for (;;) {
1613 std::unique_lock lock(mJobMutex);
1614 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1615 if (!mRunning) {
1616 return;
1617 }
1618
1619 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001620 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001621 auto queue = std::move(it->second);
1622 mJobQueue.erase(it);
1623 lock.unlock();
1624
1625 for (auto&& job : queue) {
1626 job();
1627 }
1628
1629 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001630 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001631 lock.unlock();
1632 mJobCondition.notify_all();
1633 }
1634}
1635
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001636void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001637 sp<IAppOpsCallback> listener;
1638 {
1639 std::unique_lock lock{mCallbacksLock};
1640 auto& cb = mCallbackRegistered[packageName];
1641 if (cb) {
1642 return;
1643 }
1644 cb = new AppOpsListener(*this, packageName);
1645 listener = cb;
1646 }
1647
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001648 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1649 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001650}
1651
1652bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1653 sp<IAppOpsCallback> listener;
1654 {
1655 std::unique_lock lock{mCallbacksLock};
1656 auto found = mCallbackRegistered.find(packageName);
1657 if (found == mCallbackRegistered.end()) {
1658 return false;
1659 }
1660 listener = found->second;
1661 mCallbackRegistered.erase(found);
1662 }
1663
1664 mAppOpsManager->stopWatchingMode(listener);
1665 return true;
1666}
1667
1668void IncrementalService::onAppOpChanged(const std::string& packageName) {
1669 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001670 return;
1671 }
1672
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001673 std::vector<IfsMountPtr> affected;
1674 {
1675 std::lock_guard l(mLock);
1676 affected.reserve(mMounts.size());
1677 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001678 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001679 affected.push_back(ifs);
1680 }
1681 }
1682 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001683 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001684 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001685 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001686}
1687
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001688IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1689 DataLoaderParamsParcel&& params,
1690 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001691 const DataLoaderStatusListener* statusListener,
1692 StorageHealthCheckParams&& healthCheckParams,
1693 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001694 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001695 : mService(service),
1696 mId(id),
1697 mParams(std::move(params)),
1698 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001699 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
1700 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001701 mHealthPath(std::move(healthPath)) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001702 // TODO(b/153874006): enable external health listener.
1703 mHealthListener = {};
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001704 healthStatusOk();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001705}
1706
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001707IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001708 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001709 cleanupResources();
1710 }
1711}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001712
1713void IncrementalService::DataLoaderStub::cleanupResources() {
1714 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001715
1716 auto now = Clock::now();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001717 std::unique_lock lock(mMutex);
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001718
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001719 unregisterFromPendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001720
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001721 mParams = {};
1722 mControl = {};
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001723 mStatusCondition.wait_until(lock, now + 60s, [this] {
1724 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1725 });
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001726 mStatusListener = {};
1727 mHealthListener = {};
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001728 mId = kInvalidStorageId;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001729}
1730
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001731sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1732 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001733 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001734 if (!status.isOk()) {
1735 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1736 return {};
1737 }
1738 if (!dataloader) {
1739 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1740 return {};
1741 }
1742 return dataloader;
1743}
1744
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001745bool IncrementalService::DataLoaderStub::requestCreate() {
1746 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1747}
1748
1749bool IncrementalService::DataLoaderStub::requestStart() {
1750 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1751}
1752
1753bool IncrementalService::DataLoaderStub::requestDestroy() {
1754 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1755}
1756
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001757bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001758 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001759 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001760 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001761 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001762 return fsmStep();
1763}
1764
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001765void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001766 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001767 mTargetStatus = status;
1768 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001769 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001770 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001771}
1772
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001773bool IncrementalService::DataLoaderStub::bind() {
1774 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001775 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001776 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001777 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001778 return false;
1779 }
1780 return true;
1781}
1782
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001783bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001784 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001785 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001786 return false;
1787 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001788 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001789 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001790 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001791 return false;
1792 }
1793 return true;
1794}
1795
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001796bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001797 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001798 if (!dataloader) {
1799 return false;
1800 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001801 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001802 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001803 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001804 return false;
1805 }
1806 return true;
1807}
1808
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001809bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001810 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001811}
1812
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001813bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001814 if (!isValid()) {
1815 return false;
1816 }
1817
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001818 int currentStatus;
1819 int targetStatus;
1820 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001821 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001822 currentStatus = mCurrentStatus;
1823 targetStatus = mTargetStatus;
1824 }
1825
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001826 LOG(DEBUG) << "fsmStep: " << mId << ": " << currentStatus << " -> " << targetStatus;
1827
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001828 if (currentStatus == targetStatus) {
1829 return true;
1830 }
1831
1832 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001833 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
1834 // Do nothing, this is a reset state.
1835 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001836 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1837 return destroy();
1838 }
1839 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1840 switch (currentStatus) {
1841 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1842 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1843 return start();
1844 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001845 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001846 }
1847 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1848 switch (currentStatus) {
1849 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001850 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001851 return bind();
1852 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001853 return create();
1854 }
1855 break;
1856 default:
1857 LOG(ERROR) << "Invalid target status: " << targetStatus
1858 << ", current status: " << currentStatus;
1859 break;
1860 }
1861 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001862}
1863
1864binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001865 if (!isValid()) {
1866 return binder::Status::
1867 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
1868 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001869 if (id() != mountId) {
1870 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001871 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
1872 }
1873
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001874 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001875 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001876 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001877 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001878 if (mCurrentStatus == newStatus) {
1879 return binder::Status::ok();
1880 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001881
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001882 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001883 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001884 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001885
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001886 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001887
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001888 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001889 // For unavailable, unbind from DataLoader to ensure proper re-commit.
1890 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001891 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001892 }
1893
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001894 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001895 << newStatus << " (target " << targetStatus << ")";
1896
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001897 if (listener) {
1898 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001899 }
1900
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001901 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08001902
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07001903 mStatusCondition.notify_all();
1904
Songchun Fan3c82a302019-11-29 14:23:45 -08001905 return binder::Status::ok();
1906}
1907
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001908void IncrementalService::DataLoaderStub::healthStatusOk() {
1909 LOG(DEBUG) << "healthStatusOk: " << mId;
1910 std::unique_lock lock(mMutex);
1911 registerForPendingReads();
1912}
1913
1914void IncrementalService::DataLoaderStub::healthStatusReadsPending() {
1915 LOG(DEBUG) << "healthStatusReadsPending: " << mId;
1916 requestStart();
1917
1918 std::unique_lock lock(mMutex);
1919 unregisterFromPendingReads();
1920}
1921
1922void IncrementalService::DataLoaderStub::healthStatusBlocked() {}
1923
1924void IncrementalService::DataLoaderStub::healthStatusUnhealthy() {}
1925
1926void IncrementalService::DataLoaderStub::registerForPendingReads() {
1927 auto pendingReadsFd = mHealthControl.pendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001928 if (pendingReadsFd < 0) {
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001929 mHealthControl = mService.mIncFs->openMount(mHealthPath);
1930 pendingReadsFd = mHealthControl.pendingReads();
1931 if (pendingReadsFd < 0) {
1932 LOG(ERROR) << "Failed to open health control for: " << mId << ", path: " << mHealthPath
1933 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
1934 << mHealthControl.logs() << ")";
1935 return;
1936 }
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001937 }
1938
1939 mService.mLooper->addFd(
1940 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
1941 [](int, int, void* data) -> int {
1942 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001943 return self->onPendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001944 },
1945 this);
1946 mService.mLooper->wake();
1947}
1948
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001949void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001950 const auto pendingReadsFd = mHealthControl.pendingReads();
1951 if (pendingReadsFd < 0) {
1952 return;
1953 }
1954
1955 mService.mLooper->removeFd(pendingReadsFd);
1956 mService.mLooper->wake();
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001957
1958 mHealthControl = {};
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001959}
1960
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001961int IncrementalService::DataLoaderStub::onPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001962 if (!mService.mRunning.load(std::memory_order_relaxed)) {
1963 return 0;
1964 }
1965
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001966 healthStatusReadsPending();
1967 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001968}
1969
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001970void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001971 dprintf(fd, " dataLoader: {\n");
1972 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
1973 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
1974 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001975 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
1976 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001977 dprintf(fd, " dataLoaderParams: {\n");
1978 dprintf(fd, " type: %s\n", toString(params.type).c_str());
1979 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
1980 dprintf(fd, " className: %s\n", params.className.c_str());
1981 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
1982 dprintf(fd, " }\n");
1983 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001984}
1985
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001986void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1987 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001988}
1989
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001990binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1991 bool enableReadLogs, int32_t* _aidl_return) {
1992 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1993 return binder::Status::ok();
1994}
1995
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001996FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
1997 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
1998}
1999
Songchun Fan3c82a302019-11-29 14:23:45 -08002000} // namespace android::incremental