blob: 10368586999c15f307ba9c9607e90710255cb0f6 [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 Buynytskyy9a54579a2020-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()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800269 mIncrementalDir(rootDir) {
270 if (!mVold) {
271 LOG(FATAL) << "Vold service is unavailable";
272 }
Songchun Fan68645c42020-02-27 15:57:35 -0800273 if (!mDataLoaderManager) {
274 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800275 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700276 if (!mAppOpsManager) {
277 LOG(FATAL) << "AppOpsManager is unavailable";
278 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700279
280 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700281 mJobProcessor = std::thread([this]() {
282 mJni->initializeForCurrentThread();
283 runJobProcessing();
284 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700285
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700286 const auto mountedRootNames = adoptMountedInstances();
287 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800288}
289
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700290IncrementalService::~IncrementalService() {
291 {
292 std::lock_guard lock(mJobMutex);
293 mRunning = false;
294 }
295 mJobCondition.notify_all();
296 mJobProcessor.join();
297}
Songchun Fan3c82a302019-11-29 14:23:45 -0800298
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700299static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800300 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800301 case IncrementalService::BindKind::Temporary:
302 return "Temporary";
303 case IncrementalService::BindKind::Permanent:
304 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800305 }
306}
307
308void IncrementalService::onDump(int fd) {
309 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
310 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
311
312 std::unique_lock l(mLock);
313
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700314 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800315 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700316 const IncFsMount& mnt = *ifs;
317 dprintf(fd, " [%d]: {\n", id);
318 if (id != mnt.mountId) {
319 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
320 } else {
321 dprintf(fd, " mountId: %d\n", mnt.mountId);
322 dprintf(fd, " root: %s\n", mnt.root.c_str());
323 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
324 if (mnt.dataLoaderStub) {
325 mnt.dataLoaderStub->onDump(fd);
326 } else {
327 dprintf(fd, " dataLoader: null\n");
328 }
329 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
330 for (auto&& [storageId, storage] : mnt.storages) {
331 dprintf(fd, " [%d] -> [%s]\n", storageId, storage.name.c_str());
332 }
333 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800334
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700335 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
336 for (auto&& [target, bind] : mnt.bindPoints) {
337 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
338 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
339 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
340 dprintf(fd, " kind: %s\n", toString(bind.kind));
341 }
342 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800343 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700344 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800345 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700346 dprintf(fd, "}\n");
347 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800348 for (auto&& [target, mountPairIt] : mBindsByPath) {
349 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700350 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
351 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
352 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
353 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800354 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700355 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800356}
357
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700358void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800359 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700360 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800361 }
362
363 std::vector<IfsMountPtr> mounts;
364 {
365 std::lock_guard l(mLock);
366 mounts.reserve(mMounts.size());
367 for (auto&& [id, ifs] : mMounts) {
368 if (ifs->mountId == id) {
369 mounts.push_back(ifs);
370 }
371 }
372 }
373
Alex Buynytskyy69941662020-04-11 21:40:37 -0700374 if (mounts.empty()) {
375 return;
376 }
377
Songchun Fan3c82a302019-11-29 14:23:45 -0800378 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700379 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800380 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700381 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800382 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800383 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800384}
385
386auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
387 for (;;) {
388 if (mNextId == kMaxStorageId) {
389 mNextId = 0;
390 }
391 auto id = ++mNextId;
392 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
393 if (inserted) {
394 return it;
395 }
396 }
397}
398
Songchun Fan1124fd32020-02-10 12:49:41 -0800399StorageId IncrementalService::createStorage(
400 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
401 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800402 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
403 if (!path::isAbsolute(mountPoint)) {
404 LOG(ERROR) << "path is not absolute: " << mountPoint;
405 return kInvalidStorageId;
406 }
407
408 auto mountNorm = path::normalize(mountPoint);
409 {
410 const auto id = findStorageId(mountNorm);
411 if (id != kInvalidStorageId) {
412 if (options & CreateOptions::OpenExisting) {
413 LOG(INFO) << "Opened existing storage " << id;
414 return id;
415 }
416 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
417 return kInvalidStorageId;
418 }
419 }
420
421 if (!(options & CreateOptions::CreateNew)) {
422 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
423 return kInvalidStorageId;
424 }
425
426 if (!path::isEmptyDir(mountNorm)) {
427 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
428 return kInvalidStorageId;
429 }
430 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
431 if (mountRoot.empty()) {
432 LOG(ERROR) << "Bad mount point";
433 return kInvalidStorageId;
434 }
435 // Make sure the code removes all crap it may create while still failing.
436 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
437 auto firstCleanupOnFailure =
438 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
439
440 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800441 const auto backing = path::join(mountRoot, constants().backing);
442 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800443 return kInvalidStorageId;
444 }
445
Songchun Fan3c82a302019-11-29 14:23:45 -0800446 IncFsMount::Control control;
447 {
448 std::lock_guard l(mMountOperationLock);
449 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800450
451 if (auto err = rmDirContent(backing.c_str())) {
452 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
453 return kInvalidStorageId;
454 }
455 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
456 return kInvalidStorageId;
457 }
458 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800459 if (!status.isOk()) {
460 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
461 return kInvalidStorageId;
462 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800463 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
464 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800465 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
466 return kInvalidStorageId;
467 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800468 int cmd = controlParcel.cmd.release().release();
469 int pendingReads = controlParcel.pendingReads.release().release();
470 int logs = controlParcel.log.release().release();
471 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800472 }
473
474 std::unique_lock l(mLock);
475 const auto mountIt = getStorageSlotLocked();
476 const auto mountId = mountIt->first;
477 l.unlock();
478
479 auto ifs =
480 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
481 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
482 // is the removal of the |ifs|.
483 firstCleanupOnFailure.release();
484
485 auto secondCleanup = [this, &l](auto itPtr) {
486 if (!l.owns_lock()) {
487 l.lock();
488 }
489 mMounts.erase(*itPtr);
490 };
491 auto secondCleanupOnFailure =
492 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
493
494 const auto storageIt = ifs->makeStorage(ifs->mountId);
495 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800496 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800497 return kInvalidStorageId;
498 }
499
500 {
501 metadata::Mount m;
502 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700503 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700504 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
505 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
506 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800507 const auto metadata = m.SerializeAsString();
508 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800509 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800510 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800511 if (auto err =
512 mIncFs->makeFile(ifs->control,
513 path::join(ifs->root, constants().mount,
514 constants().infoMdName),
515 0777, idFromMetadata(metadata),
516 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800517 LOG(ERROR) << "Saving mount metadata failed: " << -err;
518 return kInvalidStorageId;
519 }
520 }
521
522 const auto bk =
523 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800524 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
525 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800526 err < 0) {
527 LOG(ERROR) << "adding bind mount failed: " << -err;
528 return kInvalidStorageId;
529 }
530
531 // Done here as well, all data structures are in good state.
532 secondCleanupOnFailure.release();
533
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700534 auto dataLoaderStub =
535 prepareDataLoader(*ifs, std::move(dataLoaderParams), &dataLoaderStatusListener);
536 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800537
538 mountIt->second = std::move(ifs);
539 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700540
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700541 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700542 // failed to create data loader
543 LOG(ERROR) << "initializeDataLoader() failed";
544 deleteStorage(dataLoaderStub->id());
545 return kInvalidStorageId;
546 }
547
Songchun Fan3c82a302019-11-29 14:23:45 -0800548 LOG(INFO) << "created storage " << mountId;
549 return mountId;
550}
551
552StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
553 StorageId linkedStorage,
554 IncrementalService::CreateOptions options) {
555 if (!isValidMountTarget(mountPoint)) {
556 LOG(ERROR) << "Mount point is invalid or missing";
557 return kInvalidStorageId;
558 }
559
560 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700561 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800562 if (!ifs) {
563 LOG(ERROR) << "Ifs unavailable";
564 return kInvalidStorageId;
565 }
566
567 const auto mountIt = getStorageSlotLocked();
568 const auto storageId = mountIt->first;
569 const auto storageIt = ifs->makeStorage(storageId);
570 if (storageIt == ifs->storages.end()) {
571 LOG(ERROR) << "Can't create a new storage";
572 mMounts.erase(mountIt);
573 return kInvalidStorageId;
574 }
575
576 l.unlock();
577
578 const auto bk =
579 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800580 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
581 std::string(storageIt->second.name), path::normalize(mountPoint),
582 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800583 err < 0) {
584 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700585 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
586 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800587 return kInvalidStorageId;
588 }
589
590 mountIt->second = ifs;
591 return storageId;
592}
593
594IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
595 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700596 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800597}
598
599StorageId IncrementalService::findStorageId(std::string_view path) const {
600 std::lock_guard l(mLock);
601 auto it = findStorageLocked(path);
602 if (it == mBindsByPath.end()) {
603 return kInvalidStorageId;
604 }
605 return it->second->second.storage;
606}
607
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700608int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
609 const auto ifs = getIfs(storageId);
610 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700611 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700612 return -EINVAL;
613 }
614
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700615 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700616 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700617 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
618 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700619 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700620 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700621 return fromBinderStatus(status);
622 }
623 }
624
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700625 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
626 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
627 return fromBinderStatus(status);
628 }
629
630 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700631 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700632 }
633
634 return 0;
635}
636
637binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700638 os::incremental::IncrementalFileSystemControlParcel control;
639 control.cmd.reset(dup(ifs.control.cmd()));
640 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700641 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700642 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700643 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700644 }
645
646 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700647 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700648}
649
Songchun Fan3c82a302019-11-29 14:23:45 -0800650void IncrementalService::deleteStorage(StorageId storageId) {
651 const auto ifs = getIfs(storageId);
652 if (!ifs) {
653 return;
654 }
655 deleteStorage(*ifs);
656}
657
658void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
659 std::unique_lock l(ifs.lock);
660 deleteStorageLocked(ifs, std::move(l));
661}
662
663void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
664 std::unique_lock<std::mutex>&& ifsLock) {
665 const auto storages = std::move(ifs.storages);
666 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
667 const auto bindPoints = ifs.bindPoints;
668 ifsLock.unlock();
669
670 std::lock_guard l(mLock);
671 for (auto&& [id, _] : storages) {
672 if (id != ifs.mountId) {
673 mMounts.erase(id);
674 }
675 }
676 for (auto&& [path, _] : bindPoints) {
677 mBindsByPath.erase(path);
678 }
679 mMounts.erase(ifs.mountId);
680}
681
682StorageId IncrementalService::openStorage(std::string_view pathInMount) {
683 if (!path::isAbsolute(pathInMount)) {
684 return kInvalidStorageId;
685 }
686
687 return findStorageId(path::normalize(pathInMount));
688}
689
Songchun Fan3c82a302019-11-29 14:23:45 -0800690IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
691 std::lock_guard l(mLock);
692 return getIfsLocked(storage);
693}
694
695const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
696 auto it = mMounts.find(storage);
697 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700698 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700699 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800700 }
701 return it->second;
702}
703
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800704int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
705 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800706 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700707 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800708 return -EINVAL;
709 }
710
711 const auto ifs = getIfs(storage);
712 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700713 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800714 return -EINVAL;
715 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800716
Songchun Fan3c82a302019-11-29 14:23:45 -0800717 std::unique_lock l(ifs->lock);
718 const auto storageInfo = ifs->storages.find(storage);
719 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700720 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800721 return -EINVAL;
722 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700723 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700724 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700725 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700726 return -EINVAL;
727 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800728 l.unlock();
729 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800730 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
731 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800732}
733
734int IncrementalService::unbind(StorageId storage, std::string_view target) {
735 if (!path::isAbsolute(target)) {
736 return -EINVAL;
737 }
738
739 LOG(INFO) << "Removing bind point " << target;
740
741 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
742 // otherwise there's a chance to unmount something completely unrelated
743 const auto norm = path::normalize(target);
744 std::unique_lock l(mLock);
745 const auto storageIt = mBindsByPath.find(norm);
746 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
747 return -EINVAL;
748 }
749 const auto bindIt = storageIt->second;
750 const auto storageId = bindIt->second.storage;
751 const auto ifs = getIfsLocked(storageId);
752 if (!ifs) {
753 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
754 << " is missing";
755 return -EFAULT;
756 }
757 mBindsByPath.erase(storageIt);
758 l.unlock();
759
760 mVold->unmountIncFs(bindIt->first);
761 std::unique_lock l2(ifs->lock);
762 if (ifs->bindPoints.size() <= 1) {
763 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700764 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800765 } else {
766 const std::string savedFile = std::move(bindIt->second.savedFilename);
767 ifs->bindPoints.erase(bindIt);
768 l2.unlock();
769 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800770 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800771 }
772 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700773
Songchun Fan3c82a302019-11-29 14:23:45 -0800774 return 0;
775}
776
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700777std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700778 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700779 std::string_view path) const {
780 if (!path::isAbsolute(path)) {
781 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700782 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700783 auto normPath = path::normalize(path);
784 if (path::startsWith(normPath, storageIt->second.name)) {
785 return normPath;
786 }
787 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700788 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
789 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700790 return {};
791 }
792 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700793}
794
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700795std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700796 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700797 std::unique_lock l(ifs.lock);
798 const auto storageInfo = ifs.storages.find(storage);
799 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800800 return {};
801 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700802 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800803}
804
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800805int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
806 incfs::NewFileParams params) {
807 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700808 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800809 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700810 LOG(ERROR) << "Internal error: storageId " << storage
811 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800812 return -EINVAL;
813 }
814 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800815 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700816 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800817 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800818 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800819 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800820 }
821 return -EINVAL;
822}
823
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800824int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800825 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700826 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800827 if (normPath.empty()) {
828 return -EINVAL;
829 }
830 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800831 }
832 return -EINVAL;
833}
834
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800835int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800836 const auto ifs = getIfs(storageId);
837 if (!ifs) {
838 return -EINVAL;
839 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700840 return makeDirs(*ifs, storageId, path, mode);
841}
842
843int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
844 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800845 std::string normPath = normalizePathToStorage(ifs, storageId, path);
846 if (normPath.empty()) {
847 return -EINVAL;
848 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700849 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800850}
851
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800852int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
853 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700854 std::unique_lock l(mLock);
855 auto ifsSrc = getIfsLocked(sourceStorageId);
856 if (!ifsSrc) {
857 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800858 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700859 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
860 return -EINVAL;
861 }
862 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700863 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
864 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700865 if (normOldPath.empty() || normNewPath.empty()) {
866 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
867 return -EINVAL;
868 }
869 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800870}
871
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800872int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800873 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700874 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800875 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800876 }
877 return -EINVAL;
878}
879
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800880int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
881 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800882 std::string&& target, BindKind kind,
883 std::unique_lock<std::mutex>& mainLock) {
884 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700885 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800886 return -EINVAL;
887 }
888
889 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700890 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800891 if (kind != BindKind::Temporary) {
892 metadata::BindPoint bp;
893 bp.set_storage_id(storage);
894 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800895 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800896 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800897 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800898 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800899 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700900 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
901 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
902 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800903 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700904 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800905 return int(node);
906 }
907 }
908
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700909 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
910 std::move(target), kind, mainLock);
911 if (res) {
912 mIncFs->unlink(ifs.control, metadataFullPath);
913 }
914 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800915}
916
917int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800918 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800919 std::string&& target, BindKind kind,
920 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800921 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800922 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800923 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800924 if (!status.isOk()) {
925 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
926 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
927 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
928 : status.serviceSpecificErrorCode() == 0
929 ? -EFAULT
930 : status.serviceSpecificErrorCode()
931 : -EIO;
932 }
933 }
934
935 if (!mainLock.owns_lock()) {
936 mainLock.lock();
937 }
938 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700939 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
940 std::move(target), kind);
941 return 0;
942}
943
944void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
945 std::string&& metadataName, std::string&& source,
946 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800947 const auto [it, _] =
948 ifs.bindPoints.insert_or_assign(target,
949 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800950 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800951 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700952}
953
954RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
955 const auto ifs = getIfs(storage);
956 if (!ifs) {
957 return {};
958 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700959 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700960 if (normPath.empty()) {
961 return {};
962 }
963 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800964}
965
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800966RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800967 const auto ifs = getIfs(storage);
968 if (!ifs) {
969 return {};
970 }
971 return mIncFs->getMetadata(ifs->control, node);
972}
973
Songchun Fan3c82a302019-11-29 14:23:45 -0800974bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700975 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700976 {
977 std::unique_lock l(mLock);
978 const auto& ifs = getIfsLocked(storage);
979 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800980 return false;
981 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700982 dataLoaderStub = ifs->dataLoaderStub;
983 if (!dataLoaderStub) {
984 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700985 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800986 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700987 dataLoaderStub->requestStart();
988 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -0800989}
990
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700991std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
992 std::unordered_set<std::string_view> mountedRootNames;
993 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
994 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
995 for (auto [source, target] : binds) {
996 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
997 LOG(INFO) << " " << path::join(root, source);
998 }
999
1000 // Ensure it's a kind of a mount that's managed by IncrementalService
1001 if (path::basename(root) != constants().mount ||
1002 path::basename(backingDir) != constants().backing) {
1003 return;
1004 }
1005 const auto expectedRoot = path::dirname(root);
1006 if (path::dirname(backingDir) != expectedRoot) {
1007 return;
1008 }
1009 if (path::dirname(expectedRoot) != mIncrementalDir) {
1010 return;
1011 }
1012 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1013 return;
1014 }
1015
1016 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1017
1018 // make sure we clean up the mount if it happens to be a bad one.
1019 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1020 auto cleanupFiles = makeCleanup([&]() {
1021 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1022 IncFsMount::cleanupFilesystem(expectedRoot);
1023 });
1024 auto cleanupMounts = makeCleanup([&]() {
1025 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1026 for (auto&& [_, target] : binds) {
1027 mVold->unmountIncFs(std::string(target));
1028 }
1029 mVold->unmountIncFs(std::string(root));
1030 });
1031
1032 auto control = mIncFs->openMount(root);
1033 if (!control) {
1034 LOG(INFO) << "failed to open mount " << root;
1035 return;
1036 }
1037
1038 auto mountRecord =
1039 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1040 path::join(root, constants().infoMdName));
1041 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1042 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1043 return;
1044 }
1045
1046 auto mountId = mountRecord.storage().id();
1047 mNextId = std::max(mNextId, mountId + 1);
1048
1049 DataLoaderParamsParcel dataLoaderParams;
1050 {
1051 const auto& loader = mountRecord.loader();
1052 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1053 dataLoaderParams.packageName = loader.package_name();
1054 dataLoaderParams.className = loader.class_name();
1055 dataLoaderParams.arguments = loader.arguments();
1056 }
1057
1058 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1059 std::move(control), *this);
1060 cleanupFiles.release(); // ifs will take care of that now
1061
1062 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1063 auto d = openDir(root);
1064 while (auto e = ::readdir(d.get())) {
1065 if (e->d_type == DT_REG) {
1066 auto name = std::string_view(e->d_name);
1067 if (name.starts_with(constants().mountpointMdPrefix)) {
1068 permanentBindPoints
1069 .emplace_back(name,
1070 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1071 ifs->control,
1072 path::join(root,
1073 name)));
1074 if (permanentBindPoints.back().second.dest_path().empty() ||
1075 permanentBindPoints.back().second.source_subdir().empty()) {
1076 permanentBindPoints.pop_back();
1077 mIncFs->unlink(ifs->control, path::join(root, name));
1078 } else {
1079 LOG(INFO) << "Permanent bind record: '"
1080 << permanentBindPoints.back().second.source_subdir() << "'->'"
1081 << permanentBindPoints.back().second.dest_path() << "'";
1082 }
1083 }
1084 } else if (e->d_type == DT_DIR) {
1085 if (e->d_name == "."sv || e->d_name == ".."sv) {
1086 continue;
1087 }
1088 auto name = std::string_view(e->d_name);
1089 if (name.starts_with(constants().storagePrefix)) {
1090 int storageId;
1091 const auto res =
1092 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1093 name.data() + name.size(), storageId);
1094 if (res.ec != std::errc{} || *res.ptr != '_') {
1095 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1096 << "' for mount " << expectedRoot;
1097 continue;
1098 }
1099 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1100 if (!inserted) {
1101 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1102 << " for mount " << expectedRoot;
1103 continue;
1104 }
1105 ifs->storages.insert_or_assign(storageId,
1106 IncFsMount::Storage{path::join(root, name)});
1107 mNextId = std::max(mNextId, storageId + 1);
1108 }
1109 }
1110 }
1111
1112 if (ifs->storages.empty()) {
1113 LOG(WARNING) << "No valid storages in mount " << root;
1114 return;
1115 }
1116
1117 // now match the mounted directories with what we expect to have in the metadata
1118 {
1119 std::unique_lock l(mLock, std::defer_lock);
1120 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1121 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1122 [&, bindRecord = bindRecord](auto&& bind) {
1123 return bind.second == bindRecord.dest_path() &&
1124 path::join(root, bind.first) ==
1125 bindRecord.source_subdir();
1126 });
1127 if (mountedIt != binds.end()) {
1128 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1129 << " to mount " << mountedIt->first;
1130 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1131 std::move(*bindRecord.mutable_source_subdir()),
1132 std::move(*bindRecord.mutable_dest_path()),
1133 BindKind::Permanent);
1134 if (mountedIt != binds.end() - 1) {
1135 std::iter_swap(mountedIt, binds.end() - 1);
1136 }
1137 binds = binds.first(binds.size() - 1);
1138 } else {
1139 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1140 << ", mounting";
1141 // doesn't exist - try mounting back
1142 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1143 std::move(*bindRecord.mutable_source_subdir()),
1144 std::move(*bindRecord.mutable_dest_path()),
1145 BindKind::Permanent, l)) {
1146 mIncFs->unlink(ifs->control, metadataFile);
1147 }
1148 }
1149 }
1150 }
1151
1152 // if anything stays in |binds| those are probably temporary binds; system restarted since
1153 // they were mounted - so let's unmount them all.
1154 for (auto&& [source, target] : binds) {
1155 if (source.empty()) {
1156 continue;
1157 }
1158 mVold->unmountIncFs(std::string(target));
1159 }
1160 cleanupMounts.release(); // ifs now manages everything
1161
1162 if (ifs->bindPoints.empty()) {
1163 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1164 deleteStorage(*ifs);
1165 return;
1166 }
1167
1168 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1169 CHECK(ifs->dataLoaderStub);
1170
1171 mountedRootNames.insert(path::basename(ifs->root));
1172
1173 // not locking here at all: we're still in the constructor, no other calls can happen
1174 mMounts[ifs->mountId] = std::move(ifs);
1175 });
1176
1177 return mountedRootNames;
1178}
1179
1180void IncrementalService::mountExistingImages(
1181 const std::unordered_set<std::string_view>& mountedRootNames) {
1182 auto dir = openDir(mIncrementalDir);
1183 if (!dir) {
1184 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1185 return;
1186 }
1187 while (auto entry = ::readdir(dir.get())) {
1188 if (entry->d_type != DT_DIR) {
1189 continue;
1190 }
1191 std::string_view name = entry->d_name;
1192 if (!name.starts_with(constants().mountKeyPrefix)) {
1193 continue;
1194 }
1195 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001196 continue;
1197 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001198 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001199 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001200 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001201 }
1202 }
1203}
1204
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001205bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001206 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001207 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001208
Songchun Fan3c82a302019-11-29 14:23:45 -08001209 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001210 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001211 if (!status.isOk()) {
1212 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1213 return false;
1214 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001215
1216 int cmd = controlParcel.cmd.release().release();
1217 int pendingReads = controlParcel.pendingReads.release().release();
1218 int logs = controlParcel.log.release().release();
1219 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001220
1221 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1222
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001223 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1224 path::join(mountTarget, constants().infoMdName));
1225 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001226 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1227 return false;
1228 }
1229
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001230 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001231 mNextId = std::max(mNextId, ifs->mountId + 1);
1232
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001233 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001234 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001235 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001236 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001237 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001238 dataLoaderParams.packageName = loader.package_name();
1239 dataLoaderParams.className = loader.class_name();
1240 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001241 }
1242
Alex Buynytskyy69941662020-04-11 21:40:37 -07001243 prepareDataLoader(*ifs, std::move(dataLoaderParams), nullptr);
1244 CHECK(ifs->dataLoaderStub);
1245
Songchun Fan3c82a302019-11-29 14:23:45 -08001246 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001247 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001248 while (auto e = ::readdir(d.get())) {
1249 if (e->d_type == DT_REG) {
1250 auto name = std::string_view(e->d_name);
1251 if (name.starts_with(constants().mountpointMdPrefix)) {
1252 bindPoints.emplace_back(name,
1253 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1254 ifs->control,
1255 path::join(mountTarget,
1256 name)));
1257 if (bindPoints.back().second.dest_path().empty() ||
1258 bindPoints.back().second.source_subdir().empty()) {
1259 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001260 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001261 }
1262 }
1263 } else if (e->d_type == DT_DIR) {
1264 if (e->d_name == "."sv || e->d_name == ".."sv) {
1265 continue;
1266 }
1267 auto name = std::string_view(e->d_name);
1268 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001269 int storageId;
1270 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1271 name.data() + name.size(), storageId);
1272 if (res.ec != std::errc{} || *res.ptr != '_') {
1273 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1274 << root;
1275 continue;
1276 }
1277 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001278 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001279 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001280 << " for mount " << root;
1281 continue;
1282 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001283 ifs->storages.insert_or_assign(storageId,
1284 IncFsMount::Storage{
1285 path::join(root, constants().mount, name)});
1286 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001287 }
1288 }
1289 }
1290
1291 if (ifs->storages.empty()) {
1292 LOG(WARNING) << "No valid storages in mount " << root;
1293 return false;
1294 }
1295
1296 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001297 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001298 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001299 for (auto&& bp : bindPoints) {
1300 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1301 std::move(*bp.second.mutable_source_subdir()),
1302 std::move(*bp.second.mutable_dest_path()),
1303 BindKind::Permanent, l);
1304 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001305 }
1306
1307 if (bindCount == 0) {
1308 LOG(WARNING) << "No valid bind points for mount " << root;
1309 deleteStorage(*ifs);
1310 return false;
1311 }
1312
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001313 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001314 mMounts[ifs->mountId] = std::move(ifs);
1315 return true;
1316}
1317
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001318IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001319 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001320 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001321 std::unique_lock l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001322 prepareDataLoaderLocked(ifs, std::move(params), externalListener);
1323 return ifs.dataLoaderStub;
1324}
1325
1326void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
1327 const DataLoaderStatusListener* externalListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001328 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001329 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001330 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001331 }
1332
Songchun Fan3c82a302019-11-29 14:23:45 -08001333 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001334 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001335 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1336 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1337 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001338 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001339
1340 ifs.dataLoaderStub = new DataLoaderStub(*this, ifs.mountId, std::move(params),
1341 std::move(fsControlParcel), externalListener);
Songchun Fan3c82a302019-11-29 14:23:45 -08001342}
1343
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001344template <class Duration>
1345static long elapsedMcs(Duration start, Duration end) {
1346 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1347}
1348
1349// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001350bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1351 std::string_view libDirRelativePath,
1352 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001353 auto start = Clock::now();
1354
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001355 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001356 if (!ifs) {
1357 LOG(ERROR) << "Invalid storage " << storage;
1358 return false;
1359 }
1360
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001361 // First prepare target directories if they don't exist yet
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001362 if (auto res = makeDirs(*ifs, storage, libDirRelativePath, 0755)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001363 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1364 << " errno: " << res;
1365 return false;
1366 }
1367
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001368 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001369 ZipArchiveHandle zipFileHandle;
1370 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001371 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1372 return false;
1373 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001374
1375 // Need a shared pointer: will be passing it into all unpacking jobs.
1376 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001377 void* cookie = nullptr;
1378 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001379 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001380 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1381 return false;
1382 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001383 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001384 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1385
1386 auto openZipTs = Clock::now();
1387
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001388 std::vector<Job> jobQueue;
1389 ZipEntry entry;
1390 std::string_view fileName;
1391 while (!Next(cookie, &entry, &fileName)) {
1392 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001393 continue;
1394 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001395
1396 auto startFileTs = Clock::now();
1397
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001398 const auto libName = path::basename(fileName);
Yurii Zubrytskyi510037b2020-04-22 15:46:21 -07001399 auto targetLibPath = path::join(libDirRelativePath, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001400 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001401 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001402 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001403 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001404 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1405 << "; skipping extraction, spent "
1406 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1407 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001408 continue;
1409 }
1410
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001411 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001412 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001413 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001414 .signature = {},
1415 // Metadata of the new lib file is its relative path
1416 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1417 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001418 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001419 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1420 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001421 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001422 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001423 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001424 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001425
1426 auto makeFileTs = Clock::now();
1427
Songchun Fanafaf6e92020-03-18 14:12:20 -07001428 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001429 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001430 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001431 LOG(INFO) << "incfs: Extracted " << libName
1432 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001433 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001434 continue;
1435 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001436
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001437 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1438 libFileId, libPath = std::move(targetLibPath),
1439 makeFileTs]() mutable {
1440 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001441 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001442
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001443 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001444 auto prepareJobTs = Clock::now();
1445 LOG(INFO) << "incfs: Processed " << libName << ": "
1446 << elapsedMcs(startFileTs, prepareJobTs)
1447 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1448 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001449 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001450 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001451
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001452 auto processedTs = Clock::now();
1453
1454 if (!jobQueue.empty()) {
1455 {
1456 std::lock_guard lock(mJobMutex);
1457 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001458 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001459 if (existingJobs.empty()) {
1460 existingJobs = std::move(jobQueue);
1461 } else {
1462 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1463 std::move_iterator(jobQueue.end()));
1464 }
1465 }
1466 }
1467 mJobCondition.notify_all();
1468 }
1469
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001470 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001471 auto end = Clock::now();
1472 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1473 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1474 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001475 << " make files: " << elapsedMcs(openZipTs, processedTs)
1476 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001477 }
1478
1479 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001480}
1481
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001482void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1483 ZipEntry& entry, const incfs::FileId& libFileId,
1484 std::string_view targetLibPath,
1485 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001486 if (!ifs) {
1487 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1488 return;
1489 }
1490
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001491 auto libName = path::basename(targetLibPath);
1492 auto startedTs = Clock::now();
1493
1494 // Write extracted data to new file
1495 // NOTE: don't zero-initialize memory, it may take a while for nothing
1496 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1497 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1498 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1499 return;
1500 }
1501
1502 auto extractFileTs = Clock::now();
1503
1504 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1505 if (!writeFd.ok()) {
1506 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1507 return;
1508 }
1509
1510 auto openFileTs = Clock::now();
1511 const int numBlocks =
1512 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1513 std::vector<IncFsDataBlock> instructions(numBlocks);
1514 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1515 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001516 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001517 instructions[i] = IncFsDataBlock{
1518 .fileFd = writeFd.get(),
1519 .pageIndex = static_cast<IncFsBlockIndex>(i),
1520 .compression = INCFS_COMPRESSION_KIND_NONE,
1521 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001522 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001523 .data = reinterpret_cast<const char*>(remainingData.data()),
1524 };
1525 remainingData = remainingData.subspan(blockSize);
1526 }
1527 auto prepareInstsTs = Clock::now();
1528
1529 size_t res = mIncFs->writeBlocks(instructions);
1530 if (res != instructions.size()) {
1531 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1532 return;
1533 }
1534
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001535 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001536 auto endFileTs = Clock::now();
1537 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1538 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1539 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1540 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1541 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1542 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1543 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1544 }
1545}
1546
1547bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001548 struct WaitPrinter {
1549 const Clock::time_point startTs = Clock::now();
1550 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001551 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001552 const auto endTs = Clock::now();
1553 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1554 << elapsedMcs(startTs, endTs) << "mcs";
1555 }
1556 }
1557 } waitPrinter;
1558
1559 MountId mount;
1560 {
1561 auto ifs = getIfs(storage);
1562 if (!ifs) {
1563 return true;
1564 }
1565 mount = ifs->mountId;
1566 }
1567
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001568 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001569 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001570 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001571 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001572 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001573 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001574}
1575
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001576bool IncrementalService::perfLoggingEnabled() {
1577 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1578 return enabled;
1579}
1580
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001581void IncrementalService::runJobProcessing() {
1582 for (;;) {
1583 std::unique_lock lock(mJobMutex);
1584 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1585 if (!mRunning) {
1586 return;
1587 }
1588
1589 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001590 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001591 auto queue = std::move(it->second);
1592 mJobQueue.erase(it);
1593 lock.unlock();
1594
1595 for (auto&& job : queue) {
1596 job();
1597 }
1598
1599 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001600 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001601 lock.unlock();
1602 mJobCondition.notify_all();
1603 }
1604}
1605
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001606void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001607 sp<IAppOpsCallback> listener;
1608 {
1609 std::unique_lock lock{mCallbacksLock};
1610 auto& cb = mCallbackRegistered[packageName];
1611 if (cb) {
1612 return;
1613 }
1614 cb = new AppOpsListener(*this, packageName);
1615 listener = cb;
1616 }
1617
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001618 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1619 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001620}
1621
1622bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1623 sp<IAppOpsCallback> listener;
1624 {
1625 std::unique_lock lock{mCallbacksLock};
1626 auto found = mCallbackRegistered.find(packageName);
1627 if (found == mCallbackRegistered.end()) {
1628 return false;
1629 }
1630 listener = found->second;
1631 mCallbackRegistered.erase(found);
1632 }
1633
1634 mAppOpsManager->stopWatchingMode(listener);
1635 return true;
1636}
1637
1638void IncrementalService::onAppOpChanged(const std::string& packageName) {
1639 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001640 return;
1641 }
1642
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001643 std::vector<IfsMountPtr> affected;
1644 {
1645 std::lock_guard l(mLock);
1646 affected.reserve(mMounts.size());
1647 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001648 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001649 affected.push_back(ifs);
1650 }
1651 }
1652 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001653 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001654 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001655 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001656}
1657
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001658IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1659 DataLoaderParamsParcel&& params,
1660 FileSystemControlParcel&& control,
1661 const DataLoaderStatusListener* externalListener)
1662 : mService(service),
1663 mId(id),
1664 mParams(std::move(params)),
1665 mControl(std::move(control)),
1666 mListener(externalListener ? *externalListener : DataLoaderStatusListener()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001667}
1668
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001669IncrementalService::DataLoaderStub::~DataLoaderStub() = default;
1670
1671void IncrementalService::DataLoaderStub::cleanupResources() {
1672 requestDestroy();
1673 mParams = {};
1674 mControl = {};
1675 waitForStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED, std::chrono::seconds(60));
1676 mListener = {};
1677 mId = kInvalidStorageId;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001678}
1679
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001680sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1681 sp<IDataLoader> dataloader;
1682 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1683 if (!status.isOk()) {
1684 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1685 return {};
1686 }
1687 if (!dataloader) {
1688 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1689 return {};
1690 }
1691 return dataloader;
1692}
1693
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001694bool IncrementalService::DataLoaderStub::requestCreate() {
1695 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1696}
1697
1698bool IncrementalService::DataLoaderStub::requestStart() {
1699 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1700}
1701
1702bool IncrementalService::DataLoaderStub::requestDestroy() {
1703 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1704}
1705
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001706bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
1707 int oldStatus, curStatus;
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001708 {
1709 std::unique_lock lock(mStatusMutex);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001710 oldStatus = mTargetStatus;
1711 mTargetStatus = newStatus;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001712 mTargetStatusTs = Clock::now();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001713 curStatus = mCurrentStatus;
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001714 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001715 LOG(DEBUG) << "Target status update for DataLoader " << mId << ": " << oldStatus << " -> "
1716 << newStatus << " (current " << curStatus << ")";
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001717 return fsmStep();
1718}
1719
1720bool IncrementalService::DataLoaderStub::waitForStatus(int status, Clock::duration duration) {
1721 auto now = Clock::now();
1722 std::unique_lock lock(mStatusMutex);
1723 return mStatusCondition.wait_until(lock, now + duration,
1724 [this, status] { return mCurrentStatus == status; });
1725}
1726
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001727bool IncrementalService::DataLoaderStub::bind() {
1728 bool result = false;
1729 auto status = mService.mDataLoaderManager->bindToDataLoader(mId, mParams, this, &result);
1730 if (!status.isOk() || !result) {
1731 LOG(ERROR) << "Failed to bind a data loader for mount " << mId;
1732 return false;
1733 }
1734 return true;
1735}
1736
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001737bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001738 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001739 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001740 return false;
1741 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001742 auto status = dataloader->create(mId, mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001743 if (!status.isOk()) {
1744 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001745 return false;
1746 }
1747 return true;
1748}
1749
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001750bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001751 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001752 if (!dataloader) {
1753 return false;
1754 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001755 auto status = dataloader->start(mId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001756 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001757 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001758 return false;
1759 }
1760 return true;
1761}
1762
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001763bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001764 return mService.mDataLoaderManager->unbindFromDataLoader(mId).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001765}
1766
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001767bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001768 if (!isValid()) {
1769 return false;
1770 }
1771
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001772 int currentStatus;
1773 int targetStatus;
1774 {
1775 std::unique_lock lock(mStatusMutex);
1776 currentStatus = mCurrentStatus;
1777 targetStatus = mTargetStatus;
1778 }
1779
1780 if (currentStatus == targetStatus) {
1781 return true;
1782 }
1783
1784 switch (targetStatus) {
1785 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1786 return destroy();
1787 }
1788 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1789 switch (currentStatus) {
1790 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1791 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1792 return start();
1793 }
1794 // fallthrough
1795 }
1796 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1797 switch (currentStatus) {
1798 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001799 return bind();
1800 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001801 return create();
1802 }
1803 break;
1804 default:
1805 LOG(ERROR) << "Invalid target status: " << targetStatus
1806 << ", current status: " << currentStatus;
1807 break;
1808 }
1809 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001810}
1811
1812binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001813 if (!isValid()) {
1814 return binder::Status::
1815 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
1816 }
1817 if (mId != mountId) {
1818 LOG(ERROR) << "Mount ID mismatch: expected " << mId << ", but got: " << mountId;
1819 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
1820 }
1821
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001822 int targetStatus, oldStatus;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001823 {
1824 std::unique_lock lock(mStatusMutex);
1825 if (mCurrentStatus == newStatus) {
1826 return binder::Status::ok();
1827 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001828 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001829 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001830 targetStatus = mTargetStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001831 }
1832
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001833 LOG(DEBUG) << "Current status update for DataLoader " << mId << ": " << oldStatus << " -> "
1834 << newStatus << " (target " << targetStatus << ")";
1835
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001836 if (mListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001837 mListener->onStatusChanged(mountId, newStatus);
1838 }
1839
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001840 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08001841
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07001842 mStatusCondition.notify_all();
1843
Songchun Fan3c82a302019-11-29 14:23:45 -08001844 return binder::Status::ok();
1845}
1846
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001847void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001848 dprintf(fd, " dataLoader: {\n");
1849 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
1850 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
1851 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001852 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
1853 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001854 dprintf(fd, " dataLoaderParams: {\n");
1855 dprintf(fd, " type: %s\n", toString(params.type).c_str());
1856 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
1857 dprintf(fd, " className: %s\n", params.className.c_str());
1858 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
1859 dprintf(fd, " }\n");
1860 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001861}
1862
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001863void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1864 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001865}
1866
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001867binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1868 bool enableReadLogs, int32_t* _aidl_return) {
1869 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1870 return binder::Status::ok();
1871}
1872
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001873FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
1874 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
1875}
1876
Songchun Fan3c82a302019-11-29 14:23:45 -08001877} // namespace android::incremental