blob: 44a07a17824f1d239102c2bfa26d7323ef95f7e5 [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "IncrementalService"
18
19#include "IncrementalService.h"
20
Songchun Fan3c82a302019-11-29 14:23:45 -080021#include <android-base/logging.h>
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -070022#include <android-base/no_destructor.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080023#include <android-base/properties.h>
24#include <android-base/stringprintf.h>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070025#include <binder/AppOpsManager.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080026#include <binder/Status.h>
27#include <sys/stat.h>
28#include <uuid/uuid.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080029
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070030#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080031#include <ctime>
Songchun Fan3c82a302019-11-29 14:23:45 -080032#include <iterator>
33#include <span>
Songchun Fan3c82a302019-11-29 14:23:45 -080034#include <type_traits>
35
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070036#include "IncrementalServiceValidation.h"
Songchun Fan3c82a302019-11-29 14:23:45 -080037#include "Metadata.pb.h"
38
39using namespace std::literals;
Songchun Fan3c82a302019-11-29 14:23:45 -080040
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070041constexpr const char* kDataUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070042constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070043
Songchun Fan3c82a302019-11-29 14:23:45 -080044namespace android::incremental {
45
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070046using content::pm::DataLoaderParamsParcel;
47using content::pm::FileSystemControlParcel;
48using content::pm::IDataLoader;
49
Songchun Fan3c82a302019-11-29 14:23:45 -080050namespace {
51
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070052using IncrementalFileSystemControlParcel = os::incremental::IncrementalFileSystemControlParcel;
Songchun Fan3c82a302019-11-29 14:23:45 -080053
54struct Constants {
55 static constexpr auto backing = "backing_store"sv;
56 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080057 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080058 static constexpr auto storagePrefix = "st"sv;
59 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
60 static constexpr auto infoMdName = ".info"sv;
Alex Buynytskyy04035452020-06-06 20:15:58 -070061 static constexpr auto readLogsDisabledMarkerName = ".readlogs_disabled"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080062 static constexpr auto libDir = "lib"sv;
63 static constexpr auto libSuffix = ".so"sv;
64 static constexpr auto blockSize = 4096;
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -070065 static constexpr auto systemPackage = "android"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080066};
67
68static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070069 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080070 return c;
71}
72
73template <base::LogSeverity level = base::ERROR>
74bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
75 auto cstr = path::c_str(name);
76 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080077 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080078 PLOG(level) << "Can't create directory '" << name << '\'';
79 return false;
80 }
81 struct stat st;
82 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
83 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
84 return false;
85 }
86 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080087 if (::chmod(cstr, mode)) {
88 PLOG(level) << "Changing permission failed for '" << name << '\'';
89 return false;
90 }
91
Songchun Fan3c82a302019-11-29 14:23:45 -080092 return true;
93}
94
95static std::string toMountKey(std::string_view path) {
96 if (path.empty()) {
97 return "@none";
98 }
99 if (path == "/"sv) {
100 return "@root";
101 }
102 if (path::isAbsolute(path)) {
103 path.remove_prefix(1);
104 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700105 if (path.size() > 16) {
106 path = path.substr(0, 16);
107 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800108 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700109 std::replace_if(
110 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
111 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800112}
113
114static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
115 std::string_view path) {
116 auto mountKey = toMountKey(path);
117 const auto prefixSize = mountKey.size();
118 for (int counter = 0; counter < 1000;
119 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
120 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800121 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800122 return {mountKey, mountRoot};
123 }
124 }
125 return {};
126}
127
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700128template <class Map>
129typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
130 const auto nextIt = map.upper_bound(path);
131 if (nextIt == map.begin()) {
132 return map.end();
133 }
134 const auto suspectIt = std::prev(nextIt);
135 if (!path::startsWith(path, suspectIt->first)) {
136 return map.end();
137 }
138 return suspectIt;
139}
140
141static base::unique_fd dup(base::borrowed_fd fd) {
142 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
143 return base::unique_fd(res);
144}
145
Songchun Fan3c82a302019-11-29 14:23:45 -0800146template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700147static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800148 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800149 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800150 ProtoMessage message;
151 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
152}
153
154static bool isValidMountTarget(std::string_view path) {
155 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
156}
157
158std::string makeBindMdName() {
159 static constexpr auto uuidStringSize = 36;
160
161 uuid_t guid;
162 uuid_generate(guid);
163
164 std::string name;
165 const auto prefixSize = constants().mountpointMdPrefix.size();
166 name.reserve(prefixSize + uuidStringSize);
167
168 name = constants().mountpointMdPrefix;
169 name.resize(prefixSize + uuidStringSize);
170 uuid_unparse(guid, name.data() + prefixSize);
171
172 return name;
173}
Alex Buynytskyy04035452020-06-06 20:15:58 -0700174
175static bool checkReadLogsDisabledMarker(std::string_view root) {
176 const auto markerPath = path::c_str(path::join(root, constants().readLogsDisabledMarkerName));
177 struct stat st;
178 return (::stat(markerPath, &st) == 0);
179}
180
Songchun Fan3c82a302019-11-29 14:23:45 -0800181} // namespace
182
183IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700184 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700185 dataLoaderStub->cleanupResources();
186 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700187 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700188 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800189 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
190 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700191 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800192 incrementalService.mVold->unmountIncFs(target);
193 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700194 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800195 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
196 cleanupFilesystem(root);
197}
198
199auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800200 std::string name;
201 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
202 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
203 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800204 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
205 constants().storagePrefix.data(), id, no);
206 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800207 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800208 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800209 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
210 } else if (err != EEXIST) {
211 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
212 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800213 }
214 }
215 nextStorageDirNo = 0;
216 return storages.end();
217}
218
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700219template <class Func>
220static auto makeCleanup(Func&& f) {
221 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700222 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700223 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
224}
225
226static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
227 return {::opendir(dir), ::closedir};
228}
229
230static auto openDir(std::string_view dir) {
231 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800232}
233
234static int rmDirContent(const char* path) {
235 auto dir = openDir(path);
236 if (!dir) {
237 return -EINVAL;
238 }
239 while (auto entry = ::readdir(dir.get())) {
240 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
241 continue;
242 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700243 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800244 if (entry->d_type == DT_DIR) {
245 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
246 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
247 return err;
248 }
249 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
250 PLOG(WARNING) << "Failed to rmdir " << fullPath;
251 return err;
252 }
253 } else {
254 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
255 PLOG(WARNING) << "Failed to delete " << fullPath;
256 return err;
257 }
258 }
259 }
260 return 0;
261}
262
Songchun Fan3c82a302019-11-29 14:23:45 -0800263void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800264 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800265 ::rmdir(path::join(root, constants().backing).c_str());
266 ::rmdir(path::join(root, constants().mount).c_str());
267 ::rmdir(path::c_str(root));
268}
269
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800270IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800271 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800272 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800273 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700274 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700275 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700276 mLooper(sm.getLooper()),
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700277 mTimedQueue(sm.getTimedQueue()),
Songchun Fana7098592020-09-03 11:45:53 -0700278 mProgressUpdateJobQueue(sm.getProgressUpdateJobQueue()),
Songchun Fan374f7652020-08-20 08:40:29 -0700279 mFs(sm.getFs()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800280 mIncrementalDir(rootDir) {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700281 CHECK(mVold) << "Vold service is unavailable";
282 CHECK(mDataLoaderManager) << "DataLoaderManagerService is unavailable";
283 CHECK(mAppOpsManager) << "AppOpsManager is unavailable";
284 CHECK(mJni) << "JNI is unavailable";
285 CHECK(mLooper) << "Looper is unavailable";
286 CHECK(mTimedQueue) << "TimedQueue is unavailable";
Songchun Fana7098592020-09-03 11:45:53 -0700287 CHECK(mProgressUpdateJobQueue) << "mProgressUpdateJobQueue is unavailable";
Songchun Fan374f7652020-08-20 08:40:29 -0700288 CHECK(mFs) << "Fs is unavailable";
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700289
290 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700291 mJobProcessor = std::thread([this]() {
292 mJni->initializeForCurrentThread();
293 runJobProcessing();
294 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700295 mCmdLooperThread = std::thread([this]() {
296 mJni->initializeForCurrentThread();
297 runCmdLooper();
298 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700299
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700300 const auto mountedRootNames = adoptMountedInstances();
301 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800302}
303
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700304IncrementalService::~IncrementalService() {
305 {
306 std::lock_guard lock(mJobMutex);
307 mRunning = false;
308 }
309 mJobCondition.notify_all();
310 mJobProcessor.join();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700311 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700312 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700313 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700314 // Ensure that mounts are destroyed while the service is still valid.
315 mBindsByPath.clear();
316 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700317}
Songchun Fan3c82a302019-11-29 14:23:45 -0800318
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700319static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800320 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800321 case IncrementalService::BindKind::Temporary:
322 return "Temporary";
323 case IncrementalService::BindKind::Permanent:
324 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800325 }
326}
327
328void IncrementalService::onDump(int fd) {
329 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
330 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
331
332 std::unique_lock l(mLock);
333
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700334 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800335 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700336 const IncFsMount& mnt = *ifs;
337 dprintf(fd, " [%d]: {\n", id);
338 if (id != mnt.mountId) {
339 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
340 } else {
341 dprintf(fd, " mountId: %d\n", mnt.mountId);
342 dprintf(fd, " root: %s\n", mnt.root.c_str());
343 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
344 if (mnt.dataLoaderStub) {
345 mnt.dataLoaderStub->onDump(fd);
346 } else {
347 dprintf(fd, " dataLoader: null\n");
348 }
349 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
350 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700351 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
352 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()) * 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700353 }
354 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800355
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700356 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
357 for (auto&& [target, bind] : mnt.bindPoints) {
358 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
359 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
360 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
361 dprintf(fd, " kind: %s\n", toString(bind.kind));
362 }
363 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800364 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700365 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800366 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700367 dprintf(fd, "}\n");
368 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800369 for (auto&& [target, mountPairIt] : mBindsByPath) {
370 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700371 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
372 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
373 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
374 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800375 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700376 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800377}
378
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700379void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800380 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700381 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800382 }
383
384 std::vector<IfsMountPtr> mounts;
385 {
386 std::lock_guard l(mLock);
387 mounts.reserve(mMounts.size());
388 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -0700389 if (ifs->mountId == id &&
390 ifs->dataLoaderStub->params().packageName == Constants::systemPackage) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800391 mounts.push_back(ifs);
392 }
393 }
394 }
395
Alex Buynytskyy69941662020-04-11 21:40:37 -0700396 if (mounts.empty()) {
397 return;
398 }
399
Songchun Fan3c82a302019-11-29 14:23:45 -0800400 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700401 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800402 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700403 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800404 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800405 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800406}
407
408auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
409 for (;;) {
410 if (mNextId == kMaxStorageId) {
411 mNextId = 0;
412 }
413 auto id = ++mNextId;
414 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
415 if (inserted) {
416 return it;
417 }
418 }
419}
420
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700421StorageId IncrementalService::createStorage(std::string_view mountPoint,
422 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
423 CreateOptions options,
424 const DataLoaderStatusListener& statusListener,
425 StorageHealthCheckParams&& healthCheckParams,
426 const StorageHealthListener& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800427 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
428 if (!path::isAbsolute(mountPoint)) {
429 LOG(ERROR) << "path is not absolute: " << mountPoint;
430 return kInvalidStorageId;
431 }
432
433 auto mountNorm = path::normalize(mountPoint);
434 {
435 const auto id = findStorageId(mountNorm);
436 if (id != kInvalidStorageId) {
437 if (options & CreateOptions::OpenExisting) {
438 LOG(INFO) << "Opened existing storage " << id;
439 return id;
440 }
441 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
442 return kInvalidStorageId;
443 }
444 }
445
446 if (!(options & CreateOptions::CreateNew)) {
447 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
448 return kInvalidStorageId;
449 }
450
451 if (!path::isEmptyDir(mountNorm)) {
452 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
453 return kInvalidStorageId;
454 }
455 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
456 if (mountRoot.empty()) {
457 LOG(ERROR) << "Bad mount point";
458 return kInvalidStorageId;
459 }
460 // Make sure the code removes all crap it may create while still failing.
461 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
462 auto firstCleanupOnFailure =
463 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
464
465 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800466 const auto backing = path::join(mountRoot, constants().backing);
467 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800468 return kInvalidStorageId;
469 }
470
Songchun Fan3c82a302019-11-29 14:23:45 -0800471 IncFsMount::Control control;
472 {
473 std::lock_guard l(mMountOperationLock);
474 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800475
476 if (auto err = rmDirContent(backing.c_str())) {
477 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
478 return kInvalidStorageId;
479 }
480 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
481 return kInvalidStorageId;
482 }
483 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800484 if (!status.isOk()) {
485 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
486 return kInvalidStorageId;
487 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800488 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
489 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800490 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
491 return kInvalidStorageId;
492 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800493 int cmd = controlParcel.cmd.release().release();
494 int pendingReads = controlParcel.pendingReads.release().release();
495 int logs = controlParcel.log.release().release();
496 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800497 }
498
499 std::unique_lock l(mLock);
500 const auto mountIt = getStorageSlotLocked();
501 const auto mountId = mountIt->first;
502 l.unlock();
503
504 auto ifs =
505 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
506 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
507 // is the removal of the |ifs|.
508 firstCleanupOnFailure.release();
509
510 auto secondCleanup = [this, &l](auto itPtr) {
511 if (!l.owns_lock()) {
512 l.lock();
513 }
514 mMounts.erase(*itPtr);
515 };
516 auto secondCleanupOnFailure =
517 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
518
519 const auto storageIt = ifs->makeStorage(ifs->mountId);
520 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800521 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800522 return kInvalidStorageId;
523 }
524
525 {
526 metadata::Mount m;
527 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700528 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700529 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
530 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
531 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800532 const auto metadata = m.SerializeAsString();
533 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800534 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800535 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800536 if (auto err =
537 mIncFs->makeFile(ifs->control,
538 path::join(ifs->root, constants().mount,
539 constants().infoMdName),
540 0777, idFromMetadata(metadata),
541 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800542 LOG(ERROR) << "Saving mount metadata failed: " << -err;
543 return kInvalidStorageId;
544 }
545 }
546
547 const auto bk =
548 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800549 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
550 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800551 err < 0) {
552 LOG(ERROR) << "adding bind mount failed: " << -err;
553 return kInvalidStorageId;
554 }
555
556 // Done here as well, all data structures are in good state.
557 secondCleanupOnFailure.release();
558
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700559 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
560 std::move(healthCheckParams), &healthListener);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700561 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800562
563 mountIt->second = std::move(ifs);
564 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700565
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700566 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700567 // failed to create data loader
568 LOG(ERROR) << "initializeDataLoader() failed";
569 deleteStorage(dataLoaderStub->id());
570 return kInvalidStorageId;
571 }
572
Songchun Fan3c82a302019-11-29 14:23:45 -0800573 LOG(INFO) << "created storage " << mountId;
574 return mountId;
575}
576
577StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
578 StorageId linkedStorage,
579 IncrementalService::CreateOptions options) {
580 if (!isValidMountTarget(mountPoint)) {
581 LOG(ERROR) << "Mount point is invalid or missing";
582 return kInvalidStorageId;
583 }
584
585 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700586 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800587 if (!ifs) {
588 LOG(ERROR) << "Ifs unavailable";
589 return kInvalidStorageId;
590 }
591
592 const auto mountIt = getStorageSlotLocked();
593 const auto storageId = mountIt->first;
594 const auto storageIt = ifs->makeStorage(storageId);
595 if (storageIt == ifs->storages.end()) {
596 LOG(ERROR) << "Can't create a new storage";
597 mMounts.erase(mountIt);
598 return kInvalidStorageId;
599 }
600
601 l.unlock();
602
603 const auto bk =
604 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800605 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
606 std::string(storageIt->second.name), path::normalize(mountPoint),
607 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800608 err < 0) {
609 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700610 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
611 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800612 return kInvalidStorageId;
613 }
614
615 mountIt->second = ifs;
616 return storageId;
617}
618
619IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
620 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700621 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800622}
623
624StorageId IncrementalService::findStorageId(std::string_view path) const {
625 std::lock_guard l(mLock);
626 auto it = findStorageLocked(path);
627 if (it == mBindsByPath.end()) {
628 return kInvalidStorageId;
629 }
630 return it->second->second.storage;
631}
632
Alex Buynytskyy04035452020-06-06 20:15:58 -0700633void IncrementalService::disableReadLogs(StorageId storageId) {
634 std::unique_lock l(mLock);
635 const auto ifs = getIfsLocked(storageId);
636 if (!ifs) {
637 LOG(ERROR) << "disableReadLogs failed, invalid storageId: " << storageId;
638 return;
639 }
640 if (!ifs->readLogsEnabled()) {
641 return;
642 }
643 ifs->disableReadLogs();
644 l.unlock();
645
646 const auto metadata = constants().readLogsDisabledMarkerName;
647 if (auto err = mIncFs->makeFile(ifs->control,
648 path::join(ifs->root, constants().mount,
649 constants().readLogsDisabledMarkerName),
650 0777, idFromMetadata(metadata), {})) {
651 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
652 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
653 return;
654 }
655
656 setStorageParams(storageId, /*enableReadLogs=*/false);
657}
658
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700659int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
660 const auto ifs = getIfs(storageId);
661 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700662 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700663 return -EINVAL;
664 }
665
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700666 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700667 if (enableReadLogs) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700668 if (!ifs->readLogsEnabled()) {
669 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
670 return -EPERM;
671 }
672
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700673 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
674 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700675 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700676 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700677 return fromBinderStatus(status);
678 }
679 }
680
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700681 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
682 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
683 return fromBinderStatus(status);
684 }
685
686 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700687 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700688 }
689
690 return 0;
691}
692
693binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700694 os::incremental::IncrementalFileSystemControlParcel control;
695 control.cmd.reset(dup(ifs.control.cmd()));
696 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700697 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700698 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700699 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700700 }
701
702 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700703 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700704}
705
Songchun Fan3c82a302019-11-29 14:23:45 -0800706void IncrementalService::deleteStorage(StorageId storageId) {
707 const auto ifs = getIfs(storageId);
708 if (!ifs) {
709 return;
710 }
711 deleteStorage(*ifs);
712}
713
714void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
715 std::unique_lock l(ifs.lock);
716 deleteStorageLocked(ifs, std::move(l));
717}
718
719void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
720 std::unique_lock<std::mutex>&& ifsLock) {
721 const auto storages = std::move(ifs.storages);
722 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
723 const auto bindPoints = ifs.bindPoints;
724 ifsLock.unlock();
725
726 std::lock_guard l(mLock);
727 for (auto&& [id, _] : storages) {
728 if (id != ifs.mountId) {
729 mMounts.erase(id);
730 }
731 }
732 for (auto&& [path, _] : bindPoints) {
733 mBindsByPath.erase(path);
734 }
735 mMounts.erase(ifs.mountId);
736}
737
738StorageId IncrementalService::openStorage(std::string_view pathInMount) {
739 if (!path::isAbsolute(pathInMount)) {
740 return kInvalidStorageId;
741 }
742
743 return findStorageId(path::normalize(pathInMount));
744}
745
Songchun Fan3c82a302019-11-29 14:23:45 -0800746IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
747 std::lock_guard l(mLock);
748 return getIfsLocked(storage);
749}
750
751const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
752 auto it = mMounts.find(storage);
753 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700754 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700755 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800756 }
757 return it->second;
758}
759
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800760int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
761 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800762 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700763 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800764 return -EINVAL;
765 }
766
767 const auto ifs = getIfs(storage);
768 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700769 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800770 return -EINVAL;
771 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800772
Songchun Fan3c82a302019-11-29 14:23:45 -0800773 std::unique_lock l(ifs->lock);
774 const auto storageInfo = ifs->storages.find(storage);
775 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700776 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800777 return -EINVAL;
778 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700779 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700780 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700781 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700782 return -EINVAL;
783 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800784 l.unlock();
785 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800786 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
787 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800788}
789
790int IncrementalService::unbind(StorageId storage, std::string_view target) {
791 if (!path::isAbsolute(target)) {
792 return -EINVAL;
793 }
794
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700795 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800796
797 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
798 // otherwise there's a chance to unmount something completely unrelated
799 const auto norm = path::normalize(target);
800 std::unique_lock l(mLock);
801 const auto storageIt = mBindsByPath.find(norm);
802 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
803 return -EINVAL;
804 }
805 const auto bindIt = storageIt->second;
806 const auto storageId = bindIt->second.storage;
807 const auto ifs = getIfsLocked(storageId);
808 if (!ifs) {
809 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
810 << " is missing";
811 return -EFAULT;
812 }
813 mBindsByPath.erase(storageIt);
814 l.unlock();
815
816 mVold->unmountIncFs(bindIt->first);
817 std::unique_lock l2(ifs->lock);
818 if (ifs->bindPoints.size() <= 1) {
819 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700820 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800821 } else {
822 const std::string savedFile = std::move(bindIt->second.savedFilename);
823 ifs->bindPoints.erase(bindIt);
824 l2.unlock();
825 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800826 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800827 }
828 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700829
Songchun Fan3c82a302019-11-29 14:23:45 -0800830 return 0;
831}
832
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700833std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700834 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700835 std::string_view path) const {
836 if (!path::isAbsolute(path)) {
837 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700838 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700839 auto normPath = path::normalize(path);
840 if (path::startsWith(normPath, storageIt->second.name)) {
841 return normPath;
842 }
843 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700844 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
845 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700846 return {};
847 }
848 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700849}
850
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700851std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700852 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700853 std::unique_lock l(ifs.lock);
854 const auto storageInfo = ifs.storages.find(storage);
855 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800856 return {};
857 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700858 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800859}
860
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800861int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700862 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800863 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700864 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800865 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700866 LOG(ERROR) << "Internal error: storageId " << storage
867 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800868 return -EINVAL;
869 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700870 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700871 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800872 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800873 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700874 if (!data.empty()) {
875 if (auto err = setFileContent(ifs, id, path, data); err) {
876 return err;
877 }
878 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800879 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800880 }
881 return -EINVAL;
882}
883
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800884int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800885 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700886 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800887 if (normPath.empty()) {
888 return -EINVAL;
889 }
890 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800891 }
892 return -EINVAL;
893}
894
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800895int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800896 const auto ifs = getIfs(storageId);
897 if (!ifs) {
898 return -EINVAL;
899 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700900 return makeDirs(*ifs, storageId, path, mode);
901}
902
903int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
904 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800905 std::string normPath = normalizePathToStorage(ifs, storageId, path);
906 if (normPath.empty()) {
907 return -EINVAL;
908 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700909 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800910}
911
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800912int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
913 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700914 std::unique_lock l(mLock);
915 auto ifsSrc = getIfsLocked(sourceStorageId);
916 if (!ifsSrc) {
917 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800918 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700919 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
920 return -EINVAL;
921 }
922 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700923 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
924 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700925 if (normOldPath.empty() || normNewPath.empty()) {
926 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
927 return -EINVAL;
928 }
929 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800930}
931
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800932int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800933 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700934 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800935 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800936 }
937 return -EINVAL;
938}
939
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800940int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
941 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800942 std::string&& target, BindKind kind,
943 std::unique_lock<std::mutex>& mainLock) {
944 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700945 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800946 return -EINVAL;
947 }
948
949 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700950 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800951 if (kind != BindKind::Temporary) {
952 metadata::BindPoint bp;
953 bp.set_storage_id(storage);
954 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800955 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800956 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800957 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800958 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800959 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700960 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
961 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
962 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800963 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700964 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800965 return int(node);
966 }
967 }
968
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700969 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
970 std::move(target), kind, mainLock);
971 if (res) {
972 mIncFs->unlink(ifs.control, metadataFullPath);
973 }
974 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800975}
976
977int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800978 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800979 std::string&& target, BindKind kind,
980 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800981 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800982 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800983 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800984 if (!status.isOk()) {
985 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
986 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
987 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
988 : status.serviceSpecificErrorCode() == 0
989 ? -EFAULT
990 : status.serviceSpecificErrorCode()
991 : -EIO;
992 }
993 }
994
995 if (!mainLock.owns_lock()) {
996 mainLock.lock();
997 }
998 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700999 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1000 std::move(target), kind);
1001 return 0;
1002}
1003
1004void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1005 std::string&& metadataName, std::string&& source,
1006 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001007 const auto [it, _] =
1008 ifs.bindPoints.insert_or_assign(target,
1009 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001010 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001011 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001012}
1013
1014RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1015 const auto ifs = getIfs(storage);
1016 if (!ifs) {
1017 return {};
1018 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001019 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001020 if (normPath.empty()) {
1021 return {};
1022 }
1023 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001024}
1025
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001026RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001027 const auto ifs = getIfs(storage);
1028 if (!ifs) {
1029 return {};
1030 }
1031 return mIncFs->getMetadata(ifs->control, node);
1032}
1033
Songchun Fan3c82a302019-11-29 14:23:45 -08001034bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001035 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001036 {
1037 std::unique_lock l(mLock);
1038 const auto& ifs = getIfsLocked(storage);
1039 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001040 return false;
1041 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001042 dataLoaderStub = ifs->dataLoaderStub;
1043 if (!dataLoaderStub) {
1044 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001045 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001046 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001047 dataLoaderStub->requestStart();
1048 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001049}
1050
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001051std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1052 std::unordered_set<std::string_view> mountedRootNames;
1053 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1054 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1055 for (auto [source, target] : binds) {
1056 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1057 LOG(INFO) << " " << path::join(root, source);
1058 }
1059
1060 // Ensure it's a kind of a mount that's managed by IncrementalService
1061 if (path::basename(root) != constants().mount ||
1062 path::basename(backingDir) != constants().backing) {
1063 return;
1064 }
1065 const auto expectedRoot = path::dirname(root);
1066 if (path::dirname(backingDir) != expectedRoot) {
1067 return;
1068 }
1069 if (path::dirname(expectedRoot) != mIncrementalDir) {
1070 return;
1071 }
1072 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1073 return;
1074 }
1075
1076 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1077
1078 // make sure we clean up the mount if it happens to be a bad one.
1079 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1080 auto cleanupFiles = makeCleanup([&]() {
1081 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1082 IncFsMount::cleanupFilesystem(expectedRoot);
1083 });
1084 auto cleanupMounts = makeCleanup([&]() {
1085 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1086 for (auto&& [_, target] : binds) {
1087 mVold->unmountIncFs(std::string(target));
1088 }
1089 mVold->unmountIncFs(std::string(root));
1090 });
1091
1092 auto control = mIncFs->openMount(root);
1093 if (!control) {
1094 LOG(INFO) << "failed to open mount " << root;
1095 return;
1096 }
1097
1098 auto mountRecord =
1099 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1100 path::join(root, constants().infoMdName));
1101 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1102 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1103 return;
1104 }
1105
1106 auto mountId = mountRecord.storage().id();
1107 mNextId = std::max(mNextId, mountId + 1);
1108
1109 DataLoaderParamsParcel dataLoaderParams;
1110 {
1111 const auto& loader = mountRecord.loader();
1112 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1113 dataLoaderParams.packageName = loader.package_name();
1114 dataLoaderParams.className = loader.class_name();
1115 dataLoaderParams.arguments = loader.arguments();
1116 }
1117
1118 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1119 std::move(control), *this);
1120 cleanupFiles.release(); // ifs will take care of that now
1121
Alex Buynytskyy04035452020-06-06 20:15:58 -07001122 // Check if marker file present.
1123 if (checkReadLogsDisabledMarker(root)) {
1124 ifs->disableReadLogs();
1125 }
1126
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001127 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1128 auto d = openDir(root);
1129 while (auto e = ::readdir(d.get())) {
1130 if (e->d_type == DT_REG) {
1131 auto name = std::string_view(e->d_name);
1132 if (name.starts_with(constants().mountpointMdPrefix)) {
1133 permanentBindPoints
1134 .emplace_back(name,
1135 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1136 ifs->control,
1137 path::join(root,
1138 name)));
1139 if (permanentBindPoints.back().second.dest_path().empty() ||
1140 permanentBindPoints.back().second.source_subdir().empty()) {
1141 permanentBindPoints.pop_back();
1142 mIncFs->unlink(ifs->control, path::join(root, name));
1143 } else {
1144 LOG(INFO) << "Permanent bind record: '"
1145 << permanentBindPoints.back().second.source_subdir() << "'->'"
1146 << permanentBindPoints.back().second.dest_path() << "'";
1147 }
1148 }
1149 } else if (e->d_type == DT_DIR) {
1150 if (e->d_name == "."sv || e->d_name == ".."sv) {
1151 continue;
1152 }
1153 auto name = std::string_view(e->d_name);
1154 if (name.starts_with(constants().storagePrefix)) {
1155 int storageId;
1156 const auto res =
1157 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1158 name.data() + name.size(), storageId);
1159 if (res.ec != std::errc{} || *res.ptr != '_') {
1160 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1161 << "' for mount " << expectedRoot;
1162 continue;
1163 }
1164 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1165 if (!inserted) {
1166 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1167 << " for mount " << expectedRoot;
1168 continue;
1169 }
1170 ifs->storages.insert_or_assign(storageId,
1171 IncFsMount::Storage{path::join(root, name)});
1172 mNextId = std::max(mNextId, storageId + 1);
1173 }
1174 }
1175 }
1176
1177 if (ifs->storages.empty()) {
1178 LOG(WARNING) << "No valid storages in mount " << root;
1179 return;
1180 }
1181
1182 // now match the mounted directories with what we expect to have in the metadata
1183 {
1184 std::unique_lock l(mLock, std::defer_lock);
1185 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1186 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1187 [&, bindRecord = bindRecord](auto&& bind) {
1188 return bind.second == bindRecord.dest_path() &&
1189 path::join(root, bind.first) ==
1190 bindRecord.source_subdir();
1191 });
1192 if (mountedIt != binds.end()) {
1193 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1194 << " to mount " << mountedIt->first;
1195 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1196 std::move(*bindRecord.mutable_source_subdir()),
1197 std::move(*bindRecord.mutable_dest_path()),
1198 BindKind::Permanent);
1199 if (mountedIt != binds.end() - 1) {
1200 std::iter_swap(mountedIt, binds.end() - 1);
1201 }
1202 binds = binds.first(binds.size() - 1);
1203 } else {
1204 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1205 << ", mounting";
1206 // doesn't exist - try mounting back
1207 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1208 std::move(*bindRecord.mutable_source_subdir()),
1209 std::move(*bindRecord.mutable_dest_path()),
1210 BindKind::Permanent, l)) {
1211 mIncFs->unlink(ifs->control, metadataFile);
1212 }
1213 }
1214 }
1215 }
1216
1217 // if anything stays in |binds| those are probably temporary binds; system restarted since
1218 // they were mounted - so let's unmount them all.
1219 for (auto&& [source, target] : binds) {
1220 if (source.empty()) {
1221 continue;
1222 }
1223 mVold->unmountIncFs(std::string(target));
1224 }
1225 cleanupMounts.release(); // ifs now manages everything
1226
1227 if (ifs->bindPoints.empty()) {
1228 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1229 deleteStorage(*ifs);
1230 return;
1231 }
1232
1233 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1234 CHECK(ifs->dataLoaderStub);
1235
1236 mountedRootNames.insert(path::basename(ifs->root));
1237
1238 // not locking here at all: we're still in the constructor, no other calls can happen
1239 mMounts[ifs->mountId] = std::move(ifs);
1240 });
1241
1242 return mountedRootNames;
1243}
1244
1245void IncrementalService::mountExistingImages(
1246 const std::unordered_set<std::string_view>& mountedRootNames) {
1247 auto dir = openDir(mIncrementalDir);
1248 if (!dir) {
1249 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1250 return;
1251 }
1252 while (auto entry = ::readdir(dir.get())) {
1253 if (entry->d_type != DT_DIR) {
1254 continue;
1255 }
1256 std::string_view name = entry->d_name;
1257 if (!name.starts_with(constants().mountKeyPrefix)) {
1258 continue;
1259 }
1260 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001261 continue;
1262 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001263 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001264 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001265 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001266 }
1267 }
1268}
1269
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001270bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001271 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001272 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001273
Songchun Fan3c82a302019-11-29 14:23:45 -08001274 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001275 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001276 if (!status.isOk()) {
1277 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1278 return false;
1279 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001280
1281 int cmd = controlParcel.cmd.release().release();
1282 int pendingReads = controlParcel.pendingReads.release().release();
1283 int logs = controlParcel.log.release().release();
1284 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001285
1286 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1287
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001288 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1289 path::join(mountTarget, constants().infoMdName));
1290 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001291 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1292 return false;
1293 }
1294
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001295 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001296 mNextId = std::max(mNextId, ifs->mountId + 1);
1297
Alex Buynytskyy04035452020-06-06 20:15:58 -07001298 // Check if marker file present.
1299 if (checkReadLogsDisabledMarker(mountTarget)) {
1300 ifs->disableReadLogs();
1301 }
1302
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001303 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001304 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001305 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001306 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001307 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001308 dataLoaderParams.packageName = loader.package_name();
1309 dataLoaderParams.className = loader.class_name();
1310 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001311 }
1312
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001313 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001314 CHECK(ifs->dataLoaderStub);
1315
Songchun Fan3c82a302019-11-29 14:23:45 -08001316 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001317 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001318 while (auto e = ::readdir(d.get())) {
1319 if (e->d_type == DT_REG) {
1320 auto name = std::string_view(e->d_name);
1321 if (name.starts_with(constants().mountpointMdPrefix)) {
1322 bindPoints.emplace_back(name,
1323 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1324 ifs->control,
1325 path::join(mountTarget,
1326 name)));
1327 if (bindPoints.back().second.dest_path().empty() ||
1328 bindPoints.back().second.source_subdir().empty()) {
1329 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001330 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001331 }
1332 }
1333 } else if (e->d_type == DT_DIR) {
1334 if (e->d_name == "."sv || e->d_name == ".."sv) {
1335 continue;
1336 }
1337 auto name = std::string_view(e->d_name);
1338 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001339 int storageId;
1340 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1341 name.data() + name.size(), storageId);
1342 if (res.ec != std::errc{} || *res.ptr != '_') {
1343 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1344 << root;
1345 continue;
1346 }
1347 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001348 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001349 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001350 << " for mount " << root;
1351 continue;
1352 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001353 ifs->storages.insert_or_assign(storageId,
1354 IncFsMount::Storage{
1355 path::join(root, constants().mount, name)});
1356 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001357 }
1358 }
1359 }
1360
1361 if (ifs->storages.empty()) {
1362 LOG(WARNING) << "No valid storages in mount " << root;
1363 return false;
1364 }
1365
1366 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001367 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001368 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001369 for (auto&& bp : bindPoints) {
1370 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1371 std::move(*bp.second.mutable_source_subdir()),
1372 std::move(*bp.second.mutable_dest_path()),
1373 BindKind::Permanent, l);
1374 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001375 }
1376
1377 if (bindCount == 0) {
1378 LOG(WARNING) << "No valid bind points for mount " << root;
1379 deleteStorage(*ifs);
1380 return false;
1381 }
1382
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001383 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001384 mMounts[ifs->mountId] = std::move(ifs);
1385 return true;
1386}
1387
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001388void IncrementalService::runCmdLooper() {
1389 constexpr auto kTimeoutMsecs = 1000;
1390 while (mRunning.load(std::memory_order_relaxed)) {
1391 mLooper->pollAll(kTimeoutMsecs);
1392 }
1393}
1394
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001395IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001396 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001397 const DataLoaderStatusListener* statusListener,
1398 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001399 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001400 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1401 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001402 return ifs.dataLoaderStub;
1403}
1404
1405void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001406 const DataLoaderStatusListener* statusListener,
1407 StorageHealthCheckParams&& healthCheckParams,
1408 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001409 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001410 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001411 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001412 }
1413
Songchun Fan3c82a302019-11-29 14:23:45 -08001414 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001415 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001416 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1417 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1418 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001419 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001420
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001421 ifs.dataLoaderStub =
1422 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001423 statusListener, std::move(healthCheckParams), healthListener,
1424 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001425}
1426
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001427template <class Duration>
1428static long elapsedMcs(Duration start, Duration end) {
1429 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1430}
1431
1432// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001433// Lib files should be placed next to the APK file in the following matter:
1434// Example:
1435// /path/to/base.apk
1436// /path/to/lib/arm/first.so
1437// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001438bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1439 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001440 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001441 auto start = Clock::now();
1442
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001443 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001444 if (!ifs) {
1445 LOG(ERROR) << "Invalid storage " << storage;
1446 return false;
1447 }
1448
Songchun Fanc8975312020-07-13 12:14:37 -07001449 const auto targetLibPathRelativeToStorage =
1450 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1451 libDirRelativePath);
1452
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001453 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001454 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1455 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001456 << " errno: " << res;
1457 return false;
1458 }
1459
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001460 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001461 ZipArchiveHandle zipFileHandle;
1462 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001463 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1464 return false;
1465 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001466
1467 // Need a shared pointer: will be passing it into all unpacking jobs.
1468 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001469 void* cookie = nullptr;
1470 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001471 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001472 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1473 return false;
1474 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001475 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001476 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1477
1478 auto openZipTs = Clock::now();
1479
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001480 std::vector<Job> jobQueue;
1481 ZipEntry entry;
1482 std::string_view fileName;
1483 while (!Next(cookie, &entry, &fileName)) {
1484 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001485 continue;
1486 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001487
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001488 if (!extractNativeLibs) {
1489 // ensure the file is properly aligned and unpacked
1490 if (entry.method != kCompressStored) {
1491 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1492 return false;
1493 }
1494 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1495 LOG(WARNING) << "Library " << fileName
1496 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1497 << entry.offset;
1498 return false;
1499 }
1500 continue;
1501 }
1502
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001503 auto startFileTs = Clock::now();
1504
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001505 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001506 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001507 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001508 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001509 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001510 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001511 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1512 << "; skipping extraction, spent "
1513 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1514 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001515 continue;
1516 }
1517
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001518 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001519 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001520 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001521 .signature = {},
1522 // Metadata of the new lib file is its relative path
1523 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1524 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001525 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001526 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1527 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001528 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001529 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001530 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001531 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001532
1533 auto makeFileTs = Clock::now();
1534
Songchun Fanafaf6e92020-03-18 14:12:20 -07001535 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001536 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001537 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001538 LOG(INFO) << "incfs: Extracted " << libName
1539 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001540 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001541 continue;
1542 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001543
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001544 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1545 libFileId, libPath = std::move(targetLibPath),
1546 makeFileTs]() mutable {
1547 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001548 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001549
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001550 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001551 auto prepareJobTs = Clock::now();
1552 LOG(INFO) << "incfs: Processed " << libName << ": "
1553 << elapsedMcs(startFileTs, prepareJobTs)
1554 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1555 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001556 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001557 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001558
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001559 auto processedTs = Clock::now();
1560
1561 if (!jobQueue.empty()) {
1562 {
1563 std::lock_guard lock(mJobMutex);
1564 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001565 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001566 if (existingJobs.empty()) {
1567 existingJobs = std::move(jobQueue);
1568 } else {
1569 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1570 std::move_iterator(jobQueue.end()));
1571 }
1572 }
1573 }
1574 mJobCondition.notify_all();
1575 }
1576
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001577 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001578 auto end = Clock::now();
1579 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1580 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1581 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001582 << " make files: " << elapsedMcs(openZipTs, processedTs)
1583 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001584 }
1585
1586 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001587}
1588
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001589void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1590 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001591 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001592 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001593 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001594 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001595 return;
1596 }
1597
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001598 auto startedTs = Clock::now();
1599
1600 // Write extracted data to new file
1601 // NOTE: don't zero-initialize memory, it may take a while for nothing
1602 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1603 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001604 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001605 return;
1606 }
1607
1608 auto extractFileTs = Clock::now();
1609
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001610 if (setFileContent(ifs, libFileId, debugLibPath,
1611 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001612 return;
1613 }
1614
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001615 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001616 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001617 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1618 << entry.compressed_length << " -> " << entry.uncompressed_length
1619 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001620 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1621 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001622 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001623 }
1624}
1625
1626bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001627 struct WaitPrinter {
1628 const Clock::time_point startTs = Clock::now();
1629 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001630 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001631 const auto endTs = Clock::now();
1632 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1633 << elapsedMcs(startTs, endTs) << "mcs";
1634 }
1635 }
1636 } waitPrinter;
1637
1638 MountId mount;
1639 {
1640 auto ifs = getIfs(storage);
1641 if (!ifs) {
1642 return true;
1643 }
1644 mount = ifs->mountId;
1645 }
1646
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001647 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001648 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001649 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001650 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001651 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001652 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001653}
1654
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001655int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1656 std::string_view debugFilePath,
1657 std::span<const uint8_t> data) const {
1658 auto startTs = Clock::now();
1659
1660 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1661 if (!writeFd.ok()) {
1662 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1663 << " errno: " << writeFd.get();
1664 return writeFd.get();
1665 }
1666
1667 const auto dataLength = data.size();
1668
1669 auto openFileTs = Clock::now();
1670 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1671 std::vector<IncFsDataBlock> instructions(numBlocks);
1672 for (int i = 0; i < numBlocks; i++) {
1673 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1674 instructions[i] = IncFsDataBlock{
1675 .fileFd = writeFd.get(),
1676 .pageIndex = static_cast<IncFsBlockIndex>(i),
1677 .compression = INCFS_COMPRESSION_KIND_NONE,
1678 .kind = INCFS_BLOCK_KIND_DATA,
1679 .dataSize = static_cast<uint32_t>(blockSize),
1680 .data = reinterpret_cast<const char*>(data.data()),
1681 };
1682 data = data.subspan(blockSize);
1683 }
1684 auto prepareInstsTs = Clock::now();
1685
1686 size_t res = mIncFs->writeBlocks(instructions);
1687 if (res != instructions.size()) {
1688 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1689 return res;
1690 }
1691
1692 if (perfLoggingEnabled()) {
1693 auto endTs = Clock::now();
1694 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1695 << " bytes): " << elapsedMcs(startTs, endTs)
1696 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1697 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1698 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1699 }
1700
1701 return 0;
1702}
1703
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001704int IncrementalService::isFileFullyLoaded(StorageId storage, const std::string& path) const {
1705 std::unique_lock l(mLock);
1706 const auto ifs = getIfsLocked(storage);
1707 if (!ifs) {
1708 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1709 return -EINVAL;
1710 }
1711 const auto storageInfo = ifs->storages.find(storage);
1712 if (storageInfo == ifs->storages.end()) {
1713 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1714 return -EINVAL;
1715 }
1716 l.unlock();
1717 return isFileFullyLoadedFromPath(*ifs, path);
1718}
1719
1720int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1721 std::string_view filePath) const {
1722 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1723 if (filledBlocks < 0) {
1724 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1725 << filePath << " errno: " << filledBlocks;
1726 return filledBlocks;
1727 }
1728 if (totalBlocks < filledBlocks) {
1729 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1730 return -EINVAL;
1731 }
1732 return totalBlocks - filledBlocks;
1733}
1734
Songchun Fan374f7652020-08-20 08:40:29 -07001735float IncrementalService::getLoadingProgress(StorageId storage) const {
1736 std::unique_lock l(mLock);
1737 const auto ifs = getIfsLocked(storage);
1738 if (!ifs) {
1739 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
1740 return -EINVAL;
1741 }
1742 const auto storageInfo = ifs->storages.find(storage);
1743 if (storageInfo == ifs->storages.end()) {
1744 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
1745 return -EINVAL;
1746 }
1747 l.unlock();
1748 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
1749}
1750
1751float IncrementalService::getLoadingProgressFromPath(const IncFsMount& ifs,
1752 std::string_view storagePath) const {
1753 size_t totalBlocks = 0, filledBlocks = 0;
1754 const auto filePaths = mFs->listFilesRecursive(storagePath);
1755 for (const auto& filePath : filePaths) {
1756 const auto [filledBlocksCount, totalBlocksCount] =
1757 mIncFs->countFilledBlocks(ifs.control, filePath);
1758 if (filledBlocksCount < 0) {
1759 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1760 << " errno: " << filledBlocksCount;
1761 return filledBlocksCount;
1762 }
1763 totalBlocks += totalBlocksCount;
1764 filledBlocks += filledBlocksCount;
1765 }
1766
1767 if (totalBlocks == 0) {
Songchun Fan425862f2020-08-25 13:12:16 -07001768 // No file in the storage or files are empty; regarded as fully loaded
1769 return 1;
Songchun Fan374f7652020-08-20 08:40:29 -07001770 }
1771 return (float)filledBlocks / (float)totalBlocks;
1772}
1773
Songchun Fana7098592020-09-03 11:45:53 -07001774bool IncrementalService::updateLoadingProgress(
1775 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1776 const auto progress = getLoadingProgress(storage);
1777 if (progress < 0) {
1778 // Failed to get progress from incfs, abort.
1779 return false;
1780 }
1781 progressListener->onStorageLoadingProgressChanged(storage, progress);
1782 if (progress > 1 - 0.001f) {
1783 // Stop updating progress once it is fully loaded
1784 return true;
1785 }
1786 static constexpr auto kProgressUpdateInterval = 1000ms;
1787 addTimedJob(*mProgressUpdateJobQueue, storage, kProgressUpdateInterval /* repeat after 1s */,
1788 [storage, progressListener, this]() {
1789 updateLoadingProgress(storage, progressListener);
1790 });
1791 return true;
1792}
1793
1794bool IncrementalService::registerLoadingProgressListener(
1795 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1796 return updateLoadingProgress(storage, progressListener);
1797}
1798
1799bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
1800 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
1801}
1802
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001803bool IncrementalService::perfLoggingEnabled() {
1804 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1805 return enabled;
1806}
1807
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001808void IncrementalService::runJobProcessing() {
1809 for (;;) {
1810 std::unique_lock lock(mJobMutex);
1811 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1812 if (!mRunning) {
1813 return;
1814 }
1815
1816 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001817 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001818 auto queue = std::move(it->second);
1819 mJobQueue.erase(it);
1820 lock.unlock();
1821
1822 for (auto&& job : queue) {
1823 job();
1824 }
1825
1826 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001827 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001828 lock.unlock();
1829 mJobCondition.notify_all();
1830 }
1831}
1832
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001833void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001834 sp<IAppOpsCallback> listener;
1835 {
1836 std::unique_lock lock{mCallbacksLock};
1837 auto& cb = mCallbackRegistered[packageName];
1838 if (cb) {
1839 return;
1840 }
1841 cb = new AppOpsListener(*this, packageName);
1842 listener = cb;
1843 }
1844
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001845 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1846 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001847}
1848
1849bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1850 sp<IAppOpsCallback> listener;
1851 {
1852 std::unique_lock lock{mCallbacksLock};
1853 auto found = mCallbackRegistered.find(packageName);
1854 if (found == mCallbackRegistered.end()) {
1855 return false;
1856 }
1857 listener = found->second;
1858 mCallbackRegistered.erase(found);
1859 }
1860
1861 mAppOpsManager->stopWatchingMode(listener);
1862 return true;
1863}
1864
1865void IncrementalService::onAppOpChanged(const std::string& packageName) {
1866 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001867 return;
1868 }
1869
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001870 std::vector<IfsMountPtr> affected;
1871 {
1872 std::lock_guard l(mLock);
1873 affected.reserve(mMounts.size());
1874 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001875 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001876 affected.push_back(ifs);
1877 }
1878 }
1879 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001880 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001881 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001882 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001883}
1884
Songchun Fana7098592020-09-03 11:45:53 -07001885bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
1886 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001887 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07001888 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001889 }
Songchun Fana7098592020-09-03 11:45:53 -07001890 timedQueue.addJob(id, after, std::move(what));
1891 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001892}
1893
Songchun Fana7098592020-09-03 11:45:53 -07001894bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001895 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07001896 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001897 }
Songchun Fana7098592020-09-03 11:45:53 -07001898 timedQueue.removeJobs(id);
1899 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001900}
1901
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001902IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1903 DataLoaderParamsParcel&& params,
1904 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001905 const DataLoaderStatusListener* statusListener,
1906 StorageHealthCheckParams&& healthCheckParams,
1907 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001908 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001909 : mService(service),
1910 mId(id),
1911 mParams(std::move(params)),
1912 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001913 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
1914 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001915 mHealthPath(std::move(healthPath)),
1916 mHealthCheckParams(std::move(healthCheckParams)) {
1917 if (mHealthListener) {
1918 if (!isHealthParamsValid()) {
1919 mHealthListener = {};
1920 }
1921 } else {
1922 // Disable advanced health check statuses.
1923 mHealthCheckParams.blockedTimeoutMs = -1;
1924 }
1925 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001926}
1927
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001928IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001929 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001930 cleanupResources();
1931 }
1932}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001933
1934void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001935 auto now = Clock::now();
1936 {
1937 std::unique_lock lock(mMutex);
1938 mHealthPath.clear();
1939 unregisterFromPendingReads();
1940 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07001941 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001942 }
1943
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001944 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001945
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001946 {
1947 std::unique_lock lock(mMutex);
1948 mParams = {};
1949 mControl = {};
1950 mHealthControl = {};
1951 mHealthListener = {};
1952 mStatusCondition.wait_until(lock, now + 60s, [this] {
1953 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1954 });
1955 mStatusListener = {};
1956 mId = kInvalidStorageId;
1957 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001958}
1959
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001960sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1961 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001962 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001963 if (!status.isOk()) {
1964 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1965 return {};
1966 }
1967 if (!dataloader) {
1968 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1969 return {};
1970 }
1971 return dataloader;
1972}
1973
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001974bool IncrementalService::DataLoaderStub::requestCreate() {
1975 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1976}
1977
1978bool IncrementalService::DataLoaderStub::requestStart() {
1979 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1980}
1981
1982bool IncrementalService::DataLoaderStub::requestDestroy() {
1983 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1984}
1985
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001986bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001987 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001988 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001989 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001990 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001991 return fsmStep();
1992}
1993
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001994void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001995 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001996 mTargetStatus = status;
1997 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001998 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001999 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002000}
2001
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002002bool IncrementalService::DataLoaderStub::bind() {
2003 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002004 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002005 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002006 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002007 return false;
2008 }
2009 return true;
2010}
2011
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002012bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002013 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002014 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002015 return false;
2016 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002017 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002018 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002019 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002020 return false;
2021 }
2022 return true;
2023}
2024
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002025bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002026 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002027 if (!dataloader) {
2028 return false;
2029 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002030 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002031 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002032 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002033 return false;
2034 }
2035 return true;
2036}
2037
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002038bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002039 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002040}
2041
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002042bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002043 if (!isValid()) {
2044 return false;
2045 }
2046
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002047 int currentStatus;
2048 int targetStatus;
2049 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002050 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002051 currentStatus = mCurrentStatus;
2052 targetStatus = mTargetStatus;
2053 }
2054
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002055 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002056
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002057 if (currentStatus == targetStatus) {
2058 return true;
2059 }
2060
2061 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002062 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2063 // Do nothing, this is a reset state.
2064 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002065 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
2066 return destroy();
2067 }
2068 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2069 switch (currentStatus) {
2070 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2071 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2072 return start();
2073 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002074 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002075 }
2076 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2077 switch (currentStatus) {
2078 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002079 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002080 return bind();
2081 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002082 return create();
2083 }
2084 break;
2085 default:
2086 LOG(ERROR) << "Invalid target status: " << targetStatus
2087 << ", current status: " << currentStatus;
2088 break;
2089 }
2090 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002091}
2092
2093binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002094 if (!isValid()) {
2095 return binder::Status::
2096 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2097 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002098 if (id() != mountId) {
2099 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002100 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2101 }
2102
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002103 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002104 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002105 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002106 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002107 if (mCurrentStatus == newStatus) {
2108 return binder::Status::ok();
2109 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002110
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002111 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002112 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002113 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002114
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002115 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002116
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002117 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002118 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2119 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002120 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002121 }
2122
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002123 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002124 << newStatus << " (target " << targetStatus << ")";
2125
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002126 if (listener) {
2127 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002128 }
2129
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002130 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002131
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002132 mStatusCondition.notify_all();
2133
Songchun Fan3c82a302019-11-29 14:23:45 -08002134 return binder::Status::ok();
2135}
2136
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002137bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2138 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2139 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002140}
2141
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002142void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2143 int healthStatus) {
2144 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2145 if (healthListener) {
2146 healthListener->onHealthStatus(id(), healthStatus);
2147 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002148}
2149
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002150void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2151 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002152
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002153 int healthStatusToReport = -1;
2154 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002155
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002156 {
2157 std::unique_lock lock(mMutex);
2158 unregisterFromPendingReads();
2159
2160 healthListener = mHealthListener;
2161
2162 // Healthcheck depends on timestamp of the oldest pending read.
2163 // To get it, we need to re-open a pendingReads FD to get a full list of reads.
Songchun Fan374f7652020-08-20 08:40:29 -07002164 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2165 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002166 const auto now = Clock::now();
2167 const auto kernelTsUs = getOldestPendingReadTs();
2168 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002169 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2170 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002171 mHealthBase = {now, kernelTsUs};
2172 }
2173
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002174 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2175 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002176 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2177 registerForPendingReads();
2178 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2179 lock.unlock();
2180 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002181 return;
2182 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002183
2184 resetHealthControl();
2185
2186 // Always make sure the data loader is started.
2187 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2188
2189 // Skip any further processing if health check params are invalid.
2190 if (!isHealthParamsValid()) {
2191 LOG(DEBUG) << id()
2192 << ": Skip any further processing if health check params are invalid.";
2193 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2194 lock.unlock();
2195 onHealthStatus(healthListener, healthStatusToReport);
2196 // Triggering data loader start. This is a one-time action.
2197 fsmStep();
2198 return;
2199 }
2200
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002201 // Don't schedule timer job less than 500ms in advance.
2202 static constexpr auto kTolerance = 500ms;
2203
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002204 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2205 const auto unhealthyTimeout =
2206 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2207 const auto unhealthyMonitoring =
2208 std::max(1000ms,
2209 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2210
2211 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2212 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002213 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002214
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002215 Milliseconds checkBackAfter;
2216 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002217 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002218 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002219 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002220 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002221 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002222 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002223 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2224 } else {
2225 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002226 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002227 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2228 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002229 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002230 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002231 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2232 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002233 }
2234
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002235 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002236 if (healthStatusToReport != -1) {
2237 onHealthStatus(healthListener, healthStatusToReport);
2238 }
2239
2240 fsmStep();
2241}
2242
2243const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2244 if (mHealthPath.empty()) {
2245 resetHealthControl();
2246 return mHealthControl;
2247 }
2248 if (mHealthControl.pendingReads() < 0) {
2249 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2250 }
2251 if (mHealthControl.pendingReads() < 0) {
2252 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2253 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2254 << mHealthControl.logs() << ")";
2255 }
2256 return mHealthControl;
2257}
2258
2259void IncrementalService::DataLoaderStub::resetHealthControl() {
2260 mHealthControl = {};
2261}
2262
2263BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2264 auto result = kMaxBootClockTsUs;
2265
2266 const auto& control = initializeHealthControl();
2267 if (control.pendingReads() < 0) {
2268 return result;
2269 }
2270
2271 std::vector<incfs::ReadInfo> pendingReads;
2272 if (mService.mIncFs->waitForPendingReads(control, 0ms, &pendingReads) !=
2273 android::incfs::WaitResult::HaveData ||
2274 pendingReads.empty()) {
2275 return result;
2276 }
2277
2278 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
2279 << pendingReads.size() << ": " << pendingReads.front().bootClockTsUs;
2280
2281 for (auto&& pendingRead : pendingReads) {
2282 result = std::min(result, pendingRead.bootClockTsUs);
2283 }
2284 return result;
2285}
2286
2287void IncrementalService::DataLoaderStub::registerForPendingReads() {
2288 const auto pendingReadsFd = mHealthControl.pendingReads();
2289 if (pendingReadsFd < 0) {
2290 return;
2291 }
2292
2293 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2294
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002295 mService.mLooper->addFd(
2296 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2297 [](int, int, void* data) -> int {
2298 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002299 self->updateHealthStatus(/*baseline=*/true);
2300 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002301 },
2302 this);
2303 mService.mLooper->wake();
2304}
2305
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002306void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002307 const auto pendingReadsFd = mHealthControl.pendingReads();
2308 if (pendingReadsFd < 0) {
2309 return;
2310 }
2311
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002312 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2313
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002314 mService.mLooper->removeFd(pendingReadsFd);
2315 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002316}
2317
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002318void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002319 dprintf(fd, " dataLoader: {\n");
2320 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2321 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2322 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002323 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002324 dprintf(fd, " health: {\n");
2325 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2326 dprintf(fd, " base: %lldmcs (%lld)\n",
2327 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2328 (long long)mHealthBase.kernelTsUs);
2329 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2330 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2331 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2332 int(mHealthCheckParams.unhealthyMonitoringMs));
2333 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002334 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002335 dprintf(fd, " dataLoaderParams: {\n");
2336 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2337 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2338 dprintf(fd, " className: %s\n", params.className.c_str());
2339 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2340 dprintf(fd, " }\n");
2341 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002342}
2343
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002344void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2345 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002346}
2347
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002348binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2349 bool enableReadLogs, int32_t* _aidl_return) {
2350 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2351 return binder::Status::ok();
2352}
2353
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002354FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2355 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2356}
2357
Songchun Fan3c82a302019-11-29 14:23:45 -08002358} // namespace android::incremental