blob: 79699bb77a92b882be22796cf26a1b592a86b304 [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
21#include <android-base/file.h>
22#include <android-base/logging.h>
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -070023#include <android-base/no_destructor.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080024#include <android-base/properties.h>
25#include <android-base/stringprintf.h>
26#include <android-base/strings.h>
27#include <android/content/pm/IDataLoaderStatusListener.h>
28#include <android/os/IVold.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080029#include <binder/BinderService.h>
Jooyung Han66c567a2020-03-07 21:47:09 +090030#include <binder/Nullable.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080031#include <binder/ParcelFileDescriptor.h>
32#include <binder/Status.h>
33#include <sys/stat.h>
34#include <uuid/uuid.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080035
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070036#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080037#include <ctime>
Songchun Fan1124fd32020-02-10 12:49:41 -080038#include <filesystem>
Songchun Fan3c82a302019-11-29 14:23:45 -080039#include <iterator>
40#include <span>
Songchun Fan3c82a302019-11-29 14:23:45 -080041#include <type_traits>
42
43#include "Metadata.pb.h"
44
45using namespace std::literals;
46using namespace android::content::pm;
Songchun Fan1124fd32020-02-10 12:49:41 -080047namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080048
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070049constexpr const char* kDataUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070050constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070051
Songchun Fan3c82a302019-11-29 14:23:45 -080052namespace android::incremental {
53
54namespace {
55
56using IncrementalFileSystemControlParcel =
57 ::android::os::incremental::IncrementalFileSystemControlParcel;
58
59struct Constants {
60 static constexpr auto backing = "backing_store"sv;
61 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080062 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080063 static constexpr auto storagePrefix = "st"sv;
64 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
65 static constexpr auto infoMdName = ".info"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080066 static constexpr auto libDir = "lib"sv;
67 static constexpr auto libSuffix = ".so"sv;
68 static constexpr auto blockSize = 4096;
Songchun Fan3c82a302019-11-29 14:23:45 -080069};
70
71static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070072 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080073 return c;
74}
75
76template <base::LogSeverity level = base::ERROR>
77bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
78 auto cstr = path::c_str(name);
79 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080080 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080081 PLOG(level) << "Can't create directory '" << name << '\'';
82 return false;
83 }
84 struct stat st;
85 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
86 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
87 return false;
88 }
89 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080090 if (::chmod(cstr, mode)) {
91 PLOG(level) << "Changing permission failed for '" << name << '\'';
92 return false;
93 }
94
Songchun Fan3c82a302019-11-29 14:23:45 -080095 return true;
96}
97
98static std::string toMountKey(std::string_view path) {
99 if (path.empty()) {
100 return "@none";
101 }
102 if (path == "/"sv) {
103 return "@root";
104 }
105 if (path::isAbsolute(path)) {
106 path.remove_prefix(1);
107 }
108 std::string res(path);
109 std::replace(res.begin(), res.end(), '/', '_');
110 std::replace(res.begin(), res.end(), '@', '_');
Songchun Fan1124fd32020-02-10 12:49:41 -0800111 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
128template <class ProtoMessage, class Control>
129static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, Control&& control,
130 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800131 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800132 ProtoMessage message;
133 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
134}
135
136static bool isValidMountTarget(std::string_view path) {
137 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
138}
139
140std::string makeBindMdName() {
141 static constexpr auto uuidStringSize = 36;
142
143 uuid_t guid;
144 uuid_generate(guid);
145
146 std::string name;
147 const auto prefixSize = constants().mountpointMdPrefix.size();
148 name.reserve(prefixSize + uuidStringSize);
149
150 name = constants().mountpointMdPrefix;
151 name.resize(prefixSize + uuidStringSize);
152 uuid_unparse(guid, name.data() + prefixSize);
153
154 return name;
155}
156} // namespace
157
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700158const bool IncrementalService::sEnablePerfLogging =
159 android::base::GetBoolProperty("incremental.perflogging", false);
160
Songchun Fan3c82a302019-11-29 14:23:45 -0800161IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700162 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700163 dataLoaderStub->cleanupResources();
164 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700165 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800166 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
167 for (auto&& [target, _] : bindPoints) {
168 LOG(INFO) << "\tbind: " << target;
169 incrementalService.mVold->unmountIncFs(target);
170 }
171 LOG(INFO) << "\troot: " << root;
172 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
173 cleanupFilesystem(root);
174}
175
176auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800177 std::string name;
178 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
179 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
180 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800181 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
182 constants().storagePrefix.data(), id, no);
183 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800184 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800185 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800186 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
187 } else if (err != EEXIST) {
188 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
189 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800190 }
191 }
192 nextStorageDirNo = 0;
193 return storages.end();
194}
195
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800196static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* path) {
197 return {::opendir(path), ::closedir};
198}
199
200static int rmDirContent(const char* path) {
201 auto dir = openDir(path);
202 if (!dir) {
203 return -EINVAL;
204 }
205 while (auto entry = ::readdir(dir.get())) {
206 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
207 continue;
208 }
209 auto fullPath = android::base::StringPrintf("%s/%s", path, entry->d_name);
210 if (entry->d_type == DT_DIR) {
211 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
212 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
213 return err;
214 }
215 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
216 PLOG(WARNING) << "Failed to rmdir " << fullPath;
217 return err;
218 }
219 } else {
220 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
221 PLOG(WARNING) << "Failed to delete " << fullPath;
222 return err;
223 }
224 }
225 }
226 return 0;
227}
228
Songchun Fan3c82a302019-11-29 14:23:45 -0800229void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800230 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800231 ::rmdir(path::join(root, constants().backing).c_str());
232 ::rmdir(path::join(root, constants().mount).c_str());
233 ::rmdir(path::c_str(root));
234}
235
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800236IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800237 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800238 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800239 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700240 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700241 mJni(sm.getJni()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800242 mIncrementalDir(rootDir) {
243 if (!mVold) {
244 LOG(FATAL) << "Vold service is unavailable";
245 }
Songchun Fan68645c42020-02-27 15:57:35 -0800246 if (!mDataLoaderManager) {
247 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800248 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700249 if (!mAppOpsManager) {
250 LOG(FATAL) << "AppOpsManager is unavailable";
251 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700252
253 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700254 mJobProcessor = std::thread([this]() {
255 mJni->initializeForCurrentThread();
256 runJobProcessing();
257 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700258
Songchun Fan1124fd32020-02-10 12:49:41 -0800259 mountExistingImages();
Songchun Fan3c82a302019-11-29 14:23:45 -0800260}
261
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700262IncrementalService::~IncrementalService() {
263 {
264 std::lock_guard lock(mJobMutex);
265 mRunning = false;
266 }
267 mJobCondition.notify_all();
268 mJobProcessor.join();
269}
Songchun Fan3c82a302019-11-29 14:23:45 -0800270
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800271inline const char* toString(TimePoint t) {
272 using SystemClock = std::chrono::system_clock;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800273 time_t time = SystemClock::to_time_t(
274 SystemClock::now() +
275 std::chrono::duration_cast<SystemClock::duration>(t - Clock::now()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800276 return std::ctime(&time);
277}
278
279inline const char* toString(IncrementalService::BindKind kind) {
280 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800281 case IncrementalService::BindKind::Temporary:
282 return "Temporary";
283 case IncrementalService::BindKind::Permanent:
284 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800285 }
286}
287
288void IncrementalService::onDump(int fd) {
289 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
290 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
291
292 std::unique_lock l(mLock);
293
294 dprintf(fd, "Mounts (%d):\n", int(mMounts.size()));
295 for (auto&& [id, ifs] : mMounts) {
296 const IncFsMount& mnt = *ifs.get();
297 dprintf(fd, "\t[%d]:\n", id);
298 dprintf(fd, "\t\tmountId: %d\n", mnt.mountId);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -0700299 dprintf(fd, "\t\troot: %s\n", mnt.root.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800300 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700301 if (mnt.dataLoaderStub) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700302 mnt.dataLoaderStub->onDump(fd);
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800303 }
304 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
305 for (auto&& [storageId, storage] : mnt.storages) {
306 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
307 }
308
309 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
310 for (auto&& [target, bind] : mnt.bindPoints) {
311 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
312 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
313 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
314 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
315 }
316 }
317
318 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
319 for (auto&& [target, mountPairIt] : mBindsByPath) {
320 const auto& bind = mountPairIt->second;
321 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
322 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
323 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
324 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
325 }
326}
327
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700328void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800329 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700330 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800331 }
332
333 std::vector<IfsMountPtr> mounts;
334 {
335 std::lock_guard l(mLock);
336 mounts.reserve(mMounts.size());
337 for (auto&& [id, ifs] : mMounts) {
338 if (ifs->mountId == id) {
339 mounts.push_back(ifs);
340 }
341 }
342 }
343
Alex Buynytskyy69941662020-04-11 21:40:37 -0700344 if (mounts.empty()) {
345 return;
346 }
347
Songchun Fan3c82a302019-11-29 14:23:45 -0800348 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700349 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800350 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700351 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800352 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800353 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800354}
355
356auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
357 for (;;) {
358 if (mNextId == kMaxStorageId) {
359 mNextId = 0;
360 }
361 auto id = ++mNextId;
362 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
363 if (inserted) {
364 return it;
365 }
366 }
367}
368
Songchun Fan1124fd32020-02-10 12:49:41 -0800369StorageId IncrementalService::createStorage(
370 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
371 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800372 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
373 if (!path::isAbsolute(mountPoint)) {
374 LOG(ERROR) << "path is not absolute: " << mountPoint;
375 return kInvalidStorageId;
376 }
377
378 auto mountNorm = path::normalize(mountPoint);
379 {
380 const auto id = findStorageId(mountNorm);
381 if (id != kInvalidStorageId) {
382 if (options & CreateOptions::OpenExisting) {
383 LOG(INFO) << "Opened existing storage " << id;
384 return id;
385 }
386 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
387 return kInvalidStorageId;
388 }
389 }
390
391 if (!(options & CreateOptions::CreateNew)) {
392 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
393 return kInvalidStorageId;
394 }
395
396 if (!path::isEmptyDir(mountNorm)) {
397 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
398 return kInvalidStorageId;
399 }
400 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
401 if (mountRoot.empty()) {
402 LOG(ERROR) << "Bad mount point";
403 return kInvalidStorageId;
404 }
405 // Make sure the code removes all crap it may create while still failing.
406 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
407 auto firstCleanupOnFailure =
408 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
409
410 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800411 const auto backing = path::join(mountRoot, constants().backing);
412 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800413 return kInvalidStorageId;
414 }
415
Songchun Fan3c82a302019-11-29 14:23:45 -0800416 IncFsMount::Control control;
417 {
418 std::lock_guard l(mMountOperationLock);
419 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800420
421 if (auto err = rmDirContent(backing.c_str())) {
422 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
423 return kInvalidStorageId;
424 }
425 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
426 return kInvalidStorageId;
427 }
428 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800429 if (!status.isOk()) {
430 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
431 return kInvalidStorageId;
432 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800433 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
434 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800435 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
436 return kInvalidStorageId;
437 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800438 int cmd = controlParcel.cmd.release().release();
439 int pendingReads = controlParcel.pendingReads.release().release();
440 int logs = controlParcel.log.release().release();
441 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800442 }
443
444 std::unique_lock l(mLock);
445 const auto mountIt = getStorageSlotLocked();
446 const auto mountId = mountIt->first;
447 l.unlock();
448
449 auto ifs =
450 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
451 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
452 // is the removal of the |ifs|.
453 firstCleanupOnFailure.release();
454
455 auto secondCleanup = [this, &l](auto itPtr) {
456 if (!l.owns_lock()) {
457 l.lock();
458 }
459 mMounts.erase(*itPtr);
460 };
461 auto secondCleanupOnFailure =
462 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
463
464 const auto storageIt = ifs->makeStorage(ifs->mountId);
465 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800466 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800467 return kInvalidStorageId;
468 }
469
470 {
471 metadata::Mount m;
472 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700473 m.mutable_loader()->set_type((int)dataLoaderParams.type);
474 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
475 m.mutable_loader()->set_class_name(dataLoaderParams.className);
476 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800477 const auto metadata = m.SerializeAsString();
478 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800479 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800480 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800481 if (auto err =
482 mIncFs->makeFile(ifs->control,
483 path::join(ifs->root, constants().mount,
484 constants().infoMdName),
485 0777, idFromMetadata(metadata),
486 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800487 LOG(ERROR) << "Saving mount metadata failed: " << -err;
488 return kInvalidStorageId;
489 }
490 }
491
492 const auto bk =
493 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800494 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
495 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800496 err < 0) {
497 LOG(ERROR) << "adding bind mount failed: " << -err;
498 return kInvalidStorageId;
499 }
500
501 // Done here as well, all data structures are in good state.
502 secondCleanupOnFailure.release();
503
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700504 auto dataLoaderStub =
505 prepareDataLoader(*ifs, std::move(dataLoaderParams), &dataLoaderStatusListener);
506 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800507
508 mountIt->second = std::move(ifs);
509 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700510
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700511 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700512 // failed to create data loader
513 LOG(ERROR) << "initializeDataLoader() failed";
514 deleteStorage(dataLoaderStub->id());
515 return kInvalidStorageId;
516 }
517
Songchun Fan3c82a302019-11-29 14:23:45 -0800518 LOG(INFO) << "created storage " << mountId;
519 return mountId;
520}
521
522StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
523 StorageId linkedStorage,
524 IncrementalService::CreateOptions options) {
525 if (!isValidMountTarget(mountPoint)) {
526 LOG(ERROR) << "Mount point is invalid or missing";
527 return kInvalidStorageId;
528 }
529
530 std::unique_lock l(mLock);
531 const auto& ifs = getIfsLocked(linkedStorage);
532 if (!ifs) {
533 LOG(ERROR) << "Ifs unavailable";
534 return kInvalidStorageId;
535 }
536
537 const auto mountIt = getStorageSlotLocked();
538 const auto storageId = mountIt->first;
539 const auto storageIt = ifs->makeStorage(storageId);
540 if (storageIt == ifs->storages.end()) {
541 LOG(ERROR) << "Can't create a new storage";
542 mMounts.erase(mountIt);
543 return kInvalidStorageId;
544 }
545
546 l.unlock();
547
548 const auto bk =
549 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800550 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
551 std::string(storageIt->second.name), path::normalize(mountPoint),
552 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800553 err < 0) {
554 LOG(ERROR) << "bindMount failed with error: " << err;
555 return kInvalidStorageId;
556 }
557
558 mountIt->second = ifs;
559 return storageId;
560}
561
562IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
563 std::string_view path) const {
564 auto bindPointIt = mBindsByPath.upper_bound(path);
565 if (bindPointIt == mBindsByPath.begin()) {
566 return mBindsByPath.end();
567 }
568 --bindPointIt;
569 if (!path::startsWith(path, bindPointIt->first)) {
570 return mBindsByPath.end();
571 }
572 return bindPointIt;
573}
574
575StorageId IncrementalService::findStorageId(std::string_view path) const {
576 std::lock_guard l(mLock);
577 auto it = findStorageLocked(path);
578 if (it == mBindsByPath.end()) {
579 return kInvalidStorageId;
580 }
581 return it->second->second.storage;
582}
583
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700584int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
585 const auto ifs = getIfs(storageId);
586 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700587 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700588 return -EINVAL;
589 }
590
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700591 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700592 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700593 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
594 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700595 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700596 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700597 return fromBinderStatus(status);
598 }
599 }
600
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700601 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
602 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
603 return fromBinderStatus(status);
604 }
605
606 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700607 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700608 }
609
610 return 0;
611}
612
613binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700614 using unique_fd = ::android::base::unique_fd;
615 ::android::os::incremental::IncrementalFileSystemControlParcel control;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700616 control.cmd.reset(unique_fd(dup(ifs.control.cmd())));
617 control.pendingReads.reset(unique_fd(dup(ifs.control.pendingReads())));
618 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700619 if (logsFd >= 0) {
620 control.log.reset(unique_fd(dup(logsFd)));
621 }
622
623 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700624 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700625}
626
Songchun Fan3c82a302019-11-29 14:23:45 -0800627void IncrementalService::deleteStorage(StorageId storageId) {
628 const auto ifs = getIfs(storageId);
629 if (!ifs) {
630 return;
631 }
632 deleteStorage(*ifs);
633}
634
635void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
636 std::unique_lock l(ifs.lock);
637 deleteStorageLocked(ifs, std::move(l));
638}
639
640void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
641 std::unique_lock<std::mutex>&& ifsLock) {
642 const auto storages = std::move(ifs.storages);
643 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
644 const auto bindPoints = ifs.bindPoints;
645 ifsLock.unlock();
646
647 std::lock_guard l(mLock);
648 for (auto&& [id, _] : storages) {
649 if (id != ifs.mountId) {
650 mMounts.erase(id);
651 }
652 }
653 for (auto&& [path, _] : bindPoints) {
654 mBindsByPath.erase(path);
655 }
656 mMounts.erase(ifs.mountId);
657}
658
659StorageId IncrementalService::openStorage(std::string_view pathInMount) {
660 if (!path::isAbsolute(pathInMount)) {
661 return kInvalidStorageId;
662 }
663
664 return findStorageId(path::normalize(pathInMount));
665}
666
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800667FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800668 const auto ifs = getIfs(storage);
669 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800670 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800671 }
672 std::unique_lock l(ifs->lock);
673 auto storageIt = ifs->storages.find(storage);
674 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800675 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800676 }
677 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800678 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800679 }
680 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
681 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800682 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800683}
684
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800685std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800686 StorageId storage, std::string_view subpath) const {
687 auto name = path::basename(subpath);
688 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800689 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800690 }
691 auto dir = path::dirname(subpath);
692 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800693 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800694 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800695 auto id = nodeFor(storage, dir);
696 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800697}
698
699IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
700 std::lock_guard l(mLock);
701 return getIfsLocked(storage);
702}
703
704const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
705 auto it = mMounts.find(storage);
706 if (it == mMounts.end()) {
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700707 static const android::base::NoDestructor<IfsMountPtr> kEmpty{};
708 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800709 }
710 return it->second;
711}
712
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800713int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
714 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800715 if (!isValidMountTarget(target)) {
716 return -EINVAL;
717 }
718
719 const auto ifs = getIfs(storage);
720 if (!ifs) {
721 return -EINVAL;
722 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800723
Songchun Fan3c82a302019-11-29 14:23:45 -0800724 std::unique_lock l(ifs->lock);
725 const auto storageInfo = ifs->storages.find(storage);
726 if (storageInfo == ifs->storages.end()) {
727 return -EINVAL;
728 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700729 std::string normSource = normalizePathToStorageLocked(storageInfo, source);
730 if (normSource.empty()) {
731 return -EINVAL;
732 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800733 l.unlock();
734 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800735 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
736 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800737}
738
739int IncrementalService::unbind(StorageId storage, std::string_view target) {
740 if (!path::isAbsolute(target)) {
741 return -EINVAL;
742 }
743
744 LOG(INFO) << "Removing bind point " << target;
745
746 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
747 // otherwise there's a chance to unmount something completely unrelated
748 const auto norm = path::normalize(target);
749 std::unique_lock l(mLock);
750 const auto storageIt = mBindsByPath.find(norm);
751 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
752 return -EINVAL;
753 }
754 const auto bindIt = storageIt->second;
755 const auto storageId = bindIt->second.storage;
756 const auto ifs = getIfsLocked(storageId);
757 if (!ifs) {
758 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
759 << " is missing";
760 return -EFAULT;
761 }
762 mBindsByPath.erase(storageIt);
763 l.unlock();
764
765 mVold->unmountIncFs(bindIt->first);
766 std::unique_lock l2(ifs->lock);
767 if (ifs->bindPoints.size() <= 1) {
768 ifs->bindPoints.clear();
769 deleteStorageLocked(*ifs, std::move(l2));
770 } else {
771 const std::string savedFile = std::move(bindIt->second.savedFilename);
772 ifs->bindPoints.erase(bindIt);
773 l2.unlock();
774 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800775 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800776 }
777 }
778 return 0;
779}
780
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700781std::string IncrementalService::normalizePathToStorageLocked(
782 IncFsMount::StorageMap::iterator storageIt, std::string_view path) {
783 std::string normPath;
784 if (path::isAbsolute(path)) {
785 normPath = path::normalize(path);
786 if (!path::startsWith(normPath, storageIt->second.name)) {
787 return {};
788 }
789 } else {
790 normPath = path::normalize(path::join(storageIt->second.name, path));
791 }
792 return normPath;
793}
794
795std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr& ifs,
Songchun Fan103ba1d2020-02-03 17:32:32 -0800796 StorageId storage, std::string_view path) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700797 std::unique_lock l(ifs->lock);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800798 const auto storageInfo = ifs->storages.find(storage);
799 if (storageInfo == ifs->storages.end()) {
800 return {};
801 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700802 return normalizePathToStorageLocked(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)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800808 std::string normPath = normalizePathToStorage(ifs, storage, path);
809 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)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800826 std::string normPath = normalizePathToStorage(ifs, storageId, path);
827 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 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800840 std::string normPath = normalizePathToStorage(ifs, storageId, path);
841 if (normPath.empty()) {
842 return -EINVAL;
843 }
844 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800845 if (err == -EEXIST) {
846 return 0;
847 } else if (err != -ENOENT) {
848 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800849 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800850 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800851 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800852 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800853 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800854}
855
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800856int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
857 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700858 auto ifsSrc = getIfs(sourceStorageId);
859 auto ifsDest = sourceStorageId == destStorageId ? ifsSrc : getIfs(destStorageId);
860 if (ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800861 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
862 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
863 if (normOldPath.empty() || normNewPath.empty()) {
864 return -EINVAL;
865 }
866 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800867 }
868 return -EINVAL;
869}
870
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800871int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800872 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800873 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
874 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800875 }
876 return -EINVAL;
877}
878
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800879int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
880 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800881 std::string&& target, BindKind kind,
882 std::unique_lock<std::mutex>& mainLock) {
883 if (!isValidMountTarget(target)) {
884 return -EINVAL;
885 }
886
887 std::string mdFileName;
888 if (kind != BindKind::Temporary) {
889 metadata::BindPoint bp;
890 bp.set_storage_id(storage);
891 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800892 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800893 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800894 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800895 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800896 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800897 auto node =
898 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
899 0444, idFromMetadata(metadata),
900 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
901 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800902 return int(node);
903 }
904 }
905
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800906 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800907 std::move(target), kind, mainLock);
908}
909
910int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800911 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800912 std::string&& target, BindKind kind,
913 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800914 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800915 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800916 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800917 if (!status.isOk()) {
918 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
919 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
920 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
921 : status.serviceSpecificErrorCode() == 0
922 ? -EFAULT
923 : status.serviceSpecificErrorCode()
924 : -EIO;
925 }
926 }
927
928 if (!mainLock.owns_lock()) {
929 mainLock.lock();
930 }
931 std::lock_guard l(ifs.lock);
932 const auto [it, _] =
933 ifs.bindPoints.insert_or_assign(target,
934 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800935 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800936 mBindsByPath[std::move(target)] = it;
937 return 0;
938}
939
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800940RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800941 const auto ifs = getIfs(storage);
942 if (!ifs) {
943 return {};
944 }
945 return mIncFs->getMetadata(ifs->control, node);
946}
947
948std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
949 const auto ifs = getIfs(storage);
950 if (!ifs) {
951 return {};
952 }
953
954 std::unique_lock l(ifs->lock);
955 auto subdirIt = ifs->storages.find(storage);
956 if (subdirIt == ifs->storages.end()) {
957 return {};
958 }
959 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
960 l.unlock();
961
962 const auto prefixSize = dir.size() + 1;
963 std::vector<std::string> todoDirs{std::move(dir)};
964 std::vector<std::string> result;
965 do {
966 auto currDir = std::move(todoDirs.back());
967 todoDirs.pop_back();
968
969 auto d =
970 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
971 while (auto e = ::readdir(d.get())) {
972 if (e->d_type == DT_REG) {
973 result.emplace_back(
974 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
975 continue;
976 }
977 if (e->d_type == DT_DIR) {
978 if (e->d_name == "."sv || e->d_name == ".."sv) {
979 continue;
980 }
981 todoDirs.emplace_back(path::join(currDir, e->d_name));
982 continue;
983 }
984 }
985 } while (!todoDirs.empty());
986 return result;
987}
988
989bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700990 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700991 {
992 std::unique_lock l(mLock);
993 const auto& ifs = getIfsLocked(storage);
994 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800995 return false;
996 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700997 dataLoaderStub = ifs->dataLoaderStub;
998 if (!dataLoaderStub) {
999 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001000 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001001 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001002 dataLoaderStub->requestStart();
1003 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001004}
1005
1006void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -08001007 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
1008 const auto path = entry.path().u8string();
1009 const auto name = entry.path().filename().u8string();
1010 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001011 continue;
1012 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001013 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001014 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -08001015 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -08001016 }
1017 }
1018}
1019
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001020bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001021 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001022 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001023
Songchun Fan3c82a302019-11-29 14:23:45 -08001024 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001025 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001026 if (!status.isOk()) {
1027 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1028 return false;
1029 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001030
1031 int cmd = controlParcel.cmd.release().release();
1032 int pendingReads = controlParcel.pendingReads.release().release();
1033 int logs = controlParcel.log.release().release();
1034 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001035
1036 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1037
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001038 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1039 path::join(mountTarget, constants().infoMdName));
1040 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001041 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1042 return false;
1043 }
1044
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001045 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001046 mNextId = std::max(mNextId, ifs->mountId + 1);
1047
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001048 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001049 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001050 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001051 const auto& loader = mount.loader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001052 dataLoaderParams.type = (android::content::pm::DataLoaderType)loader.type();
1053 dataLoaderParams.packageName = loader.package_name();
1054 dataLoaderParams.className = loader.class_name();
1055 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001056 }
1057
Alex Buynytskyy69941662020-04-11 21:40:37 -07001058 prepareDataLoader(*ifs, std::move(dataLoaderParams), nullptr);
1059 CHECK(ifs->dataLoaderStub);
1060
Songchun Fan3c82a302019-11-29 14:23:45 -08001061 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001062 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001063 while (auto e = ::readdir(d.get())) {
1064 if (e->d_type == DT_REG) {
1065 auto name = std::string_view(e->d_name);
1066 if (name.starts_with(constants().mountpointMdPrefix)) {
1067 bindPoints.emplace_back(name,
1068 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1069 ifs->control,
1070 path::join(mountTarget,
1071 name)));
1072 if (bindPoints.back().second.dest_path().empty() ||
1073 bindPoints.back().second.source_subdir().empty()) {
1074 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001075 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001076 }
1077 }
1078 } else if (e->d_type == DT_DIR) {
1079 if (e->d_name == "."sv || e->d_name == ".."sv) {
1080 continue;
1081 }
1082 auto name = std::string_view(e->d_name);
1083 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001084 int storageId;
1085 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1086 name.data() + name.size(), storageId);
1087 if (res.ec != std::errc{} || *res.ptr != '_') {
1088 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1089 << root;
1090 continue;
1091 }
1092 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001093 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001094 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001095 << " for mount " << root;
1096 continue;
1097 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001098 ifs->storages.insert_or_assign(storageId,
1099 IncFsMount::Storage{
1100 path::join(root, constants().mount, name)});
1101 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001102 }
1103 }
1104 }
1105
1106 if (ifs->storages.empty()) {
1107 LOG(WARNING) << "No valid storages in mount " << root;
1108 return false;
1109 }
1110
1111 int bindCount = 0;
1112 for (auto&& bp : bindPoints) {
1113 std::unique_lock l(mLock, std::defer_lock);
1114 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1115 std::move(*bp.second.mutable_source_subdir()),
1116 std::move(*bp.second.mutable_dest_path()),
1117 BindKind::Permanent, l);
1118 }
1119
1120 if (bindCount == 0) {
1121 LOG(WARNING) << "No valid bind points for mount " << root;
1122 deleteStorage(*ifs);
1123 return false;
1124 }
1125
Songchun Fan3c82a302019-11-29 14:23:45 -08001126 mMounts[ifs->mountId] = std::move(ifs);
1127 return true;
1128}
1129
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001130IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
1131 IncrementalService::IncFsMount& ifs, DataLoaderParamsParcel&& params,
1132 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001133 std::unique_lock l(ifs.lock);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001134 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001135 LOG(INFO) << "Skipped data loader preparation because it already exists";
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001136 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001137 }
1138
Songchun Fan3c82a302019-11-29 14:23:45 -08001139 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001140 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001141 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001142 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001143 base::unique_fd(::dup(ifs.control.pendingReads())));
1144 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001145 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001146
1147 ifs.dataLoaderStub = new DataLoaderStub(*this, ifs.mountId, std::move(params),
1148 std::move(fsControlParcel), externalListener);
1149 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001150}
1151
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001152template <class Duration>
1153static long elapsedMcs(Duration start, Duration end) {
1154 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1155}
1156
1157// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001158bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1159 std::string_view libDirRelativePath,
1160 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001161 auto start = Clock::now();
1162
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001163 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001164 if (!ifs) {
1165 LOG(ERROR) << "Invalid storage " << storage;
1166 return false;
1167 }
1168
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001169 // First prepare target directories if they don't exist yet
1170 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1171 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1172 << " errno: " << res;
1173 return false;
1174 }
1175
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001176 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001177 ZipArchiveHandle zipFileHandle;
1178 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001179 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1180 return false;
1181 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001182
1183 // Need a shared pointer: will be passing it into all unpacking jobs.
1184 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001185 void* cookie = nullptr;
1186 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001187 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001188 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1189 return false;
1190 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001191 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001192 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1193
1194 auto openZipTs = Clock::now();
1195
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001196 std::vector<Job> jobQueue;
1197 ZipEntry entry;
1198 std::string_view fileName;
1199 while (!Next(cookie, &entry, &fileName)) {
1200 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001201 continue;
1202 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001203
1204 auto startFileTs = Clock::now();
1205
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001206 const auto libName = path::basename(fileName);
1207 const auto targetLibPath = path::join(libDirRelativePath, libName);
1208 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1209 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001210 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
1211 if (sEnablePerfLogging) {
1212 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1213 << "; skipping extraction, spent "
1214 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1215 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001216 continue;
1217 }
1218
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001219 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001220 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001221 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001222 .signature = {},
1223 // Metadata of the new lib file is its relative path
1224 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1225 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001226 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001227 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1228 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001229 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001230 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001231 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001232 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001233
1234 auto makeFileTs = Clock::now();
1235
Songchun Fanafaf6e92020-03-18 14:12:20 -07001236 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001237 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001238 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001239 LOG(INFO) << "incfs: Extracted " << libName
1240 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001241 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001242 continue;
1243 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001244
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001245 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1246 libFileId, libPath = std::move(targetLibPath),
1247 makeFileTs]() mutable {
1248 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001249 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001250
1251 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001252 auto prepareJobTs = Clock::now();
1253 LOG(INFO) << "incfs: Processed " << libName << ": "
1254 << elapsedMcs(startFileTs, prepareJobTs)
1255 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1256 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001257 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001258 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001259
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001260 auto processedTs = Clock::now();
1261
1262 if (!jobQueue.empty()) {
1263 {
1264 std::lock_guard lock(mJobMutex);
1265 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001266 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001267 if (existingJobs.empty()) {
1268 existingJobs = std::move(jobQueue);
1269 } else {
1270 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1271 std::move_iterator(jobQueue.end()));
1272 }
1273 }
1274 }
1275 mJobCondition.notify_all();
1276 }
1277
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001278 if (sEnablePerfLogging) {
1279 auto end = Clock::now();
1280 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1281 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1282 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001283 << " make files: " << elapsedMcs(openZipTs, processedTs)
1284 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001285 }
1286
1287 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001288}
1289
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001290void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1291 ZipEntry& entry, const incfs::FileId& libFileId,
1292 std::string_view targetLibPath,
1293 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001294 if (!ifs) {
1295 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1296 return;
1297 }
1298
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001299 auto libName = path::basename(targetLibPath);
1300 auto startedTs = Clock::now();
1301
1302 // Write extracted data to new file
1303 // NOTE: don't zero-initialize memory, it may take a while for nothing
1304 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1305 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1306 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1307 return;
1308 }
1309
1310 auto extractFileTs = Clock::now();
1311
1312 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1313 if (!writeFd.ok()) {
1314 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1315 return;
1316 }
1317
1318 auto openFileTs = Clock::now();
1319 const int numBlocks =
1320 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1321 std::vector<IncFsDataBlock> instructions(numBlocks);
1322 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1323 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001324 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001325 instructions[i] = IncFsDataBlock{
1326 .fileFd = writeFd.get(),
1327 .pageIndex = static_cast<IncFsBlockIndex>(i),
1328 .compression = INCFS_COMPRESSION_KIND_NONE,
1329 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001330 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001331 .data = reinterpret_cast<const char*>(remainingData.data()),
1332 };
1333 remainingData = remainingData.subspan(blockSize);
1334 }
1335 auto prepareInstsTs = Clock::now();
1336
1337 size_t res = mIncFs->writeBlocks(instructions);
1338 if (res != instructions.size()) {
1339 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1340 return;
1341 }
1342
1343 if (sEnablePerfLogging) {
1344 auto endFileTs = Clock::now();
1345 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1346 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1347 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1348 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1349 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1350 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1351 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1352 }
1353}
1354
1355bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001356 struct WaitPrinter {
1357 const Clock::time_point startTs = Clock::now();
1358 ~WaitPrinter() noexcept {
1359 if (sEnablePerfLogging) {
1360 const auto endTs = Clock::now();
1361 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1362 << elapsedMcs(startTs, endTs) << "mcs";
1363 }
1364 }
1365 } waitPrinter;
1366
1367 MountId mount;
1368 {
1369 auto ifs = getIfs(storage);
1370 if (!ifs) {
1371 return true;
1372 }
1373 mount = ifs->mountId;
1374 }
1375
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001376 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001377 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001378 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001379 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001380 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001381 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001382}
1383
1384void IncrementalService::runJobProcessing() {
1385 for (;;) {
1386 std::unique_lock lock(mJobMutex);
1387 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1388 if (!mRunning) {
1389 return;
1390 }
1391
1392 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001393 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001394 auto queue = std::move(it->second);
1395 mJobQueue.erase(it);
1396 lock.unlock();
1397
1398 for (auto&& job : queue) {
1399 job();
1400 }
1401
1402 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001403 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001404 lock.unlock();
1405 mJobCondition.notify_all();
1406 }
1407}
1408
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001409void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001410 sp<IAppOpsCallback> listener;
1411 {
1412 std::unique_lock lock{mCallbacksLock};
1413 auto& cb = mCallbackRegistered[packageName];
1414 if (cb) {
1415 return;
1416 }
1417 cb = new AppOpsListener(*this, packageName);
1418 listener = cb;
1419 }
1420
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001421 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1422 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001423}
1424
1425bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1426 sp<IAppOpsCallback> listener;
1427 {
1428 std::unique_lock lock{mCallbacksLock};
1429 auto found = mCallbackRegistered.find(packageName);
1430 if (found == mCallbackRegistered.end()) {
1431 return false;
1432 }
1433 listener = found->second;
1434 mCallbackRegistered.erase(found);
1435 }
1436
1437 mAppOpsManager->stopWatchingMode(listener);
1438 return true;
1439}
1440
1441void IncrementalService::onAppOpChanged(const std::string& packageName) {
1442 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001443 return;
1444 }
1445
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001446 std::vector<IfsMountPtr> affected;
1447 {
1448 std::lock_guard l(mLock);
1449 affected.reserve(mMounts.size());
1450 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001451 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001452 affected.push_back(ifs);
1453 }
1454 }
1455 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001456 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001457 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001458 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001459}
1460
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001461IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1462 DataLoaderParamsParcel&& params,
1463 FileSystemControlParcel&& control,
1464 const DataLoaderStatusListener* externalListener)
1465 : mService(service),
1466 mId(id),
1467 mParams(std::move(params)),
1468 mControl(std::move(control)),
1469 mListener(externalListener ? *externalListener : DataLoaderStatusListener()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001470}
1471
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001472IncrementalService::DataLoaderStub::~DataLoaderStub() = default;
1473
1474void IncrementalService::DataLoaderStub::cleanupResources() {
1475 requestDestroy();
1476 mParams = {};
1477 mControl = {};
1478 waitForStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED, std::chrono::seconds(60));
1479 mListener = {};
1480 mId = kInvalidStorageId;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001481}
1482
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001483bool IncrementalService::DataLoaderStub::requestCreate() {
1484 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1485}
1486
1487bool IncrementalService::DataLoaderStub::requestStart() {
1488 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1489}
1490
1491bool IncrementalService::DataLoaderStub::requestDestroy() {
1492 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1493}
1494
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001495bool IncrementalService::DataLoaderStub::setTargetStatus(int status) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001496 {
1497 std::unique_lock lock(mStatusMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001498 mTargetStatus = status;
1499 mTargetStatusTs = Clock::now();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001500 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001501 return fsmStep();
1502}
1503
1504bool IncrementalService::DataLoaderStub::waitForStatus(int status, Clock::duration duration) {
1505 auto now = Clock::now();
1506 std::unique_lock lock(mStatusMutex);
1507 return mStatusCondition.wait_until(lock, now + duration,
1508 [this, status] { return mCurrentStatus == status; });
1509}
1510
1511bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001512 bool created = false;
1513 auto status = mService.mDataLoaderManager->initializeDataLoader(mId, mParams, mControl, this,
1514 &created);
1515 if (!status.isOk() || !created) {
1516 LOG(ERROR) << "Failed to create a data loader for mount " << mId;
1517 return false;
1518 }
1519 return true;
1520}
1521
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001522bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001523 sp<IDataLoader> dataloader;
1524 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1525 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001526 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001527 return false;
1528 }
1529 if (!dataloader) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001530 LOG(ERROR) << "DataLoader is null: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001531 return false;
1532 }
1533 status = dataloader->start(mId);
1534 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001535 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001536 return false;
1537 }
1538 return true;
1539}
1540
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001541bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001542 mService.mDataLoaderManager->destroyDataLoader(mId);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001543 return true;
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001544}
1545
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001546bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001547 if (!isValid()) {
1548 return false;
1549 }
1550
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001551 int currentStatus;
1552 int targetStatus;
1553 {
1554 std::unique_lock lock(mStatusMutex);
1555 currentStatus = mCurrentStatus;
1556 targetStatus = mTargetStatus;
1557 }
1558
1559 if (currentStatus == targetStatus) {
1560 return true;
1561 }
1562
1563 switch (targetStatus) {
1564 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1565 return destroy();
1566 }
1567 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1568 switch (currentStatus) {
1569 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1570 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1571 return start();
1572 }
1573 // fallthrough
1574 }
1575 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1576 switch (currentStatus) {
1577 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
1578 return create();
1579 }
1580 break;
1581 default:
1582 LOG(ERROR) << "Invalid target status: " << targetStatus
1583 << ", current status: " << currentStatus;
1584 break;
1585 }
1586 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001587}
1588
1589binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001590 if (!isValid()) {
1591 return binder::Status::
1592 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
1593 }
1594 if (mId != mountId) {
1595 LOG(ERROR) << "Mount ID mismatch: expected " << mId << ", but got: " << mountId;
1596 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
1597 }
1598
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001599 {
1600 std::unique_lock lock(mStatusMutex);
1601 if (mCurrentStatus == newStatus) {
1602 return binder::Status::ok();
1603 }
1604 mCurrentStatus = newStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001605 }
1606
1607 if (mListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001608 mListener->onStatusChanged(mountId, newStatus);
1609 }
1610
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001611 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08001612
1613 return binder::Status::ok();
1614}
1615
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001616void IncrementalService::DataLoaderStub::onDump(int fd) {
1617 dprintf(fd, "\t\tdataLoader:");
1618 dprintf(fd, "\t\t\tcurrentStatus: %d\n", mCurrentStatus);
1619 dprintf(fd, "\t\t\ttargetStatus: %d\n", mTargetStatus);
1620 dprintf(fd, "\t\t\ttargetStatusTs: %lldmcs\n",
1621 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
1622 const auto& params = mParams;
1623 dprintf(fd, "\t\t\tdataLoaderParams:\n");
1624 dprintf(fd, "\t\t\t\ttype: %s\n", toString(params.type).c_str());
1625 dprintf(fd, "\t\t\t\tpackageName: %s\n", params.packageName.c_str());
1626 dprintf(fd, "\t\t\t\tclassName: %s\n", params.className.c_str());
1627 dprintf(fd, "\t\t\t\targuments: %s\n", params.arguments.c_str());
1628}
1629
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001630void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1631 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001632}
1633
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001634binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1635 bool enableReadLogs, int32_t* _aidl_return) {
1636 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1637 return binder::Status::ok();
1638}
1639
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001640FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
1641 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
1642}
1643
Songchun Fan3c82a302019-11-29 14:23:45 -08001644} // namespace android::incremental