blob: 78439dba27246c908a5564c69e65fe39aa872672 [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;
Songchun Fan3c82a302019-11-29 14:23:45 -080066};
67
68static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070069 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080070 return c;
71}
72
73template <base::LogSeverity level = base::ERROR>
74bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
75 auto cstr = path::c_str(name);
76 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080077 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080078 PLOG(level) << "Can't create directory '" << name << '\'';
79 return false;
80 }
81 struct stat st;
82 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
83 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
84 return false;
85 }
86 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080087 if (::chmod(cstr, mode)) {
88 PLOG(level) << "Changing permission failed for '" << name << '\'';
89 return false;
90 }
91
Songchun Fan3c82a302019-11-29 14:23:45 -080092 return true;
93}
94
95static std::string toMountKey(std::string_view path) {
96 if (path.empty()) {
97 return "@none";
98 }
99 if (path == "/"sv) {
100 return "@root";
101 }
102 if (path::isAbsolute(path)) {
103 path.remove_prefix(1);
104 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700105 if (path.size() > 16) {
106 path = path.substr(0, 16);
107 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800108 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700109 std::replace_if(
110 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
111 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800112}
113
114static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
115 std::string_view path) {
116 auto mountKey = toMountKey(path);
117 const auto prefixSize = mountKey.size();
118 for (int counter = 0; counter < 1000;
119 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
120 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800121 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800122 return {mountKey, mountRoot};
123 }
124 }
125 return {};
126}
127
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700128template <class Map>
129typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
130 const auto nextIt = map.upper_bound(path);
131 if (nextIt == map.begin()) {
132 return map.end();
133 }
134 const auto suspectIt = std::prev(nextIt);
135 if (!path::startsWith(path, suspectIt->first)) {
136 return map.end();
137 }
138 return suspectIt;
139}
140
141static base::unique_fd dup(base::borrowed_fd fd) {
142 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
143 return base::unique_fd(res);
144}
145
Songchun Fan3c82a302019-11-29 14:23:45 -0800146template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700147static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800148 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800149 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800150 ProtoMessage message;
151 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
152}
153
154static bool isValidMountTarget(std::string_view path) {
155 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
156}
157
158std::string makeBindMdName() {
159 static constexpr auto uuidStringSize = 36;
160
161 uuid_t guid;
162 uuid_generate(guid);
163
164 std::string name;
165 const auto prefixSize = constants().mountpointMdPrefix.size();
166 name.reserve(prefixSize + uuidStringSize);
167
168 name = constants().mountpointMdPrefix;
169 name.resize(prefixSize + uuidStringSize);
170 uuid_unparse(guid, name.data() + prefixSize);
171
172 return name;
173}
174} // namespace
175
176IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700177 if (dataLoaderStub) {
Alex Buynytskyy9a545792020-04-17 15:34:47 -0700178 dataLoaderStub->cleanupResources();
179 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700180 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700181 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800182 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
183 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700184 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800185 incrementalService.mVold->unmountIncFs(target);
186 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700187 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800188 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
189 cleanupFilesystem(root);
190}
191
192auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800193 std::string name;
194 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
195 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
196 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800197 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
198 constants().storagePrefix.data(), id, no);
199 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800200 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800201 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800202 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
203 } else if (err != EEXIST) {
204 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
205 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800206 }
207 }
208 nextStorageDirNo = 0;
209 return storages.end();
210}
211
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700212template <class Func>
213static auto makeCleanup(Func&& f) {
214 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700215 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700216 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
217}
218
219static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
220 return {::opendir(dir), ::closedir};
221}
222
223static auto openDir(std::string_view dir) {
224 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800225}
226
227static int rmDirContent(const char* path) {
228 auto dir = openDir(path);
229 if (!dir) {
230 return -EINVAL;
231 }
232 while (auto entry = ::readdir(dir.get())) {
233 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
234 continue;
235 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700236 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800237 if (entry->d_type == DT_DIR) {
238 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
239 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
240 return err;
241 }
242 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
243 PLOG(WARNING) << "Failed to rmdir " << fullPath;
244 return err;
245 }
246 } else {
247 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
248 PLOG(WARNING) << "Failed to delete " << fullPath;
249 return err;
250 }
251 }
252 }
253 return 0;
254}
255
Songchun Fan3c82a302019-11-29 14:23:45 -0800256void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800257 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800258 ::rmdir(path::join(root, constants().backing).c_str());
259 ::rmdir(path::join(root, constants().mount).c_str());
260 ::rmdir(path::c_str(root));
261}
262
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800263IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800264 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800265 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800266 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700267 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700268 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700269 mLooper(sm.getLooper()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800270 mIncrementalDir(rootDir) {
271 if (!mVold) {
272 LOG(FATAL) << "Vold service is unavailable";
273 }
Songchun Fan68645c42020-02-27 15:57:35 -0800274 if (!mDataLoaderManager) {
275 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800276 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700277 if (!mAppOpsManager) {
278 LOG(FATAL) << "AppOpsManager is unavailable";
279 }
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700280 if (!mJni) {
281 LOG(FATAL) << "JNI is unavailable";
282 }
283 if (!mLooper) {
284 LOG(FATAL) << "Looper is unavailable";
285 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700286
287 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700288 mJobProcessor = std::thread([this]() {
289 mJni->initializeForCurrentThread();
290 runJobProcessing();
291 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700292 mCmdLooperThread = std::thread([this]() {
293 mJni->initializeForCurrentThread();
294 runCmdLooper();
295 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700296
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700297 const auto mountedRootNames = adoptMountedInstances();
298 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800299}
300
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700301IncrementalService::~IncrementalService() {
302 {
303 std::lock_guard lock(mJobMutex);
304 mRunning = false;
305 }
306 mJobCondition.notify_all();
307 mJobProcessor.join();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700308 mCmdLooperThread.join();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700309}
Songchun Fan3c82a302019-11-29 14:23:45 -0800310
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700311static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800312 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800313 case IncrementalService::BindKind::Temporary:
314 return "Temporary";
315 case IncrementalService::BindKind::Permanent:
316 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800317 }
318}
319
320void IncrementalService::onDump(int fd) {
321 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
322 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
323
324 std::unique_lock l(mLock);
325
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700326 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800327 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700328 const IncFsMount& mnt = *ifs;
329 dprintf(fd, " [%d]: {\n", id);
330 if (id != mnt.mountId) {
331 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
332 } else {
333 dprintf(fd, " mountId: %d\n", mnt.mountId);
334 dprintf(fd, " root: %s\n", mnt.root.c_str());
335 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
336 if (mnt.dataLoaderStub) {
337 mnt.dataLoaderStub->onDump(fd);
338 } else {
339 dprintf(fd, " dataLoader: null\n");
340 }
341 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
342 for (auto&& [storageId, storage] : mnt.storages) {
343 dprintf(fd, " [%d] -> [%s]\n", storageId, storage.name.c_str());
344 }
345 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800346
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700347 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
348 for (auto&& [target, bind] : mnt.bindPoints) {
349 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
350 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
351 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
352 dprintf(fd, " kind: %s\n", toString(bind.kind));
353 }
354 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800355 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700356 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800357 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700358 dprintf(fd, "}\n");
359 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800360 for (auto&& [target, mountPairIt] : mBindsByPath) {
361 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700362 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
363 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
364 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
365 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800366 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700367 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800368}
369
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700370void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800371 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700372 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800373 }
374
375 std::vector<IfsMountPtr> mounts;
376 {
377 std::lock_guard l(mLock);
378 mounts.reserve(mMounts.size());
379 for (auto&& [id, ifs] : mMounts) {
380 if (ifs->mountId == id) {
381 mounts.push_back(ifs);
382 }
383 }
384 }
385
Alex Buynytskyy69941662020-04-11 21:40:37 -0700386 if (mounts.empty()) {
387 return;
388 }
389
Songchun Fan3c82a302019-11-29 14:23:45 -0800390 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700391 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800392 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700393 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800394 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800395 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800396}
397
398auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
399 for (;;) {
400 if (mNextId == kMaxStorageId) {
401 mNextId = 0;
402 }
403 auto id = ++mNextId;
404 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
405 if (inserted) {
406 return it;
407 }
408 }
409}
410
Songchun Fan1124fd32020-02-10 12:49:41 -0800411StorageId IncrementalService::createStorage(
412 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
413 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800414 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
415 if (!path::isAbsolute(mountPoint)) {
416 LOG(ERROR) << "path is not absolute: " << mountPoint;
417 return kInvalidStorageId;
418 }
419
420 auto mountNorm = path::normalize(mountPoint);
421 {
422 const auto id = findStorageId(mountNorm);
423 if (id != kInvalidStorageId) {
424 if (options & CreateOptions::OpenExisting) {
425 LOG(INFO) << "Opened existing storage " << id;
426 return id;
427 }
428 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
429 return kInvalidStorageId;
430 }
431 }
432
433 if (!(options & CreateOptions::CreateNew)) {
434 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
435 return kInvalidStorageId;
436 }
437
438 if (!path::isEmptyDir(mountNorm)) {
439 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
440 return kInvalidStorageId;
441 }
442 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
443 if (mountRoot.empty()) {
444 LOG(ERROR) << "Bad mount point";
445 return kInvalidStorageId;
446 }
447 // Make sure the code removes all crap it may create while still failing.
448 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
449 auto firstCleanupOnFailure =
450 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
451
452 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800453 const auto backing = path::join(mountRoot, constants().backing);
454 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800455 return kInvalidStorageId;
456 }
457
Songchun Fan3c82a302019-11-29 14:23:45 -0800458 IncFsMount::Control control;
459 {
460 std::lock_guard l(mMountOperationLock);
461 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800462
463 if (auto err = rmDirContent(backing.c_str())) {
464 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
465 return kInvalidStorageId;
466 }
467 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
468 return kInvalidStorageId;
469 }
470 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800471 if (!status.isOk()) {
472 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
473 return kInvalidStorageId;
474 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800475 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
476 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800477 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
478 return kInvalidStorageId;
479 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800480 int cmd = controlParcel.cmd.release().release();
481 int pendingReads = controlParcel.pendingReads.release().release();
482 int logs = controlParcel.log.release().release();
483 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800484 }
485
486 std::unique_lock l(mLock);
487 const auto mountIt = getStorageSlotLocked();
488 const auto mountId = mountIt->first;
489 l.unlock();
490
491 auto ifs =
492 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
493 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
494 // is the removal of the |ifs|.
495 firstCleanupOnFailure.release();
496
497 auto secondCleanup = [this, &l](auto itPtr) {
498 if (!l.owns_lock()) {
499 l.lock();
500 }
501 mMounts.erase(*itPtr);
502 };
503 auto secondCleanupOnFailure =
504 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
505
506 const auto storageIt = ifs->makeStorage(ifs->mountId);
507 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800508 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800509 return kInvalidStorageId;
510 }
511
512 {
513 metadata::Mount m;
514 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700515 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700516 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
517 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
518 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800519 const auto metadata = m.SerializeAsString();
520 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800521 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800522 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800523 if (auto err =
524 mIncFs->makeFile(ifs->control,
525 path::join(ifs->root, constants().mount,
526 constants().infoMdName),
527 0777, idFromMetadata(metadata),
528 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800529 LOG(ERROR) << "Saving mount metadata failed: " << -err;
530 return kInvalidStorageId;
531 }
532 }
533
534 const auto bk =
535 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800536 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
537 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800538 err < 0) {
539 LOG(ERROR) << "adding bind mount failed: " << -err;
540 return kInvalidStorageId;
541 }
542
543 // Done here as well, all data structures are in good state.
544 secondCleanupOnFailure.release();
545
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700546 auto dataLoaderStub =
547 prepareDataLoader(*ifs, std::move(dataLoaderParams), &dataLoaderStatusListener);
548 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800549
550 mountIt->second = std::move(ifs);
551 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700552
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700553 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700554 // failed to create data loader
555 LOG(ERROR) << "initializeDataLoader() failed";
556 deleteStorage(dataLoaderStub->id());
557 return kInvalidStorageId;
558 }
559
Songchun Fan3c82a302019-11-29 14:23:45 -0800560 LOG(INFO) << "created storage " << mountId;
561 return mountId;
562}
563
564StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
565 StorageId linkedStorage,
566 IncrementalService::CreateOptions options) {
567 if (!isValidMountTarget(mountPoint)) {
568 LOG(ERROR) << "Mount point is invalid or missing";
569 return kInvalidStorageId;
570 }
571
572 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700573 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800574 if (!ifs) {
575 LOG(ERROR) << "Ifs unavailable";
576 return kInvalidStorageId;
577 }
578
579 const auto mountIt = getStorageSlotLocked();
580 const auto storageId = mountIt->first;
581 const auto storageIt = ifs->makeStorage(storageId);
582 if (storageIt == ifs->storages.end()) {
583 LOG(ERROR) << "Can't create a new storage";
584 mMounts.erase(mountIt);
585 return kInvalidStorageId;
586 }
587
588 l.unlock();
589
590 const auto bk =
591 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800592 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
593 std::string(storageIt->second.name), path::normalize(mountPoint),
594 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800595 err < 0) {
596 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700597 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
598 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800599 return kInvalidStorageId;
600 }
601
602 mountIt->second = ifs;
603 return storageId;
604}
605
606IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
607 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700608 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800609}
610
611StorageId IncrementalService::findStorageId(std::string_view path) const {
612 std::lock_guard l(mLock);
613 auto it = findStorageLocked(path);
614 if (it == mBindsByPath.end()) {
615 return kInvalidStorageId;
616 }
617 return it->second->second.storage;
618}
619
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700620int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
621 const auto ifs = getIfs(storageId);
622 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700623 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700624 return -EINVAL;
625 }
626
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700627 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700628 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700629 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
630 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700631 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700632 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700633 return fromBinderStatus(status);
634 }
635 }
636
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700637 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
638 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
639 return fromBinderStatus(status);
640 }
641
642 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700643 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700644 }
645
646 return 0;
647}
648
649binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700650 os::incremental::IncrementalFileSystemControlParcel control;
651 control.cmd.reset(dup(ifs.control.cmd()));
652 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700653 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700654 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700655 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700656 }
657
658 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700659 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700660}
661
Songchun Fan3c82a302019-11-29 14:23:45 -0800662void IncrementalService::deleteStorage(StorageId storageId) {
663 const auto ifs = getIfs(storageId);
664 if (!ifs) {
665 return;
666 }
667 deleteStorage(*ifs);
668}
669
670void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
671 std::unique_lock l(ifs.lock);
672 deleteStorageLocked(ifs, std::move(l));
673}
674
675void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
676 std::unique_lock<std::mutex>&& ifsLock) {
677 const auto storages = std::move(ifs.storages);
678 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
679 const auto bindPoints = ifs.bindPoints;
680 ifsLock.unlock();
681
682 std::lock_guard l(mLock);
683 for (auto&& [id, _] : storages) {
684 if (id != ifs.mountId) {
685 mMounts.erase(id);
686 }
687 }
688 for (auto&& [path, _] : bindPoints) {
689 mBindsByPath.erase(path);
690 }
691 mMounts.erase(ifs.mountId);
692}
693
694StorageId IncrementalService::openStorage(std::string_view pathInMount) {
695 if (!path::isAbsolute(pathInMount)) {
696 return kInvalidStorageId;
697 }
698
699 return findStorageId(path::normalize(pathInMount));
700}
701
Songchun Fan3c82a302019-11-29 14:23:45 -0800702IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
703 std::lock_guard l(mLock);
704 return getIfsLocked(storage);
705}
706
707const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
708 auto it = mMounts.find(storage);
709 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700710 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700711 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800712 }
713 return it->second;
714}
715
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800716int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
717 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800718 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700719 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800720 return -EINVAL;
721 }
722
723 const auto ifs = getIfs(storage);
724 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700725 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800726 return -EINVAL;
727 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800728
Songchun Fan3c82a302019-11-29 14:23:45 -0800729 std::unique_lock l(ifs->lock);
730 const auto storageInfo = ifs->storages.find(storage);
731 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700732 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800733 return -EINVAL;
734 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700735 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700736 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700737 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700738 return -EINVAL;
739 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800740 l.unlock();
741 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800742 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
743 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800744}
745
746int IncrementalService::unbind(StorageId storage, std::string_view target) {
747 if (!path::isAbsolute(target)) {
748 return -EINVAL;
749 }
750
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700751 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800752
753 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
754 // otherwise there's a chance to unmount something completely unrelated
755 const auto norm = path::normalize(target);
756 std::unique_lock l(mLock);
757 const auto storageIt = mBindsByPath.find(norm);
758 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
759 return -EINVAL;
760 }
761 const auto bindIt = storageIt->second;
762 const auto storageId = bindIt->second.storage;
763 const auto ifs = getIfsLocked(storageId);
764 if (!ifs) {
765 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
766 << " is missing";
767 return -EFAULT;
768 }
769 mBindsByPath.erase(storageIt);
770 l.unlock();
771
772 mVold->unmountIncFs(bindIt->first);
773 std::unique_lock l2(ifs->lock);
774 if (ifs->bindPoints.size() <= 1) {
775 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700776 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800777 } else {
778 const std::string savedFile = std::move(bindIt->second.savedFilename);
779 ifs->bindPoints.erase(bindIt);
780 l2.unlock();
781 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800782 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800783 }
784 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700785
Songchun Fan3c82a302019-11-29 14:23:45 -0800786 return 0;
787}
788
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700789std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700790 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700791 std::string_view path) const {
792 if (!path::isAbsolute(path)) {
793 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700794 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700795 auto normPath = path::normalize(path);
796 if (path::startsWith(normPath, storageIt->second.name)) {
797 return normPath;
798 }
799 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700800 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
801 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700802 return {};
803 }
804 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700805}
806
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700807std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700808 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700809 std::unique_lock l(ifs.lock);
810 const auto storageInfo = ifs.storages.find(storage);
811 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800812 return {};
813 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700814 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800815}
816
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800817int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
818 incfs::NewFileParams params) {
819 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700820 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800821 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700822 LOG(ERROR) << "Internal error: storageId " << storage
823 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800824 return -EINVAL;
825 }
826 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800827 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700828 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800829 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800830 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800831 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800832 }
833 return -EINVAL;
834}
835
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800836int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800837 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700838 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800839 if (normPath.empty()) {
840 return -EINVAL;
841 }
842 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800843 }
844 return -EINVAL;
845}
846
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800847int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800848 const auto ifs = getIfs(storageId);
849 if (!ifs) {
850 return -EINVAL;
851 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700852 return makeDirs(*ifs, storageId, path, mode);
853}
854
855int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
856 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800857 std::string normPath = normalizePathToStorage(ifs, storageId, path);
858 if (normPath.empty()) {
859 return -EINVAL;
860 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700861 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800862}
863
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800864int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
865 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700866 std::unique_lock l(mLock);
867 auto ifsSrc = getIfsLocked(sourceStorageId);
868 if (!ifsSrc) {
869 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800870 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700871 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
872 return -EINVAL;
873 }
874 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700875 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
876 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700877 if (normOldPath.empty() || normNewPath.empty()) {
878 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
879 return -EINVAL;
880 }
881 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800882}
883
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800884int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800885 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700886 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800887 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800888 }
889 return -EINVAL;
890}
891
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800892int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
893 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800894 std::string&& target, BindKind kind,
895 std::unique_lock<std::mutex>& mainLock) {
896 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700897 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800898 return -EINVAL;
899 }
900
901 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700902 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800903 if (kind != BindKind::Temporary) {
904 metadata::BindPoint bp;
905 bp.set_storage_id(storage);
906 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800907 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800908 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800909 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800910 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800911 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700912 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
913 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
914 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800915 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700916 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800917 return int(node);
918 }
919 }
920
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700921 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
922 std::move(target), kind, mainLock);
923 if (res) {
924 mIncFs->unlink(ifs.control, metadataFullPath);
925 }
926 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800927}
928
929int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800930 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800931 std::string&& target, BindKind kind,
932 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800933 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800934 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800935 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800936 if (!status.isOk()) {
937 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
938 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
939 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
940 : status.serviceSpecificErrorCode() == 0
941 ? -EFAULT
942 : status.serviceSpecificErrorCode()
943 : -EIO;
944 }
945 }
946
947 if (!mainLock.owns_lock()) {
948 mainLock.lock();
949 }
950 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700951 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
952 std::move(target), kind);
953 return 0;
954}
955
956void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
957 std::string&& metadataName, std::string&& source,
958 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800959 const auto [it, _] =
960 ifs.bindPoints.insert_or_assign(target,
961 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800962 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800963 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700964}
965
966RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
967 const auto ifs = getIfs(storage);
968 if (!ifs) {
969 return {};
970 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700971 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700972 if (normPath.empty()) {
973 return {};
974 }
975 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800976}
977
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800978RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800979 const auto ifs = getIfs(storage);
980 if (!ifs) {
981 return {};
982 }
983 return mIncFs->getMetadata(ifs->control, node);
984}
985
Songchun Fan3c82a302019-11-29 14:23:45 -0800986bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700987 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700988 {
989 std::unique_lock l(mLock);
990 const auto& ifs = getIfsLocked(storage);
991 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800992 return false;
993 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700994 dataLoaderStub = ifs->dataLoaderStub;
995 if (!dataLoaderStub) {
996 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700997 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800998 }
Alex Buynytskyy9a545792020-04-17 15:34:47 -0700999 dataLoaderStub->requestStart();
1000 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001001}
1002
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001003std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1004 std::unordered_set<std::string_view> mountedRootNames;
1005 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1006 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1007 for (auto [source, target] : binds) {
1008 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1009 LOG(INFO) << " " << path::join(root, source);
1010 }
1011
1012 // Ensure it's a kind of a mount that's managed by IncrementalService
1013 if (path::basename(root) != constants().mount ||
1014 path::basename(backingDir) != constants().backing) {
1015 return;
1016 }
1017 const auto expectedRoot = path::dirname(root);
1018 if (path::dirname(backingDir) != expectedRoot) {
1019 return;
1020 }
1021 if (path::dirname(expectedRoot) != mIncrementalDir) {
1022 return;
1023 }
1024 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1025 return;
1026 }
1027
1028 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1029
1030 // make sure we clean up the mount if it happens to be a bad one.
1031 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1032 auto cleanupFiles = makeCleanup([&]() {
1033 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1034 IncFsMount::cleanupFilesystem(expectedRoot);
1035 });
1036 auto cleanupMounts = makeCleanup([&]() {
1037 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1038 for (auto&& [_, target] : binds) {
1039 mVold->unmountIncFs(std::string(target));
1040 }
1041 mVold->unmountIncFs(std::string(root));
1042 });
1043
1044 auto control = mIncFs->openMount(root);
1045 if (!control) {
1046 LOG(INFO) << "failed to open mount " << root;
1047 return;
1048 }
1049
1050 auto mountRecord =
1051 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1052 path::join(root, constants().infoMdName));
1053 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1054 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1055 return;
1056 }
1057
1058 auto mountId = mountRecord.storage().id();
1059 mNextId = std::max(mNextId, mountId + 1);
1060
1061 DataLoaderParamsParcel dataLoaderParams;
1062 {
1063 const auto& loader = mountRecord.loader();
1064 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1065 dataLoaderParams.packageName = loader.package_name();
1066 dataLoaderParams.className = loader.class_name();
1067 dataLoaderParams.arguments = loader.arguments();
1068 }
1069
1070 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1071 std::move(control), *this);
1072 cleanupFiles.release(); // ifs will take care of that now
1073
1074 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1075 auto d = openDir(root);
1076 while (auto e = ::readdir(d.get())) {
1077 if (e->d_type == DT_REG) {
1078 auto name = std::string_view(e->d_name);
1079 if (name.starts_with(constants().mountpointMdPrefix)) {
1080 permanentBindPoints
1081 .emplace_back(name,
1082 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1083 ifs->control,
1084 path::join(root,
1085 name)));
1086 if (permanentBindPoints.back().second.dest_path().empty() ||
1087 permanentBindPoints.back().second.source_subdir().empty()) {
1088 permanentBindPoints.pop_back();
1089 mIncFs->unlink(ifs->control, path::join(root, name));
1090 } else {
1091 LOG(INFO) << "Permanent bind record: '"
1092 << permanentBindPoints.back().second.source_subdir() << "'->'"
1093 << permanentBindPoints.back().second.dest_path() << "'";
1094 }
1095 }
1096 } else if (e->d_type == DT_DIR) {
1097 if (e->d_name == "."sv || e->d_name == ".."sv) {
1098 continue;
1099 }
1100 auto name = std::string_view(e->d_name);
1101 if (name.starts_with(constants().storagePrefix)) {
1102 int storageId;
1103 const auto res =
1104 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1105 name.data() + name.size(), storageId);
1106 if (res.ec != std::errc{} || *res.ptr != '_') {
1107 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1108 << "' for mount " << expectedRoot;
1109 continue;
1110 }
1111 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1112 if (!inserted) {
1113 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1114 << " for mount " << expectedRoot;
1115 continue;
1116 }
1117 ifs->storages.insert_or_assign(storageId,
1118 IncFsMount::Storage{path::join(root, name)});
1119 mNextId = std::max(mNextId, storageId + 1);
1120 }
1121 }
1122 }
1123
1124 if (ifs->storages.empty()) {
1125 LOG(WARNING) << "No valid storages in mount " << root;
1126 return;
1127 }
1128
1129 // now match the mounted directories with what we expect to have in the metadata
1130 {
1131 std::unique_lock l(mLock, std::defer_lock);
1132 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1133 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1134 [&, bindRecord = bindRecord](auto&& bind) {
1135 return bind.second == bindRecord.dest_path() &&
1136 path::join(root, bind.first) ==
1137 bindRecord.source_subdir();
1138 });
1139 if (mountedIt != binds.end()) {
1140 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1141 << " to mount " << mountedIt->first;
1142 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1143 std::move(*bindRecord.mutable_source_subdir()),
1144 std::move(*bindRecord.mutable_dest_path()),
1145 BindKind::Permanent);
1146 if (mountedIt != binds.end() - 1) {
1147 std::iter_swap(mountedIt, binds.end() - 1);
1148 }
1149 binds = binds.first(binds.size() - 1);
1150 } else {
1151 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1152 << ", mounting";
1153 // doesn't exist - try mounting back
1154 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1155 std::move(*bindRecord.mutable_source_subdir()),
1156 std::move(*bindRecord.mutable_dest_path()),
1157 BindKind::Permanent, l)) {
1158 mIncFs->unlink(ifs->control, metadataFile);
1159 }
1160 }
1161 }
1162 }
1163
1164 // if anything stays in |binds| those are probably temporary binds; system restarted since
1165 // they were mounted - so let's unmount them all.
1166 for (auto&& [source, target] : binds) {
1167 if (source.empty()) {
1168 continue;
1169 }
1170 mVold->unmountIncFs(std::string(target));
1171 }
1172 cleanupMounts.release(); // ifs now manages everything
1173
1174 if (ifs->bindPoints.empty()) {
1175 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1176 deleteStorage(*ifs);
1177 return;
1178 }
1179
1180 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1181 CHECK(ifs->dataLoaderStub);
1182
1183 mountedRootNames.insert(path::basename(ifs->root));
1184
1185 // not locking here at all: we're still in the constructor, no other calls can happen
1186 mMounts[ifs->mountId] = std::move(ifs);
1187 });
1188
1189 return mountedRootNames;
1190}
1191
1192void IncrementalService::mountExistingImages(
1193 const std::unordered_set<std::string_view>& mountedRootNames) {
1194 auto dir = openDir(mIncrementalDir);
1195 if (!dir) {
1196 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1197 return;
1198 }
1199 while (auto entry = ::readdir(dir.get())) {
1200 if (entry->d_type != DT_DIR) {
1201 continue;
1202 }
1203 std::string_view name = entry->d_name;
1204 if (!name.starts_with(constants().mountKeyPrefix)) {
1205 continue;
1206 }
1207 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001208 continue;
1209 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001210 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001211 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001212 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001213 }
1214 }
1215}
1216
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001217bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001218 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001219 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001220
Songchun Fan3c82a302019-11-29 14:23:45 -08001221 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001222 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001223 if (!status.isOk()) {
1224 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1225 return false;
1226 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001227
1228 int cmd = controlParcel.cmd.release().release();
1229 int pendingReads = controlParcel.pendingReads.release().release();
1230 int logs = controlParcel.log.release().release();
1231 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001232
1233 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1234
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001235 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1236 path::join(mountTarget, constants().infoMdName));
1237 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001238 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1239 return false;
1240 }
1241
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001242 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001243 mNextId = std::max(mNextId, ifs->mountId + 1);
1244
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001245 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001246 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001247 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001248 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001249 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001250 dataLoaderParams.packageName = loader.package_name();
1251 dataLoaderParams.className = loader.class_name();
1252 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001253 }
1254
Alex Buynytskyy69941662020-04-11 21:40:37 -07001255 prepareDataLoader(*ifs, std::move(dataLoaderParams), nullptr);
1256 CHECK(ifs->dataLoaderStub);
1257
Songchun Fan3c82a302019-11-29 14:23:45 -08001258 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001259 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001260 while (auto e = ::readdir(d.get())) {
1261 if (e->d_type == DT_REG) {
1262 auto name = std::string_view(e->d_name);
1263 if (name.starts_with(constants().mountpointMdPrefix)) {
1264 bindPoints.emplace_back(name,
1265 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1266 ifs->control,
1267 path::join(mountTarget,
1268 name)));
1269 if (bindPoints.back().second.dest_path().empty() ||
1270 bindPoints.back().second.source_subdir().empty()) {
1271 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001272 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001273 }
1274 }
1275 } else if (e->d_type == DT_DIR) {
1276 if (e->d_name == "."sv || e->d_name == ".."sv) {
1277 continue;
1278 }
1279 auto name = std::string_view(e->d_name);
1280 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001281 int storageId;
1282 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1283 name.data() + name.size(), storageId);
1284 if (res.ec != std::errc{} || *res.ptr != '_') {
1285 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1286 << root;
1287 continue;
1288 }
1289 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001290 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001291 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001292 << " for mount " << root;
1293 continue;
1294 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001295 ifs->storages.insert_or_assign(storageId,
1296 IncFsMount::Storage{
1297 path::join(root, constants().mount, name)});
1298 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001299 }
1300 }
1301 }
1302
1303 if (ifs->storages.empty()) {
1304 LOG(WARNING) << "No valid storages in mount " << root;
1305 return false;
1306 }
1307
1308 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001309 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001310 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001311 for (auto&& bp : bindPoints) {
1312 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1313 std::move(*bp.second.mutable_source_subdir()),
1314 std::move(*bp.second.mutable_dest_path()),
1315 BindKind::Permanent, l);
1316 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001317 }
1318
1319 if (bindCount == 0) {
1320 LOG(WARNING) << "No valid bind points for mount " << root;
1321 deleteStorage(*ifs);
1322 return false;
1323 }
1324
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001325 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001326 mMounts[ifs->mountId] = std::move(ifs);
1327 return true;
1328}
1329
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001330void IncrementalService::runCmdLooper() {
1331 constexpr auto kTimeoutMsecs = 1000;
1332 while (mRunning.load(std::memory_order_relaxed)) {
1333 mLooper->pollAll(kTimeoutMsecs);
1334 }
1335}
1336
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001337IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001338 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001339 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001340 std::unique_lock l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001341 prepareDataLoaderLocked(ifs, std::move(params), externalListener);
1342 return ifs.dataLoaderStub;
1343}
1344
1345void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
1346 const DataLoaderStatusListener* externalListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001347 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001348 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001349 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001350 }
1351
Songchun Fan3c82a302019-11-29 14:23:45 -08001352 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001353 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001354 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1355 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1356 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001357 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001358
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001359 ifs.dataLoaderStub =
1360 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001361 externalListener, path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001362}
1363
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001364template <class Duration>
1365static long elapsedMcs(Duration start, Duration end) {
1366 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1367}
1368
1369// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001370bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1371 std::string_view libDirRelativePath,
1372 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001373 auto start = Clock::now();
1374
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001375 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001376 if (!ifs) {
1377 LOG(ERROR) << "Invalid storage " << storage;
1378 return false;
1379 }
1380
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001381 // First prepare target directories if they don't exist yet
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001382 if (auto res = makeDirs(*ifs, storage, libDirRelativePath, 0755)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001383 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1384 << " errno: " << res;
1385 return false;
1386 }
1387
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001388 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001389 ZipArchiveHandle zipFileHandle;
1390 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001391 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1392 return false;
1393 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001394
1395 // Need a shared pointer: will be passing it into all unpacking jobs.
1396 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001397 void* cookie = nullptr;
1398 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001399 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001400 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1401 return false;
1402 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001403 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001404 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1405
1406 auto openZipTs = Clock::now();
1407
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001408 std::vector<Job> jobQueue;
1409 ZipEntry entry;
1410 std::string_view fileName;
1411 while (!Next(cookie, &entry, &fileName)) {
1412 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001413 continue;
1414 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001415
1416 auto startFileTs = Clock::now();
1417
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001418 const auto libName = path::basename(fileName);
Yurii Zubrytskyi510037b2020-04-22 15:46:21 -07001419 auto targetLibPath = path::join(libDirRelativePath, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001420 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001421 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001422 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001423 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001424 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1425 << "; skipping extraction, spent "
1426 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1427 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001428 continue;
1429 }
1430
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001431 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001432 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001433 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001434 .signature = {},
1435 // Metadata of the new lib file is its relative path
1436 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1437 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001438 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001439 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1440 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001441 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001442 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001443 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001444 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001445
1446 auto makeFileTs = Clock::now();
1447
Songchun Fanafaf6e92020-03-18 14:12:20 -07001448 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001449 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001450 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001451 LOG(INFO) << "incfs: Extracted " << libName
1452 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001453 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001454 continue;
1455 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001456
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001457 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1458 libFileId, libPath = std::move(targetLibPath),
1459 makeFileTs]() mutable {
1460 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001461 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001462
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001463 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001464 auto prepareJobTs = Clock::now();
1465 LOG(INFO) << "incfs: Processed " << libName << ": "
1466 << elapsedMcs(startFileTs, prepareJobTs)
1467 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1468 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001469 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001470 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001471
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001472 auto processedTs = Clock::now();
1473
1474 if (!jobQueue.empty()) {
1475 {
1476 std::lock_guard lock(mJobMutex);
1477 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001478 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001479 if (existingJobs.empty()) {
1480 existingJobs = std::move(jobQueue);
1481 } else {
1482 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1483 std::move_iterator(jobQueue.end()));
1484 }
1485 }
1486 }
1487 mJobCondition.notify_all();
1488 }
1489
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001490 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001491 auto end = Clock::now();
1492 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1493 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1494 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001495 << " make files: " << elapsedMcs(openZipTs, processedTs)
1496 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001497 }
1498
1499 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001500}
1501
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001502void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1503 ZipEntry& entry, const incfs::FileId& libFileId,
1504 std::string_view targetLibPath,
1505 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001506 if (!ifs) {
1507 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1508 return;
1509 }
1510
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001511 auto libName = path::basename(targetLibPath);
1512 auto startedTs = Clock::now();
1513
1514 // Write extracted data to new file
1515 // NOTE: don't zero-initialize memory, it may take a while for nothing
1516 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1517 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1518 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1519 return;
1520 }
1521
1522 auto extractFileTs = Clock::now();
1523
1524 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1525 if (!writeFd.ok()) {
1526 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1527 return;
1528 }
1529
1530 auto openFileTs = Clock::now();
1531 const int numBlocks =
1532 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1533 std::vector<IncFsDataBlock> instructions(numBlocks);
1534 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1535 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001536 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001537 instructions[i] = IncFsDataBlock{
1538 .fileFd = writeFd.get(),
1539 .pageIndex = static_cast<IncFsBlockIndex>(i),
1540 .compression = INCFS_COMPRESSION_KIND_NONE,
1541 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001542 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001543 .data = reinterpret_cast<const char*>(remainingData.data()),
1544 };
1545 remainingData = remainingData.subspan(blockSize);
1546 }
1547 auto prepareInstsTs = Clock::now();
1548
1549 size_t res = mIncFs->writeBlocks(instructions);
1550 if (res != instructions.size()) {
1551 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1552 return;
1553 }
1554
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001555 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001556 auto endFileTs = Clock::now();
1557 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1558 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1559 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1560 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1561 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1562 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1563 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1564 }
1565}
1566
1567bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001568 struct WaitPrinter {
1569 const Clock::time_point startTs = Clock::now();
1570 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001571 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001572 const auto endTs = Clock::now();
1573 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1574 << elapsedMcs(startTs, endTs) << "mcs";
1575 }
1576 }
1577 } waitPrinter;
1578
1579 MountId mount;
1580 {
1581 auto ifs = getIfs(storage);
1582 if (!ifs) {
1583 return true;
1584 }
1585 mount = ifs->mountId;
1586 }
1587
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001588 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001589 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001590 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001591 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001592 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001593 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001594}
1595
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001596bool IncrementalService::perfLoggingEnabled() {
1597 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1598 return enabled;
1599}
1600
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001601void IncrementalService::runJobProcessing() {
1602 for (;;) {
1603 std::unique_lock lock(mJobMutex);
1604 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1605 if (!mRunning) {
1606 return;
1607 }
1608
1609 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001610 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001611 auto queue = std::move(it->second);
1612 mJobQueue.erase(it);
1613 lock.unlock();
1614
1615 for (auto&& job : queue) {
1616 job();
1617 }
1618
1619 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001620 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001621 lock.unlock();
1622 mJobCondition.notify_all();
1623 }
1624}
1625
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001626void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001627 sp<IAppOpsCallback> listener;
1628 {
1629 std::unique_lock lock{mCallbacksLock};
1630 auto& cb = mCallbackRegistered[packageName];
1631 if (cb) {
1632 return;
1633 }
1634 cb = new AppOpsListener(*this, packageName);
1635 listener = cb;
1636 }
1637
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001638 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1639 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001640}
1641
1642bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1643 sp<IAppOpsCallback> listener;
1644 {
1645 std::unique_lock lock{mCallbacksLock};
1646 auto found = mCallbackRegistered.find(packageName);
1647 if (found == mCallbackRegistered.end()) {
1648 return false;
1649 }
1650 listener = found->second;
1651 mCallbackRegistered.erase(found);
1652 }
1653
1654 mAppOpsManager->stopWatchingMode(listener);
1655 return true;
1656}
1657
1658void IncrementalService::onAppOpChanged(const std::string& packageName) {
1659 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001660 return;
1661 }
1662
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001663 std::vector<IfsMountPtr> affected;
1664 {
1665 std::lock_guard l(mLock);
1666 affected.reserve(mMounts.size());
1667 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001668 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001669 affected.push_back(ifs);
1670 }
1671 }
1672 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001673 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001674 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001675 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001676}
1677
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001678IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1679 DataLoaderParamsParcel&& params,
1680 FileSystemControlParcel&& control,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001681 const DataLoaderStatusListener* externalListener,
1682 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001683 : mService(service),
1684 mId(id),
1685 mParams(std::move(params)),
1686 mControl(std::move(control)),
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001687 mListener(externalListener ? *externalListener : DataLoaderStatusListener()),
1688 mHealthPath(std::move(healthPath)) {
1689 healthStatusOk();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001690}
1691
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001692IncrementalService::DataLoaderStub::~DataLoaderStub() {
1693 if (mId != kInvalidStorageId) {
1694 cleanupResources();
1695 }
1696}
Alex Buynytskyy9a545792020-04-17 15:34:47 -07001697
1698void IncrementalService::DataLoaderStub::cleanupResources() {
1699 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001700
1701 auto now = Clock::now();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001702 std::unique_lock lock(mMutex);
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001703
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001704 unregisterFromPendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001705
Alex Buynytskyy9a545792020-04-17 15:34:47 -07001706 mParams = {};
1707 mControl = {};
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001708 mStatusCondition.wait_until(lock, now + 60s, [this] {
1709 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1710 });
Alex Buynytskyy9a545792020-04-17 15:34:47 -07001711 mListener = {};
1712 mId = kInvalidStorageId;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001713}
1714
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001715sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1716 sp<IDataLoader> dataloader;
1717 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1718 if (!status.isOk()) {
1719 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1720 return {};
1721 }
1722 if (!dataloader) {
1723 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1724 return {};
1725 }
1726 return dataloader;
1727}
1728
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001729bool IncrementalService::DataLoaderStub::requestCreate() {
1730 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1731}
1732
1733bool IncrementalService::DataLoaderStub::requestStart() {
1734 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1735}
1736
1737bool IncrementalService::DataLoaderStub::requestDestroy() {
1738 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1739}
1740
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001741bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001742 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001743 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001744 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001745 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001746 return fsmStep();
1747}
1748
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001749void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001750 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001751 mTargetStatus = status;
1752 mTargetStatusTs = Clock::now();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001753 LOG(DEBUG) << "Target status update for DataLoader " << mId << ": " << oldStatus << " -> "
1754 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001755}
1756
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001757bool IncrementalService::DataLoaderStub::bind() {
1758 bool result = false;
1759 auto status = mService.mDataLoaderManager->bindToDataLoader(mId, mParams, this, &result);
1760 if (!status.isOk() || !result) {
1761 LOG(ERROR) << "Failed to bind a data loader for mount " << mId;
1762 return false;
1763 }
1764 return true;
1765}
1766
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001767bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001768 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001769 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001770 return false;
1771 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001772 auto status = dataloader->create(mId, mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001773 if (!status.isOk()) {
1774 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001775 return false;
1776 }
1777 return true;
1778}
1779
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001780bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001781 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001782 if (!dataloader) {
1783 return false;
1784 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001785 auto status = dataloader->start(mId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001786 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001787 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001788 return false;
1789 }
1790 return true;
1791}
1792
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001793bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001794 return mService.mDataLoaderManager->unbindFromDataLoader(mId).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001795}
1796
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001797bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a545792020-04-17 15:34:47 -07001798 if (!isValid()) {
1799 return false;
1800 }
1801
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001802 int currentStatus;
1803 int targetStatus;
1804 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001805 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001806 currentStatus = mCurrentStatus;
1807 targetStatus = mTargetStatus;
1808 }
1809
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001810 LOG(DEBUG) << "fsmStep: " << mId << ": " << currentStatus << " -> " << targetStatus;
1811
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001812 if (currentStatus == targetStatus) {
1813 return true;
1814 }
1815
1816 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001817 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
1818 // Do nothing, this is a reset state.
1819 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001820 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1821 return destroy();
1822 }
1823 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1824 switch (currentStatus) {
1825 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1826 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1827 return start();
1828 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001829 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001830 }
1831 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1832 switch (currentStatus) {
1833 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001834 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001835 return bind();
1836 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001837 return create();
1838 }
1839 break;
1840 default:
1841 LOG(ERROR) << "Invalid target status: " << targetStatus
1842 << ", current status: " << currentStatus;
1843 break;
1844 }
1845 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001846}
1847
1848binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a545792020-04-17 15:34:47 -07001849 if (!isValid()) {
1850 return binder::Status::
1851 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
1852 }
1853 if (mId != mountId) {
1854 LOG(ERROR) << "Mount ID mismatch: expected " << mId << ", but got: " << mountId;
1855 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
1856 }
1857
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001858 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001859 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001860 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001861 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001862 if (mCurrentStatus == newStatus) {
1863 return binder::Status::ok();
1864 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001865
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001866 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001867 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001868 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001869
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001870 listener = mListener;
1871
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001872 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001873 // For unavailable, unbind from DataLoader to ensure proper re-commit.
1874 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001875 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001876 }
1877
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001878 LOG(DEBUG) << "Current status update for DataLoader " << mId << ": " << oldStatus << " -> "
1879 << newStatus << " (target " << targetStatus << ")";
1880
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001881 if (listener) {
1882 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001883 }
1884
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001885 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08001886
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07001887 mStatusCondition.notify_all();
1888
Songchun Fan3c82a302019-11-29 14:23:45 -08001889 return binder::Status::ok();
1890}
1891
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001892void IncrementalService::DataLoaderStub::healthStatusOk() {
1893 LOG(DEBUG) << "healthStatusOk: " << mId;
1894 std::unique_lock lock(mMutex);
1895 registerForPendingReads();
1896}
1897
1898void IncrementalService::DataLoaderStub::healthStatusReadsPending() {
1899 LOG(DEBUG) << "healthStatusReadsPending: " << mId;
1900 requestStart();
1901
1902 std::unique_lock lock(mMutex);
1903 unregisterFromPendingReads();
1904}
1905
1906void IncrementalService::DataLoaderStub::healthStatusBlocked() {}
1907
1908void IncrementalService::DataLoaderStub::healthStatusUnhealthy() {}
1909
1910void IncrementalService::DataLoaderStub::registerForPendingReads() {
1911 auto pendingReadsFd = mHealthControl.pendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001912 if (pendingReadsFd < 0) {
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001913 mHealthControl = mService.mIncFs->openMount(mHealthPath);
1914 pendingReadsFd = mHealthControl.pendingReads();
1915 if (pendingReadsFd < 0) {
1916 LOG(ERROR) << "Failed to open health control for: " << mId << ", path: " << mHealthPath
1917 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
1918 << mHealthControl.logs() << ")";
1919 return;
1920 }
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001921 }
1922
1923 mService.mLooper->addFd(
1924 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
1925 [](int, int, void* data) -> int {
1926 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001927 return self->onPendingReads();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001928 },
1929 this);
1930 mService.mLooper->wake();
1931}
1932
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001933void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001934 const auto pendingReadsFd = mHealthControl.pendingReads();
1935 if (pendingReadsFd < 0) {
1936 return;
1937 }
1938
1939 mService.mLooper->removeFd(pendingReadsFd);
1940 mService.mLooper->wake();
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001941
1942 mHealthControl = {};
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001943}
1944
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001945int IncrementalService::DataLoaderStub::onPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001946 if (!mService.mRunning.load(std::memory_order_relaxed)) {
1947 return 0;
1948 }
1949
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001950 healthStatusReadsPending();
1951 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001952}
1953
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001954void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001955 dprintf(fd, " dataLoader: {\n");
1956 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
1957 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
1958 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001959 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
1960 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001961 dprintf(fd, " dataLoaderParams: {\n");
1962 dprintf(fd, " type: %s\n", toString(params.type).c_str());
1963 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
1964 dprintf(fd, " className: %s\n", params.className.c_str());
1965 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
1966 dprintf(fd, " }\n");
1967 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001968}
1969
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001970void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1971 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001972}
1973
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001974binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1975 bool enableReadLogs, int32_t* _aidl_return) {
1976 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1977 return binder::Status::ok();
1978}
1979
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001980FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
1981 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
1982}
1983
Songchun Fan3c82a302019-11-29 14:23:45 -08001984} // namespace android::incremental