blob: cae5027250e14c4c73c3435646bac8ddebbbe4bc [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()),
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 Buynytskyy0bdbccf2020-04-23 20:36:42 -0700764 std::thread([this, ifs, l2 = std::move(l2)]() mutable {
765 mJni->initializeForCurrentThread();
766 deleteStorageLocked(*ifs, std::move(l2));
767 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800768 } else {
769 const std::string savedFile = std::move(bindIt->second.savedFilename);
770 ifs->bindPoints.erase(bindIt);
771 l2.unlock();
772 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800773 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800774 }
775 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700776
Songchun Fan3c82a302019-11-29 14:23:45 -0800777 return 0;
778}
779
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700780std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700781 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700782 std::string_view path) const {
783 if (!path::isAbsolute(path)) {
784 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700785 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700786 auto normPath = path::normalize(path);
787 if (path::startsWith(normPath, storageIt->second.name)) {
788 return normPath;
789 }
790 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700791 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
792 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700793 return {};
794 }
795 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700796}
797
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700798std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700799 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700800 std::unique_lock l(ifs.lock);
801 const auto storageInfo = ifs.storages.find(storage);
802 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800803 return {};
804 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700805 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800806}
807
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800808int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
809 incfs::NewFileParams params) {
810 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700811 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800812 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700813 LOG(ERROR) << "Internal error: storageId " << storage
814 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800815 return -EINVAL;
816 }
817 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800818 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700819 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800820 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800821 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800822 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800823 }
824 return -EINVAL;
825}
826
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800827int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800828 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700829 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800830 if (normPath.empty()) {
831 return -EINVAL;
832 }
833 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800834 }
835 return -EINVAL;
836}
837
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800838int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800839 const auto ifs = getIfs(storageId);
840 if (!ifs) {
841 return -EINVAL;
842 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700843 return makeDirs(*ifs, storageId, path, mode);
844}
845
846int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
847 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800848 std::string normPath = normalizePathToStorage(ifs, storageId, path);
849 if (normPath.empty()) {
850 return -EINVAL;
851 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700852 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800853}
854
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800855int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
856 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700857 std::unique_lock l(mLock);
858 auto ifsSrc = getIfsLocked(sourceStorageId);
859 if (!ifsSrc) {
860 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800861 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700862 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
863 return -EINVAL;
864 }
865 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700866 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
867 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700868 if (normOldPath.empty() || normNewPath.empty()) {
869 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
870 return -EINVAL;
871 }
872 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800873}
874
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800875int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800876 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700877 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800878 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800879 }
880 return -EINVAL;
881}
882
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800883int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
884 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800885 std::string&& target, BindKind kind,
886 std::unique_lock<std::mutex>& mainLock) {
887 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700888 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800889 return -EINVAL;
890 }
891
892 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700893 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800894 if (kind != BindKind::Temporary) {
895 metadata::BindPoint bp;
896 bp.set_storage_id(storage);
897 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800898 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800899 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800900 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800901 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800902 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700903 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
904 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
905 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800906 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700907 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800908 return int(node);
909 }
910 }
911
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700912 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
913 std::move(target), kind, mainLock);
914 if (res) {
915 mIncFs->unlink(ifs.control, metadataFullPath);
916 }
917 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800918}
919
920int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800921 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800922 std::string&& target, BindKind kind,
923 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800924 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800925 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800926 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800927 if (!status.isOk()) {
928 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
929 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
930 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
931 : status.serviceSpecificErrorCode() == 0
932 ? -EFAULT
933 : status.serviceSpecificErrorCode()
934 : -EIO;
935 }
936 }
937
938 if (!mainLock.owns_lock()) {
939 mainLock.lock();
940 }
941 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700942 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
943 std::move(target), kind);
944 return 0;
945}
946
947void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
948 std::string&& metadataName, std::string&& source,
949 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800950 const auto [it, _] =
951 ifs.bindPoints.insert_or_assign(target,
952 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800953 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800954 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700955}
956
957RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
958 const auto ifs = getIfs(storage);
959 if (!ifs) {
960 return {};
961 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700962 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700963 if (normPath.empty()) {
964 return {};
965 }
966 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800967}
968
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800969RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800970 const auto ifs = getIfs(storage);
971 if (!ifs) {
972 return {};
973 }
974 return mIncFs->getMetadata(ifs->control, node);
975}
976
Songchun Fan3c82a302019-11-29 14:23:45 -0800977bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700978 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700979 {
980 std::unique_lock l(mLock);
981 const auto& ifs = getIfsLocked(storage);
982 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800983 return false;
984 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700985 dataLoaderStub = ifs->dataLoaderStub;
986 if (!dataLoaderStub) {
987 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700988 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800989 }
Alex Buynytskyy9a545792020-04-17 15:34:47 -0700990 dataLoaderStub->requestStart();
991 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -0800992}
993
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700994std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
995 std::unordered_set<std::string_view> mountedRootNames;
996 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
997 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
998 for (auto [source, target] : binds) {
999 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1000 LOG(INFO) << " " << path::join(root, source);
1001 }
1002
1003 // Ensure it's a kind of a mount that's managed by IncrementalService
1004 if (path::basename(root) != constants().mount ||
1005 path::basename(backingDir) != constants().backing) {
1006 return;
1007 }
1008 const auto expectedRoot = path::dirname(root);
1009 if (path::dirname(backingDir) != expectedRoot) {
1010 return;
1011 }
1012 if (path::dirname(expectedRoot) != mIncrementalDir) {
1013 return;
1014 }
1015 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1016 return;
1017 }
1018
1019 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1020
1021 // make sure we clean up the mount if it happens to be a bad one.
1022 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1023 auto cleanupFiles = makeCleanup([&]() {
1024 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1025 IncFsMount::cleanupFilesystem(expectedRoot);
1026 });
1027 auto cleanupMounts = makeCleanup([&]() {
1028 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1029 for (auto&& [_, target] : binds) {
1030 mVold->unmountIncFs(std::string(target));
1031 }
1032 mVold->unmountIncFs(std::string(root));
1033 });
1034
1035 auto control = mIncFs->openMount(root);
1036 if (!control) {
1037 LOG(INFO) << "failed to open mount " << root;
1038 return;
1039 }
1040
1041 auto mountRecord =
1042 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1043 path::join(root, constants().infoMdName));
1044 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1045 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1046 return;
1047 }
1048
1049 auto mountId = mountRecord.storage().id();
1050 mNextId = std::max(mNextId, mountId + 1);
1051
1052 DataLoaderParamsParcel dataLoaderParams;
1053 {
1054 const auto& loader = mountRecord.loader();
1055 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1056 dataLoaderParams.packageName = loader.package_name();
1057 dataLoaderParams.className = loader.class_name();
1058 dataLoaderParams.arguments = loader.arguments();
1059 }
1060
1061 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1062 std::move(control), *this);
1063 cleanupFiles.release(); // ifs will take care of that now
1064
1065 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1066 auto d = openDir(root);
1067 while (auto e = ::readdir(d.get())) {
1068 if (e->d_type == DT_REG) {
1069 auto name = std::string_view(e->d_name);
1070 if (name.starts_with(constants().mountpointMdPrefix)) {
1071 permanentBindPoints
1072 .emplace_back(name,
1073 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1074 ifs->control,
1075 path::join(root,
1076 name)));
1077 if (permanentBindPoints.back().second.dest_path().empty() ||
1078 permanentBindPoints.back().second.source_subdir().empty()) {
1079 permanentBindPoints.pop_back();
1080 mIncFs->unlink(ifs->control, path::join(root, name));
1081 } else {
1082 LOG(INFO) << "Permanent bind record: '"
1083 << permanentBindPoints.back().second.source_subdir() << "'->'"
1084 << permanentBindPoints.back().second.dest_path() << "'";
1085 }
1086 }
1087 } else if (e->d_type == DT_DIR) {
1088 if (e->d_name == "."sv || e->d_name == ".."sv) {
1089 continue;
1090 }
1091 auto name = std::string_view(e->d_name);
1092 if (name.starts_with(constants().storagePrefix)) {
1093 int storageId;
1094 const auto res =
1095 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1096 name.data() + name.size(), storageId);
1097 if (res.ec != std::errc{} || *res.ptr != '_') {
1098 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1099 << "' for mount " << expectedRoot;
1100 continue;
1101 }
1102 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1103 if (!inserted) {
1104 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1105 << " for mount " << expectedRoot;
1106 continue;
1107 }
1108 ifs->storages.insert_or_assign(storageId,
1109 IncFsMount::Storage{path::join(root, name)});
1110 mNextId = std::max(mNextId, storageId + 1);
1111 }
1112 }
1113 }
1114
1115 if (ifs->storages.empty()) {
1116 LOG(WARNING) << "No valid storages in mount " << root;
1117 return;
1118 }
1119
1120 // now match the mounted directories with what we expect to have in the metadata
1121 {
1122 std::unique_lock l(mLock, std::defer_lock);
1123 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1124 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1125 [&, bindRecord = bindRecord](auto&& bind) {
1126 return bind.second == bindRecord.dest_path() &&
1127 path::join(root, bind.first) ==
1128 bindRecord.source_subdir();
1129 });
1130 if (mountedIt != binds.end()) {
1131 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1132 << " to mount " << mountedIt->first;
1133 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1134 std::move(*bindRecord.mutable_source_subdir()),
1135 std::move(*bindRecord.mutable_dest_path()),
1136 BindKind::Permanent);
1137 if (mountedIt != binds.end() - 1) {
1138 std::iter_swap(mountedIt, binds.end() - 1);
1139 }
1140 binds = binds.first(binds.size() - 1);
1141 } else {
1142 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1143 << ", mounting";
1144 // doesn't exist - try mounting back
1145 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1146 std::move(*bindRecord.mutable_source_subdir()),
1147 std::move(*bindRecord.mutable_dest_path()),
1148 BindKind::Permanent, l)) {
1149 mIncFs->unlink(ifs->control, metadataFile);
1150 }
1151 }
1152 }
1153 }
1154
1155 // if anything stays in |binds| those are probably temporary binds; system restarted since
1156 // they were mounted - so let's unmount them all.
1157 for (auto&& [source, target] : binds) {
1158 if (source.empty()) {
1159 continue;
1160 }
1161 mVold->unmountIncFs(std::string(target));
1162 }
1163 cleanupMounts.release(); // ifs now manages everything
1164
1165 if (ifs->bindPoints.empty()) {
1166 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1167 deleteStorage(*ifs);
1168 return;
1169 }
1170
1171 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1172 CHECK(ifs->dataLoaderStub);
1173
1174 mountedRootNames.insert(path::basename(ifs->root));
1175
1176 // not locking here at all: we're still in the constructor, no other calls can happen
1177 mMounts[ifs->mountId] = std::move(ifs);
1178 });
1179
1180 return mountedRootNames;
1181}
1182
1183void IncrementalService::mountExistingImages(
1184 const std::unordered_set<std::string_view>& mountedRootNames) {
1185 auto dir = openDir(mIncrementalDir);
1186 if (!dir) {
1187 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1188 return;
1189 }
1190 while (auto entry = ::readdir(dir.get())) {
1191 if (entry->d_type != DT_DIR) {
1192 continue;
1193 }
1194 std::string_view name = entry->d_name;
1195 if (!name.starts_with(constants().mountKeyPrefix)) {
1196 continue;
1197 }
1198 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001199 continue;
1200 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001201 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001202 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001203 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001204 }
1205 }
1206}
1207
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001208bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001209 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001210 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001211
Songchun Fan3c82a302019-11-29 14:23:45 -08001212 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001213 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001214 if (!status.isOk()) {
1215 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1216 return false;
1217 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001218
1219 int cmd = controlParcel.cmd.release().release();
1220 int pendingReads = controlParcel.pendingReads.release().release();
1221 int logs = controlParcel.log.release().release();
1222 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001223
1224 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1225
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001226 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1227 path::join(mountTarget, constants().infoMdName));
1228 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001229 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1230 return false;
1231 }
1232
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001233 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001234 mNextId = std::max(mNextId, ifs->mountId + 1);
1235
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001236 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001237 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001238 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001239 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001240 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001241 dataLoaderParams.packageName = loader.package_name();
1242 dataLoaderParams.className = loader.class_name();
1243 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001244 }
1245
Alex Buynytskyy69941662020-04-11 21:40:37 -07001246 prepareDataLoader(*ifs, std::move(dataLoaderParams), nullptr);
1247 CHECK(ifs->dataLoaderStub);
1248
Songchun Fan3c82a302019-11-29 14:23:45 -08001249 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001250 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001251 while (auto e = ::readdir(d.get())) {
1252 if (e->d_type == DT_REG) {
1253 auto name = std::string_view(e->d_name);
1254 if (name.starts_with(constants().mountpointMdPrefix)) {
1255 bindPoints.emplace_back(name,
1256 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1257 ifs->control,
1258 path::join(mountTarget,
1259 name)));
1260 if (bindPoints.back().second.dest_path().empty() ||
1261 bindPoints.back().second.source_subdir().empty()) {
1262 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001263 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001264 }
1265 }
1266 } else if (e->d_type == DT_DIR) {
1267 if (e->d_name == "."sv || e->d_name == ".."sv) {
1268 continue;
1269 }
1270 auto name = std::string_view(e->d_name);
1271 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001272 int storageId;
1273 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1274 name.data() + name.size(), storageId);
1275 if (res.ec != std::errc{} || *res.ptr != '_') {
1276 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1277 << root;
1278 continue;
1279 }
1280 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001281 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001282 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001283 << " for mount " << root;
1284 continue;
1285 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001286 ifs->storages.insert_or_assign(storageId,
1287 IncFsMount::Storage{
1288 path::join(root, constants().mount, name)});
1289 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001290 }
1291 }
1292 }
1293
1294 if (ifs->storages.empty()) {
1295 LOG(WARNING) << "No valid storages in mount " << root;
1296 return false;
1297 }
1298
1299 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001300 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001301 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001302 for (auto&& bp : bindPoints) {
1303 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1304 std::move(*bp.second.mutable_source_subdir()),
1305 std::move(*bp.second.mutable_dest_path()),
1306 BindKind::Permanent, l);
1307 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001308 }
1309
1310 if (bindCount == 0) {
1311 LOG(WARNING) << "No valid bind points for mount " << root;
1312 deleteStorage(*ifs);
1313 return false;
1314 }
1315
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001316 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001317 mMounts[ifs->mountId] = std::move(ifs);
1318 return true;
1319}
1320
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001321IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001322 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001323 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001324 std::unique_lock l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001325 prepareDataLoaderLocked(ifs, std::move(params), externalListener);
1326 return ifs.dataLoaderStub;
1327}
1328
1329void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
1330 const DataLoaderStatusListener* externalListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001331 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001332 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001333 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001334 }
1335
Songchun Fan3c82a302019-11-29 14:23:45 -08001336 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001337 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001338 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1339 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1340 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001341 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001342
1343 ifs.dataLoaderStub = new DataLoaderStub(*this, ifs.mountId, std::move(params),
1344 std::move(fsControlParcel), externalListener);
Songchun Fan3c82a302019-11-29 14:23:45 -08001345}
1346
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001347template <class Duration>
1348static long elapsedMcs(Duration start, Duration end) {
1349 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1350}
1351
1352// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001353bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1354 std::string_view libDirRelativePath,
1355 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001356 auto start = Clock::now();
1357
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001358 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001359 if (!ifs) {
1360 LOG(ERROR) << "Invalid storage " << storage;
1361 return false;
1362 }
1363
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001364 // First prepare target directories if they don't exist yet
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001365 if (auto res = makeDirs(*ifs, storage, libDirRelativePath, 0755)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001366 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1367 << " errno: " << res;
1368 return false;
1369 }
1370
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001371 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001372 ZipArchiveHandle zipFileHandle;
1373 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001374 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1375 return false;
1376 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001377
1378 // Need a shared pointer: will be passing it into all unpacking jobs.
1379 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001380 void* cookie = nullptr;
1381 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001382 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001383 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1384 return false;
1385 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001386 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001387 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1388
1389 auto openZipTs = Clock::now();
1390
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001391 std::vector<Job> jobQueue;
1392 ZipEntry entry;
1393 std::string_view fileName;
1394 while (!Next(cookie, &entry, &fileName)) {
1395 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001396 continue;
1397 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001398
1399 auto startFileTs = Clock::now();
1400
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001401 const auto libName = path::basename(fileName);
Yurii Zubrytskyi510037b2020-04-22 15:46:21 -07001402 auto targetLibPath = path::join(libDirRelativePath, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001403 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001404 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001405 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001406 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001407 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1408 << "; skipping extraction, spent "
1409 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1410 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001411 continue;
1412 }
1413
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001414 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001415 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001416 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001417 .signature = {},
1418 // Metadata of the new lib file is its relative path
1419 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1420 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001421 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001422 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1423 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001424 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001425 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001426 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001427 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001428
1429 auto makeFileTs = Clock::now();
1430
Songchun Fanafaf6e92020-03-18 14:12:20 -07001431 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001432 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001433 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001434 LOG(INFO) << "incfs: Extracted " << libName
1435 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001436 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001437 continue;
1438 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001439
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001440 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1441 libFileId, libPath = std::move(targetLibPath),
1442 makeFileTs]() mutable {
1443 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001444 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001445
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001446 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001447 auto prepareJobTs = Clock::now();
1448 LOG(INFO) << "incfs: Processed " << libName << ": "
1449 << elapsedMcs(startFileTs, prepareJobTs)
1450 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1451 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001452 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001453 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001454
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001455 auto processedTs = Clock::now();
1456
1457 if (!jobQueue.empty()) {
1458 {
1459 std::lock_guard lock(mJobMutex);
1460 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001461 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001462 if (existingJobs.empty()) {
1463 existingJobs = std::move(jobQueue);
1464 } else {
1465 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1466 std::move_iterator(jobQueue.end()));
1467 }
1468 }
1469 }
1470 mJobCondition.notify_all();
1471 }
1472
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001473 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001474 auto end = Clock::now();
1475 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1476 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1477 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001478 << " make files: " << elapsedMcs(openZipTs, processedTs)
1479 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001480 }
1481
1482 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001483}
1484
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001485void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1486 ZipEntry& entry, const incfs::FileId& libFileId,
1487 std::string_view targetLibPath,
1488 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001489 if (!ifs) {
1490 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1491 return;
1492 }
1493
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001494 auto libName = path::basename(targetLibPath);
1495 auto startedTs = Clock::now();
1496
1497 // Write extracted data to new file
1498 // NOTE: don't zero-initialize memory, it may take a while for nothing
1499 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1500 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1501 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1502 return;
1503 }
1504
1505 auto extractFileTs = Clock::now();
1506
1507 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1508 if (!writeFd.ok()) {
1509 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1510 return;
1511 }
1512
1513 auto openFileTs = Clock::now();
1514 const int numBlocks =
1515 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1516 std::vector<IncFsDataBlock> instructions(numBlocks);
1517 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1518 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001519 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001520 instructions[i] = IncFsDataBlock{
1521 .fileFd = writeFd.get(),
1522 .pageIndex = static_cast<IncFsBlockIndex>(i),
1523 .compression = INCFS_COMPRESSION_KIND_NONE,
1524 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001525 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001526 .data = reinterpret_cast<const char*>(remainingData.data()),
1527 };
1528 remainingData = remainingData.subspan(blockSize);
1529 }
1530 auto prepareInstsTs = Clock::now();
1531
1532 size_t res = mIncFs->writeBlocks(instructions);
1533 if (res != instructions.size()) {
1534 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1535 return;
1536 }
1537
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001538 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001539 auto endFileTs = Clock::now();
1540 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1541 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1542 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1543 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1544 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1545 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1546 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1547 }
1548}
1549
1550bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001551 struct WaitPrinter {
1552 const Clock::time_point startTs = Clock::now();
1553 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001554 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001555 const auto endTs = Clock::now();
1556 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1557 << elapsedMcs(startTs, endTs) << "mcs";
1558 }
1559 }
1560 } waitPrinter;
1561
1562 MountId mount;
1563 {
1564 auto ifs = getIfs(storage);
1565 if (!ifs) {
1566 return true;
1567 }
1568 mount = ifs->mountId;
1569 }
1570
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001571 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001572 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001573 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001574 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001575 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001576 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001577}
1578
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001579bool IncrementalService::perfLoggingEnabled() {
1580 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1581 return enabled;
1582}
1583
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001584void IncrementalService::runJobProcessing() {
1585 for (;;) {
1586 std::unique_lock lock(mJobMutex);
1587 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1588 if (!mRunning) {
1589 return;
1590 }
1591
1592 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001593 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001594 auto queue = std::move(it->second);
1595 mJobQueue.erase(it);
1596 lock.unlock();
1597
1598 for (auto&& job : queue) {
1599 job();
1600 }
1601
1602 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001603 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001604 lock.unlock();
1605 mJobCondition.notify_all();
1606 }
1607}
1608
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001609void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001610 sp<IAppOpsCallback> listener;
1611 {
1612 std::unique_lock lock{mCallbacksLock};
1613 auto& cb = mCallbackRegistered[packageName];
1614 if (cb) {
1615 return;
1616 }
1617 cb = new AppOpsListener(*this, packageName);
1618 listener = cb;
1619 }
1620
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001621 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1622 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001623}
1624
1625bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1626 sp<IAppOpsCallback> listener;
1627 {
1628 std::unique_lock lock{mCallbacksLock};
1629 auto found = mCallbackRegistered.find(packageName);
1630 if (found == mCallbackRegistered.end()) {
1631 return false;
1632 }
1633 listener = found->second;
1634 mCallbackRegistered.erase(found);
1635 }
1636
1637 mAppOpsManager->stopWatchingMode(listener);
1638 return true;
1639}
1640
1641void IncrementalService::onAppOpChanged(const std::string& packageName) {
1642 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001643 return;
1644 }
1645
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001646 std::vector<IfsMountPtr> affected;
1647 {
1648 std::lock_guard l(mLock);
1649 affected.reserve(mMounts.size());
1650 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001651 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001652 affected.push_back(ifs);
1653 }
1654 }
1655 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001656 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001657 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001658 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001659}
1660
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001661IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1662 DataLoaderParamsParcel&& params,
1663 FileSystemControlParcel&& control,
1664 const DataLoaderStatusListener* externalListener)
1665 : mService(service),
1666 mId(id),
1667 mParams(std::move(params)),
1668 mControl(std::move(control)),
1669 mListener(externalListener ? *externalListener : DataLoaderStatusListener()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001670}
1671
Alex Buynytskyy9a545792020-04-17 15:34:47 -07001672IncrementalService::DataLoaderStub::~DataLoaderStub() = default;
1673
1674void IncrementalService::DataLoaderStub::cleanupResources() {
1675 requestDestroy();
1676 mParams = {};
1677 mControl = {};
1678 waitForStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED, std::chrono::seconds(60));
1679 mListener = {};
1680 mId = kInvalidStorageId;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001681}
1682
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001683sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1684 sp<IDataLoader> dataloader;
1685 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1686 if (!status.isOk()) {
1687 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1688 return {};
1689 }
1690 if (!dataloader) {
1691 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1692 return {};
1693 }
1694 return dataloader;
1695}
1696
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001697bool IncrementalService::DataLoaderStub::requestCreate() {
1698 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1699}
1700
1701bool IncrementalService::DataLoaderStub::requestStart() {
1702 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1703}
1704
1705bool IncrementalService::DataLoaderStub::requestDestroy() {
1706 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1707}
1708
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001709bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
1710 int oldStatus, curStatus;
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001711 {
1712 std::unique_lock lock(mStatusMutex);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001713 oldStatus = mTargetStatus;
1714 mTargetStatus = newStatus;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001715 mTargetStatusTs = Clock::now();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001716 curStatus = mCurrentStatus;
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001717 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001718 LOG(DEBUG) << "Target status update for DataLoader " << mId << ": " << oldStatus << " -> "
1719 << newStatus << " (current " << curStatus << ")";
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001720 return fsmStep();
1721}
1722
1723bool IncrementalService::DataLoaderStub::waitForStatus(int status, Clock::duration duration) {
1724 auto now = Clock::now();
1725 std::unique_lock lock(mStatusMutex);
1726 return mStatusCondition.wait_until(lock, now + duration,
1727 [this, status] { return mCurrentStatus == status; });
1728}
1729
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001730bool IncrementalService::DataLoaderStub::bind() {
1731 bool result = false;
1732 auto status = mService.mDataLoaderManager->bindToDataLoader(mId, mParams, this, &result);
1733 if (!status.isOk() || !result) {
1734 LOG(ERROR) << "Failed to bind a data loader for mount " << mId;
1735 return false;
1736 }
1737 return true;
1738}
1739
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001740bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001741 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001742 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001743 return false;
1744 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001745 auto status = dataloader->create(mId, mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001746 if (!status.isOk()) {
1747 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001748 return false;
1749 }
1750 return true;
1751}
1752
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001753bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001754 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001755 if (!dataloader) {
1756 return false;
1757 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001758 auto status = dataloader->start(mId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001759 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001760 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001761 return false;
1762 }
1763 return true;
1764}
1765
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001766bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001767 return mService.mDataLoaderManager->unbindFromDataLoader(mId).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001768}
1769
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001770bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a545792020-04-17 15:34:47 -07001771 if (!isValid()) {
1772 return false;
1773 }
1774
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001775 int currentStatus;
1776 int targetStatus;
1777 {
1778 std::unique_lock lock(mStatusMutex);
1779 currentStatus = mCurrentStatus;
1780 targetStatus = mTargetStatus;
1781 }
1782
1783 if (currentStatus == targetStatus) {
1784 return true;
1785 }
1786
1787 switch (targetStatus) {
1788 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1789 return destroy();
1790 }
1791 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1792 switch (currentStatus) {
1793 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1794 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1795 return start();
1796 }
1797 // fallthrough
1798 }
1799 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1800 switch (currentStatus) {
1801 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001802 return bind();
1803 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001804 return create();
1805 }
1806 break;
1807 default:
1808 LOG(ERROR) << "Invalid target status: " << targetStatus
1809 << ", current status: " << currentStatus;
1810 break;
1811 }
1812 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001813}
1814
1815binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a545792020-04-17 15:34:47 -07001816 if (!isValid()) {
1817 return binder::Status::
1818 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
1819 }
1820 if (mId != mountId) {
1821 LOG(ERROR) << "Mount ID mismatch: expected " << mId << ", but got: " << mountId;
1822 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
1823 }
1824
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001825 int targetStatus, oldStatus;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001826 {
1827 std::unique_lock lock(mStatusMutex);
1828 if (mCurrentStatus == newStatus) {
1829 return binder::Status::ok();
1830 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001831 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001832 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001833 targetStatus = mTargetStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001834 }
1835
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001836 LOG(DEBUG) << "Current status update for DataLoader " << mId << ": " << oldStatus << " -> "
1837 << newStatus << " (target " << targetStatus << ")";
1838
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001839 if (mListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001840 mListener->onStatusChanged(mountId, newStatus);
1841 }
1842
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001843 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08001844
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07001845 mStatusCondition.notify_all();
1846
Songchun Fan3c82a302019-11-29 14:23:45 -08001847 return binder::Status::ok();
1848}
1849
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001850void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001851 dprintf(fd, " dataLoader: {\n");
1852 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
1853 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
1854 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001855 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
1856 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001857 dprintf(fd, " dataLoaderParams: {\n");
1858 dprintf(fd, " type: %s\n", toString(params.type).c_str());
1859 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
1860 dprintf(fd, " className: %s\n", params.className.c_str());
1861 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
1862 dprintf(fd, " }\n");
1863 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001864}
1865
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001866void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1867 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001868}
1869
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001870binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1871 bool enableReadLogs, int32_t* _aidl_return) {
1872 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1873 return binder::Status::ok();
1874}
1875
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001876FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
1877 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
1878}
1879
Songchun Fan3c82a302019-11-29 14:23:45 -08001880} // namespace android::incremental