blob: 68b7ac0001e583a655a59e9e9e1a345c7ab7d4af [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 Buynytskyyab65cb12020-04-17 10:01:47 -0700163 dataLoaderStub->requestDestroy();
164 dataLoaderStub->waitForDestroy();
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 Buynytskyy0b202662020-04-13 09:53:04 -07001002 return dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -08001003}
1004
1005void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -08001006 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
1007 const auto path = entry.path().u8string();
1008 const auto name = entry.path().filename().u8string();
1009 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001010 continue;
1011 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001012 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001013 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -08001014 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -08001015 }
1016 }
1017}
1018
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001019bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001020 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001021 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001022
Songchun Fan3c82a302019-11-29 14:23:45 -08001023 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001024 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001025 if (!status.isOk()) {
1026 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1027 return false;
1028 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001029
1030 int cmd = controlParcel.cmd.release().release();
1031 int pendingReads = controlParcel.pendingReads.release().release();
1032 int logs = controlParcel.log.release().release();
1033 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001034
1035 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1036
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001037 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1038 path::join(mountTarget, constants().infoMdName));
1039 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001040 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1041 return false;
1042 }
1043
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001044 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001045 mNextId = std::max(mNextId, ifs->mountId + 1);
1046
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001047 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001048 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001049 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001050 const auto& loader = mount.loader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001051 dataLoaderParams.type = (android::content::pm::DataLoaderType)loader.type();
1052 dataLoaderParams.packageName = loader.package_name();
1053 dataLoaderParams.className = loader.class_name();
1054 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001055 }
1056
Alex Buynytskyy69941662020-04-11 21:40:37 -07001057 prepareDataLoader(*ifs, std::move(dataLoaderParams), nullptr);
1058 CHECK(ifs->dataLoaderStub);
1059
Songchun Fan3c82a302019-11-29 14:23:45 -08001060 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001061 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001062 while (auto e = ::readdir(d.get())) {
1063 if (e->d_type == DT_REG) {
1064 auto name = std::string_view(e->d_name);
1065 if (name.starts_with(constants().mountpointMdPrefix)) {
1066 bindPoints.emplace_back(name,
1067 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1068 ifs->control,
1069 path::join(mountTarget,
1070 name)));
1071 if (bindPoints.back().second.dest_path().empty() ||
1072 bindPoints.back().second.source_subdir().empty()) {
1073 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001074 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001075 }
1076 }
1077 } else if (e->d_type == DT_DIR) {
1078 if (e->d_name == "."sv || e->d_name == ".."sv) {
1079 continue;
1080 }
1081 auto name = std::string_view(e->d_name);
1082 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001083 int storageId;
1084 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1085 name.data() + name.size(), storageId);
1086 if (res.ec != std::errc{} || *res.ptr != '_') {
1087 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1088 << root;
1089 continue;
1090 }
1091 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001092 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001093 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001094 << " for mount " << root;
1095 continue;
1096 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001097 ifs->storages.insert_or_assign(storageId,
1098 IncFsMount::Storage{
1099 path::join(root, constants().mount, name)});
1100 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001101 }
1102 }
1103 }
1104
1105 if (ifs->storages.empty()) {
1106 LOG(WARNING) << "No valid storages in mount " << root;
1107 return false;
1108 }
1109
1110 int bindCount = 0;
1111 for (auto&& bp : bindPoints) {
1112 std::unique_lock l(mLock, std::defer_lock);
1113 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1114 std::move(*bp.second.mutable_source_subdir()),
1115 std::move(*bp.second.mutable_dest_path()),
1116 BindKind::Permanent, l);
1117 }
1118
1119 if (bindCount == 0) {
1120 LOG(WARNING) << "No valid bind points for mount " << root;
1121 deleteStorage(*ifs);
1122 return false;
1123 }
1124
Songchun Fan3c82a302019-11-29 14:23:45 -08001125 mMounts[ifs->mountId] = std::move(ifs);
1126 return true;
1127}
1128
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001129IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
1130 IncrementalService::IncFsMount& ifs, DataLoaderParamsParcel&& params,
1131 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001132 std::unique_lock l(ifs.lock);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001133 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001134 LOG(INFO) << "Skipped data loader preparation because it already exists";
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001135 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001136 }
1137
Songchun Fan3c82a302019-11-29 14:23:45 -08001138 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001139 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001140 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001141 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001142 base::unique_fd(::dup(ifs.control.pendingReads())));
1143 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001144 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001145
1146 ifs.dataLoaderStub = new DataLoaderStub(*this, ifs.mountId, std::move(params),
1147 std::move(fsControlParcel), externalListener);
1148 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001149}
1150
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001151template <class Duration>
1152static long elapsedMcs(Duration start, Duration end) {
1153 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1154}
1155
1156// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001157bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1158 std::string_view libDirRelativePath,
1159 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001160 auto start = Clock::now();
1161
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001162 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001163 if (!ifs) {
1164 LOG(ERROR) << "Invalid storage " << storage;
1165 return false;
1166 }
1167
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001168 // First prepare target directories if they don't exist yet
1169 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1170 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1171 << " errno: " << res;
1172 return false;
1173 }
1174
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001175 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001176 ZipArchiveHandle zipFileHandle;
1177 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001178 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1179 return false;
1180 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001181
1182 // Need a shared pointer: will be passing it into all unpacking jobs.
1183 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001184 void* cookie = nullptr;
1185 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001186 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001187 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1188 return false;
1189 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001190 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001191 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1192
1193 auto openZipTs = Clock::now();
1194
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001195 std::vector<Job> jobQueue;
1196 ZipEntry entry;
1197 std::string_view fileName;
1198 while (!Next(cookie, &entry, &fileName)) {
1199 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001200 continue;
1201 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001202
1203 auto startFileTs = Clock::now();
1204
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001205 const auto libName = path::basename(fileName);
1206 const auto targetLibPath = path::join(libDirRelativePath, libName);
1207 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1208 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001209 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
1210 if (sEnablePerfLogging) {
1211 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1212 << "; skipping extraction, spent "
1213 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1214 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001215 continue;
1216 }
1217
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001218 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001219 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001220 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001221 .signature = {},
1222 // Metadata of the new lib file is its relative path
1223 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1224 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001225 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001226 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1227 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001228 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001229 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001230 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001231 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001232
1233 auto makeFileTs = Clock::now();
1234
Songchun Fanafaf6e92020-03-18 14:12:20 -07001235 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001236 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001237 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001238 LOG(INFO) << "incfs: Extracted " << libName
1239 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001240 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001241 continue;
1242 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001243
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001244 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1245 libFileId, libPath = std::move(targetLibPath),
1246 makeFileTs]() mutable {
1247 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001248 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001249
1250 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001251 auto prepareJobTs = Clock::now();
1252 LOG(INFO) << "incfs: Processed " << libName << ": "
1253 << elapsedMcs(startFileTs, prepareJobTs)
1254 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1255 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001256 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001257 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001258
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001259 auto processedTs = Clock::now();
1260
1261 if (!jobQueue.empty()) {
1262 {
1263 std::lock_guard lock(mJobMutex);
1264 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001265 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001266 if (existingJobs.empty()) {
1267 existingJobs = std::move(jobQueue);
1268 } else {
1269 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1270 std::move_iterator(jobQueue.end()));
1271 }
1272 }
1273 }
1274 mJobCondition.notify_all();
1275 }
1276
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001277 if (sEnablePerfLogging) {
1278 auto end = Clock::now();
1279 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1280 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1281 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001282 << " make files: " << elapsedMcs(openZipTs, processedTs)
1283 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001284 }
1285
1286 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001287}
1288
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001289void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1290 ZipEntry& entry, const incfs::FileId& libFileId,
1291 std::string_view targetLibPath,
1292 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001293 if (!ifs) {
1294 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1295 return;
1296 }
1297
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001298 auto libName = path::basename(targetLibPath);
1299 auto startedTs = Clock::now();
1300
1301 // Write extracted data to new file
1302 // NOTE: don't zero-initialize memory, it may take a while for nothing
1303 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1304 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1305 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1306 return;
1307 }
1308
1309 auto extractFileTs = Clock::now();
1310
1311 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1312 if (!writeFd.ok()) {
1313 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1314 return;
1315 }
1316
1317 auto openFileTs = Clock::now();
1318 const int numBlocks =
1319 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1320 std::vector<IncFsDataBlock> instructions(numBlocks);
1321 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1322 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001323 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001324 instructions[i] = IncFsDataBlock{
1325 .fileFd = writeFd.get(),
1326 .pageIndex = static_cast<IncFsBlockIndex>(i),
1327 .compression = INCFS_COMPRESSION_KIND_NONE,
1328 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001329 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001330 .data = reinterpret_cast<const char*>(remainingData.data()),
1331 };
1332 remainingData = remainingData.subspan(blockSize);
1333 }
1334 auto prepareInstsTs = Clock::now();
1335
1336 size_t res = mIncFs->writeBlocks(instructions);
1337 if (res != instructions.size()) {
1338 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1339 return;
1340 }
1341
1342 if (sEnablePerfLogging) {
1343 auto endFileTs = Clock::now();
1344 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1345 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1346 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1347 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1348 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1349 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1350 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1351 }
1352}
1353
1354bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001355 struct WaitPrinter {
1356 const Clock::time_point startTs = Clock::now();
1357 ~WaitPrinter() noexcept {
1358 if (sEnablePerfLogging) {
1359 const auto endTs = Clock::now();
1360 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1361 << elapsedMcs(startTs, endTs) << "mcs";
1362 }
1363 }
1364 } waitPrinter;
1365
1366 MountId mount;
1367 {
1368 auto ifs = getIfs(storage);
1369 if (!ifs) {
1370 return true;
1371 }
1372 mount = ifs->mountId;
1373 }
1374
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001375 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001376 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001377 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001378 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001379 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001380 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001381}
1382
1383void IncrementalService::runJobProcessing() {
1384 for (;;) {
1385 std::unique_lock lock(mJobMutex);
1386 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1387 if (!mRunning) {
1388 return;
1389 }
1390
1391 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001392 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001393 auto queue = std::move(it->second);
1394 mJobQueue.erase(it);
1395 lock.unlock();
1396
1397 for (auto&& job : queue) {
1398 job();
1399 }
1400
1401 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001402 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001403 lock.unlock();
1404 mJobCondition.notify_all();
1405 }
1406}
1407
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001408void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001409 sp<IAppOpsCallback> listener;
1410 {
1411 std::unique_lock lock{mCallbacksLock};
1412 auto& cb = mCallbackRegistered[packageName];
1413 if (cb) {
1414 return;
1415 }
1416 cb = new AppOpsListener(*this, packageName);
1417 listener = cb;
1418 }
1419
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001420 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1421 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001422}
1423
1424bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1425 sp<IAppOpsCallback> listener;
1426 {
1427 std::unique_lock lock{mCallbacksLock};
1428 auto found = mCallbackRegistered.find(packageName);
1429 if (found == mCallbackRegistered.end()) {
1430 return false;
1431 }
1432 listener = found->second;
1433 mCallbackRegistered.erase(found);
1434 }
1435
1436 mAppOpsManager->stopWatchingMode(listener);
1437 return true;
1438}
1439
1440void IncrementalService::onAppOpChanged(const std::string& packageName) {
1441 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001442 return;
1443 }
1444
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001445 std::vector<IfsMountPtr> affected;
1446 {
1447 std::lock_guard l(mLock);
1448 affected.reserve(mMounts.size());
1449 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001450 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001451 affected.push_back(ifs);
1452 }
1453 }
1454 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001455 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001456 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001457 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001458}
1459
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001460IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1461 DataLoaderParamsParcel&& params,
1462 FileSystemControlParcel&& control,
1463 const DataLoaderStatusListener* externalListener)
1464 : mService(service),
1465 mId(id),
1466 mParams(std::move(params)),
1467 mControl(std::move(control)),
1468 mListener(externalListener ? *externalListener : DataLoaderStatusListener()) {
1469 //
1470}
1471
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001472IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001473 waitForDestroy();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001474}
1475
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001476bool IncrementalService::DataLoaderStub::requestCreate() {
1477 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1478}
1479
1480bool IncrementalService::DataLoaderStub::requestStart() {
1481 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1482}
1483
1484bool IncrementalService::DataLoaderStub::requestDestroy() {
1485 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1486}
1487
1488bool IncrementalService::DataLoaderStub::waitForDestroy(Clock::duration duration) {
1489 return waitForStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED, duration);
1490}
1491
1492bool IncrementalService::DataLoaderStub::setTargetStatus(int status) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001493 {
1494 std::unique_lock lock(mStatusMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001495 mTargetStatus = status;
1496 mTargetStatusTs = Clock::now();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001497 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001498 return fsmStep();
1499}
1500
1501bool IncrementalService::DataLoaderStub::waitForStatus(int status, Clock::duration duration) {
1502 auto now = Clock::now();
1503 std::unique_lock lock(mStatusMutex);
1504 return mStatusCondition.wait_until(lock, now + duration,
1505 [this, status] { return mCurrentStatus == status; });
1506}
1507
1508bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001509 bool created = false;
1510 auto status = mService.mDataLoaderManager->initializeDataLoader(mId, mParams, mControl, this,
1511 &created);
1512 if (!status.isOk() || !created) {
1513 LOG(ERROR) << "Failed to create a data loader for mount " << mId;
1514 return false;
1515 }
1516 return true;
1517}
1518
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001519bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001520 sp<IDataLoader> dataloader;
1521 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1522 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001523 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001524 return false;
1525 }
1526 if (!dataloader) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001527 LOG(ERROR) << "DataLoader is null: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001528 return false;
1529 }
1530 status = dataloader->start(mId);
1531 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001532 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001533 return false;
1534 }
1535 return true;
1536}
1537
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001538bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001539 mService.mDataLoaderManager->destroyDataLoader(mId);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001540 return true;
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001541}
1542
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001543bool IncrementalService::DataLoaderStub::fsmStep() {
1544 int currentStatus;
1545 int targetStatus;
1546 {
1547 std::unique_lock lock(mStatusMutex);
1548 currentStatus = mCurrentStatus;
1549 targetStatus = mTargetStatus;
1550 }
1551
1552 if (currentStatus == targetStatus) {
1553 return true;
1554 }
1555
1556 switch (targetStatus) {
1557 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1558 return destroy();
1559 }
1560 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1561 switch (currentStatus) {
1562 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1563 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1564 return start();
1565 }
1566 // fallthrough
1567 }
1568 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1569 switch (currentStatus) {
1570 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
1571 return create();
1572 }
1573 break;
1574 default:
1575 LOG(ERROR) << "Invalid target status: " << targetStatus
1576 << ", current status: " << currentStatus;
1577 break;
1578 }
1579 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001580}
1581
1582binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001583 {
1584 std::unique_lock lock(mStatusMutex);
1585 if (mCurrentStatus == newStatus) {
1586 return binder::Status::ok();
1587 }
1588 mCurrentStatus = newStatus;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001589 }
1590
1591 if (mListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001592 mListener->onStatusChanged(mountId, newStatus);
1593 }
1594
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001595 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08001596
1597 return binder::Status::ok();
1598}
1599
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001600void IncrementalService::DataLoaderStub::onDump(int fd) {
1601 dprintf(fd, "\t\tdataLoader:");
1602 dprintf(fd, "\t\t\tcurrentStatus: %d\n", mCurrentStatus);
1603 dprintf(fd, "\t\t\ttargetStatus: %d\n", mTargetStatus);
1604 dprintf(fd, "\t\t\ttargetStatusTs: %lldmcs\n",
1605 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
1606 const auto& params = mParams;
1607 dprintf(fd, "\t\t\tdataLoaderParams:\n");
1608 dprintf(fd, "\t\t\t\ttype: %s\n", toString(params.type).c_str());
1609 dprintf(fd, "\t\t\t\tpackageName: %s\n", params.packageName.c_str());
1610 dprintf(fd, "\t\t\t\tclassName: %s\n", params.className.c_str());
1611 dprintf(fd, "\t\t\t\targuments: %s\n", params.arguments.c_str());
1612}
1613
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001614void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1615 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001616}
1617
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001618binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1619 bool enableReadLogs, int32_t* _aidl_return) {
1620 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1621 return binder::Status::ok();
1622}
1623
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001624FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
1625 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
1626}
1627
Songchun Fan3c82a302019-11-29 14:23:45 -08001628} // namespace android::incremental