blob: 10a508b06086f6dde8be01729cfb233f4895e29a [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,
862 incfs::NewFileParams params) {
863 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 }
870 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800871 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700872 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800873 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800874 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800875 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800876 }
877 return -EINVAL;
878}
879
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800880int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800881 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700882 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800883 if (normPath.empty()) {
884 return -EINVAL;
885 }
886 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800887 }
888 return -EINVAL;
889}
890
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800891int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800892 const auto ifs = getIfs(storageId);
893 if (!ifs) {
894 return -EINVAL;
895 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700896 return makeDirs(*ifs, storageId, path, mode);
897}
898
899int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
900 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800901 std::string normPath = normalizePathToStorage(ifs, storageId, path);
902 if (normPath.empty()) {
903 return -EINVAL;
904 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700905 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800906}
907
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800908int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
909 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700910 std::unique_lock l(mLock);
911 auto ifsSrc = getIfsLocked(sourceStorageId);
912 if (!ifsSrc) {
913 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800914 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700915 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
916 return -EINVAL;
917 }
918 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700919 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
920 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700921 if (normOldPath.empty() || normNewPath.empty()) {
922 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
923 return -EINVAL;
924 }
925 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800926}
927
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800928int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800929 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700930 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800931 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800932 }
933 return -EINVAL;
934}
935
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800936int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
937 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800938 std::string&& target, BindKind kind,
939 std::unique_lock<std::mutex>& mainLock) {
940 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700941 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800942 return -EINVAL;
943 }
944
945 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700946 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800947 if (kind != BindKind::Temporary) {
948 metadata::BindPoint bp;
949 bp.set_storage_id(storage);
950 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800951 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800952 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800953 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800954 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800955 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700956 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
957 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
958 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800959 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700960 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800961 return int(node);
962 }
963 }
964
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700965 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
966 std::move(target), kind, mainLock);
967 if (res) {
968 mIncFs->unlink(ifs.control, metadataFullPath);
969 }
970 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800971}
972
973int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800974 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800975 std::string&& target, BindKind kind,
976 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800977 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800978 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800979 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800980 if (!status.isOk()) {
981 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
982 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
983 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
984 : status.serviceSpecificErrorCode() == 0
985 ? -EFAULT
986 : status.serviceSpecificErrorCode()
987 : -EIO;
988 }
989 }
990
991 if (!mainLock.owns_lock()) {
992 mainLock.lock();
993 }
994 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700995 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
996 std::move(target), kind);
997 return 0;
998}
999
1000void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1001 std::string&& metadataName, std::string&& source,
1002 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001003 const auto [it, _] =
1004 ifs.bindPoints.insert_or_assign(target,
1005 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001006 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001007 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001008}
1009
1010RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1011 const auto ifs = getIfs(storage);
1012 if (!ifs) {
1013 return {};
1014 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001015 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001016 if (normPath.empty()) {
1017 return {};
1018 }
1019 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001020}
1021
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001022RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001023 const auto ifs = getIfs(storage);
1024 if (!ifs) {
1025 return {};
1026 }
1027 return mIncFs->getMetadata(ifs->control, node);
1028}
1029
Songchun Fan3c82a302019-11-29 14:23:45 -08001030bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001031 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001032 {
1033 std::unique_lock l(mLock);
1034 const auto& ifs = getIfsLocked(storage);
1035 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001036 return false;
1037 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001038 dataLoaderStub = ifs->dataLoaderStub;
1039 if (!dataLoaderStub) {
1040 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001041 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001042 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001043 dataLoaderStub->requestStart();
1044 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001045}
1046
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001047std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1048 std::unordered_set<std::string_view> mountedRootNames;
1049 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1050 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1051 for (auto [source, target] : binds) {
1052 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1053 LOG(INFO) << " " << path::join(root, source);
1054 }
1055
1056 // Ensure it's a kind of a mount that's managed by IncrementalService
1057 if (path::basename(root) != constants().mount ||
1058 path::basename(backingDir) != constants().backing) {
1059 return;
1060 }
1061 const auto expectedRoot = path::dirname(root);
1062 if (path::dirname(backingDir) != expectedRoot) {
1063 return;
1064 }
1065 if (path::dirname(expectedRoot) != mIncrementalDir) {
1066 return;
1067 }
1068 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1069 return;
1070 }
1071
1072 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1073
1074 // make sure we clean up the mount if it happens to be a bad one.
1075 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1076 auto cleanupFiles = makeCleanup([&]() {
1077 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1078 IncFsMount::cleanupFilesystem(expectedRoot);
1079 });
1080 auto cleanupMounts = makeCleanup([&]() {
1081 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1082 for (auto&& [_, target] : binds) {
1083 mVold->unmountIncFs(std::string(target));
1084 }
1085 mVold->unmountIncFs(std::string(root));
1086 });
1087
1088 auto control = mIncFs->openMount(root);
1089 if (!control) {
1090 LOG(INFO) << "failed to open mount " << root;
1091 return;
1092 }
1093
1094 auto mountRecord =
1095 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1096 path::join(root, constants().infoMdName));
1097 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1098 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1099 return;
1100 }
1101
1102 auto mountId = mountRecord.storage().id();
1103 mNextId = std::max(mNextId, mountId + 1);
1104
1105 DataLoaderParamsParcel dataLoaderParams;
1106 {
1107 const auto& loader = mountRecord.loader();
1108 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1109 dataLoaderParams.packageName = loader.package_name();
1110 dataLoaderParams.className = loader.class_name();
1111 dataLoaderParams.arguments = loader.arguments();
1112 }
1113
1114 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1115 std::move(control), *this);
1116 cleanupFiles.release(); // ifs will take care of that now
1117
Alex Buynytskyy04035452020-06-06 20:15:58 -07001118 // Check if marker file present.
1119 if (checkReadLogsDisabledMarker(root)) {
1120 ifs->disableReadLogs();
1121 }
1122
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001123 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1124 auto d = openDir(root);
1125 while (auto e = ::readdir(d.get())) {
1126 if (e->d_type == DT_REG) {
1127 auto name = std::string_view(e->d_name);
1128 if (name.starts_with(constants().mountpointMdPrefix)) {
1129 permanentBindPoints
1130 .emplace_back(name,
1131 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1132 ifs->control,
1133 path::join(root,
1134 name)));
1135 if (permanentBindPoints.back().second.dest_path().empty() ||
1136 permanentBindPoints.back().second.source_subdir().empty()) {
1137 permanentBindPoints.pop_back();
1138 mIncFs->unlink(ifs->control, path::join(root, name));
1139 } else {
1140 LOG(INFO) << "Permanent bind record: '"
1141 << permanentBindPoints.back().second.source_subdir() << "'->'"
1142 << permanentBindPoints.back().second.dest_path() << "'";
1143 }
1144 }
1145 } else if (e->d_type == DT_DIR) {
1146 if (e->d_name == "."sv || e->d_name == ".."sv) {
1147 continue;
1148 }
1149 auto name = std::string_view(e->d_name);
1150 if (name.starts_with(constants().storagePrefix)) {
1151 int storageId;
1152 const auto res =
1153 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1154 name.data() + name.size(), storageId);
1155 if (res.ec != std::errc{} || *res.ptr != '_') {
1156 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1157 << "' for mount " << expectedRoot;
1158 continue;
1159 }
1160 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1161 if (!inserted) {
1162 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1163 << " for mount " << expectedRoot;
1164 continue;
1165 }
1166 ifs->storages.insert_or_assign(storageId,
1167 IncFsMount::Storage{path::join(root, name)});
1168 mNextId = std::max(mNextId, storageId + 1);
1169 }
1170 }
1171 }
1172
1173 if (ifs->storages.empty()) {
1174 LOG(WARNING) << "No valid storages in mount " << root;
1175 return;
1176 }
1177
1178 // now match the mounted directories with what we expect to have in the metadata
1179 {
1180 std::unique_lock l(mLock, std::defer_lock);
1181 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1182 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1183 [&, bindRecord = bindRecord](auto&& bind) {
1184 return bind.second == bindRecord.dest_path() &&
1185 path::join(root, bind.first) ==
1186 bindRecord.source_subdir();
1187 });
1188 if (mountedIt != binds.end()) {
1189 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1190 << " to mount " << mountedIt->first;
1191 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1192 std::move(*bindRecord.mutable_source_subdir()),
1193 std::move(*bindRecord.mutable_dest_path()),
1194 BindKind::Permanent);
1195 if (mountedIt != binds.end() - 1) {
1196 std::iter_swap(mountedIt, binds.end() - 1);
1197 }
1198 binds = binds.first(binds.size() - 1);
1199 } else {
1200 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1201 << ", mounting";
1202 // doesn't exist - try mounting back
1203 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1204 std::move(*bindRecord.mutable_source_subdir()),
1205 std::move(*bindRecord.mutable_dest_path()),
1206 BindKind::Permanent, l)) {
1207 mIncFs->unlink(ifs->control, metadataFile);
1208 }
1209 }
1210 }
1211 }
1212
1213 // if anything stays in |binds| those are probably temporary binds; system restarted since
1214 // they were mounted - so let's unmount them all.
1215 for (auto&& [source, target] : binds) {
1216 if (source.empty()) {
1217 continue;
1218 }
1219 mVold->unmountIncFs(std::string(target));
1220 }
1221 cleanupMounts.release(); // ifs now manages everything
1222
1223 if (ifs->bindPoints.empty()) {
1224 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1225 deleteStorage(*ifs);
1226 return;
1227 }
1228
1229 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1230 CHECK(ifs->dataLoaderStub);
1231
1232 mountedRootNames.insert(path::basename(ifs->root));
1233
1234 // not locking here at all: we're still in the constructor, no other calls can happen
1235 mMounts[ifs->mountId] = std::move(ifs);
1236 });
1237
1238 return mountedRootNames;
1239}
1240
1241void IncrementalService::mountExistingImages(
1242 const std::unordered_set<std::string_view>& mountedRootNames) {
1243 auto dir = openDir(mIncrementalDir);
1244 if (!dir) {
1245 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1246 return;
1247 }
1248 while (auto entry = ::readdir(dir.get())) {
1249 if (entry->d_type != DT_DIR) {
1250 continue;
1251 }
1252 std::string_view name = entry->d_name;
1253 if (!name.starts_with(constants().mountKeyPrefix)) {
1254 continue;
1255 }
1256 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001257 continue;
1258 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001259 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001260 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001261 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001262 }
1263 }
1264}
1265
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001266bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001267 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001268 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001269
Songchun Fan3c82a302019-11-29 14:23:45 -08001270 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001271 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001272 if (!status.isOk()) {
1273 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1274 return false;
1275 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001276
1277 int cmd = controlParcel.cmd.release().release();
1278 int pendingReads = controlParcel.pendingReads.release().release();
1279 int logs = controlParcel.log.release().release();
1280 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001281
1282 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1283
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001284 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1285 path::join(mountTarget, constants().infoMdName));
1286 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001287 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1288 return false;
1289 }
1290
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001291 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001292 mNextId = std::max(mNextId, ifs->mountId + 1);
1293
Alex Buynytskyy04035452020-06-06 20:15:58 -07001294 // Check if marker file present.
1295 if (checkReadLogsDisabledMarker(mountTarget)) {
1296 ifs->disableReadLogs();
1297 }
1298
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001299 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001300 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001301 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001302 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001303 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001304 dataLoaderParams.packageName = loader.package_name();
1305 dataLoaderParams.className = loader.class_name();
1306 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001307 }
1308
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001309 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001310 CHECK(ifs->dataLoaderStub);
1311
Songchun Fan3c82a302019-11-29 14:23:45 -08001312 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001313 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001314 while (auto e = ::readdir(d.get())) {
1315 if (e->d_type == DT_REG) {
1316 auto name = std::string_view(e->d_name);
1317 if (name.starts_with(constants().mountpointMdPrefix)) {
1318 bindPoints.emplace_back(name,
1319 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1320 ifs->control,
1321 path::join(mountTarget,
1322 name)));
1323 if (bindPoints.back().second.dest_path().empty() ||
1324 bindPoints.back().second.source_subdir().empty()) {
1325 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001326 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001327 }
1328 }
1329 } else if (e->d_type == DT_DIR) {
1330 if (e->d_name == "."sv || e->d_name == ".."sv) {
1331 continue;
1332 }
1333 auto name = std::string_view(e->d_name);
1334 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001335 int storageId;
1336 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1337 name.data() + name.size(), storageId);
1338 if (res.ec != std::errc{} || *res.ptr != '_') {
1339 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1340 << root;
1341 continue;
1342 }
1343 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001344 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001345 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001346 << " for mount " << root;
1347 continue;
1348 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001349 ifs->storages.insert_or_assign(storageId,
1350 IncFsMount::Storage{
1351 path::join(root, constants().mount, name)});
1352 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001353 }
1354 }
1355 }
1356
1357 if (ifs->storages.empty()) {
1358 LOG(WARNING) << "No valid storages in mount " << root;
1359 return false;
1360 }
1361
1362 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001363 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001364 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001365 for (auto&& bp : bindPoints) {
1366 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1367 std::move(*bp.second.mutable_source_subdir()),
1368 std::move(*bp.second.mutable_dest_path()),
1369 BindKind::Permanent, l);
1370 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001371 }
1372
1373 if (bindCount == 0) {
1374 LOG(WARNING) << "No valid bind points for mount " << root;
1375 deleteStorage(*ifs);
1376 return false;
1377 }
1378
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001379 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001380 mMounts[ifs->mountId] = std::move(ifs);
1381 return true;
1382}
1383
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001384void IncrementalService::runCmdLooper() {
1385 constexpr auto kTimeoutMsecs = 1000;
1386 while (mRunning.load(std::memory_order_relaxed)) {
1387 mLooper->pollAll(kTimeoutMsecs);
1388 }
1389}
1390
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001391IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001392 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001393 const DataLoaderStatusListener* statusListener,
1394 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001395 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001396 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1397 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001398 return ifs.dataLoaderStub;
1399}
1400
1401void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001402 const DataLoaderStatusListener* statusListener,
1403 StorageHealthCheckParams&& healthCheckParams,
1404 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001405 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001406 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001407 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001408 }
1409
Songchun Fan3c82a302019-11-29 14:23:45 -08001410 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001411 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001412 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1413 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1414 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001415 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001416
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001417 ifs.dataLoaderStub =
1418 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001419 statusListener, std::move(healthCheckParams), healthListener,
1420 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001421}
1422
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001423template <class Duration>
1424static long elapsedMcs(Duration start, Duration end) {
1425 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1426}
1427
1428// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001429// Lib files should be placed next to the APK file in the following matter:
1430// Example:
1431// /path/to/base.apk
1432// /path/to/lib/arm/first.so
1433// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001434bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1435 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001436 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001437 auto start = Clock::now();
1438
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001439 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001440 if (!ifs) {
1441 LOG(ERROR) << "Invalid storage " << storage;
1442 return false;
1443 }
1444
Songchun Fanc8975312020-07-13 12:14:37 -07001445 const auto targetLibPathRelativeToStorage =
1446 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1447 libDirRelativePath);
1448
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001449 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001450 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1451 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001452 << " errno: " << res;
1453 return false;
1454 }
1455
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001456 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001457 ZipArchiveHandle zipFileHandle;
1458 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001459 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1460 return false;
1461 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001462
1463 // Need a shared pointer: will be passing it into all unpacking jobs.
1464 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001465 void* cookie = nullptr;
1466 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001467 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001468 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1469 return false;
1470 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001471 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001472 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1473
1474 auto openZipTs = Clock::now();
1475
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001476 std::vector<Job> jobQueue;
1477 ZipEntry entry;
1478 std::string_view fileName;
1479 while (!Next(cookie, &entry, &fileName)) {
1480 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001481 continue;
1482 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001483
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001484 if (!extractNativeLibs) {
1485 // ensure the file is properly aligned and unpacked
1486 if (entry.method != kCompressStored) {
1487 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1488 return false;
1489 }
1490 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1491 LOG(WARNING) << "Library " << fileName
1492 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1493 << entry.offset;
1494 return false;
1495 }
1496 continue;
1497 }
1498
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001499 auto startFileTs = Clock::now();
1500
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001501 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001502 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001503 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001504 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001505 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001506 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001507 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1508 << "; skipping extraction, spent "
1509 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1510 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001511 continue;
1512 }
1513
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001514 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001515 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001516 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001517 .signature = {},
1518 // Metadata of the new lib file is its relative path
1519 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1520 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001521 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001522 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1523 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001524 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001525 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001526 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001527 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001528
1529 auto makeFileTs = Clock::now();
1530
Songchun Fanafaf6e92020-03-18 14:12:20 -07001531 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001532 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001533 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001534 LOG(INFO) << "incfs: Extracted " << libName
1535 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001536 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001537 continue;
1538 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001539
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001540 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1541 libFileId, libPath = std::move(targetLibPath),
1542 makeFileTs]() mutable {
1543 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001544 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001545
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001546 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001547 auto prepareJobTs = Clock::now();
1548 LOG(INFO) << "incfs: Processed " << libName << ": "
1549 << elapsedMcs(startFileTs, prepareJobTs)
1550 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1551 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001552 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001553 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001554
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001555 auto processedTs = Clock::now();
1556
1557 if (!jobQueue.empty()) {
1558 {
1559 std::lock_guard lock(mJobMutex);
1560 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001561 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001562 if (existingJobs.empty()) {
1563 existingJobs = std::move(jobQueue);
1564 } else {
1565 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1566 std::move_iterator(jobQueue.end()));
1567 }
1568 }
1569 }
1570 mJobCondition.notify_all();
1571 }
1572
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001573 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001574 auto end = Clock::now();
1575 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1576 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1577 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001578 << " make files: " << elapsedMcs(openZipTs, processedTs)
1579 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001580 }
1581
1582 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001583}
1584
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001585void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1586 ZipEntry& entry, const incfs::FileId& libFileId,
1587 std::string_view targetLibPath,
1588 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001589 if (!ifs) {
1590 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1591 return;
1592 }
1593
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001594 auto libName = path::basename(targetLibPath);
1595 auto startedTs = Clock::now();
1596
1597 // Write extracted data to new file
1598 // NOTE: don't zero-initialize memory, it may take a while for nothing
1599 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1600 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1601 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1602 return;
1603 }
1604
1605 auto extractFileTs = Clock::now();
1606
1607 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1608 if (!writeFd.ok()) {
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001609 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath
1610 << " errno: " << writeFd.get();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001611 return;
1612 }
1613
1614 auto openFileTs = Clock::now();
1615 const int numBlocks =
1616 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1617 std::vector<IncFsDataBlock> instructions(numBlocks);
1618 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1619 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001620 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001621 instructions[i] = IncFsDataBlock{
1622 .fileFd = writeFd.get(),
1623 .pageIndex = static_cast<IncFsBlockIndex>(i),
1624 .compression = INCFS_COMPRESSION_KIND_NONE,
1625 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001626 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001627 .data = reinterpret_cast<const char*>(remainingData.data()),
1628 };
1629 remainingData = remainingData.subspan(blockSize);
1630 }
1631 auto prepareInstsTs = Clock::now();
1632
1633 size_t res = mIncFs->writeBlocks(instructions);
1634 if (res != instructions.size()) {
1635 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1636 return;
1637 }
1638
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001639 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001640 auto endFileTs = Clock::now();
1641 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1642 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1643 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1644 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1645 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1646 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1647 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1648 }
1649}
1650
1651bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001652 struct WaitPrinter {
1653 const Clock::time_point startTs = Clock::now();
1654 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001655 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001656 const auto endTs = Clock::now();
1657 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1658 << elapsedMcs(startTs, endTs) << "mcs";
1659 }
1660 }
1661 } waitPrinter;
1662
1663 MountId mount;
1664 {
1665 auto ifs = getIfs(storage);
1666 if (!ifs) {
1667 return true;
1668 }
1669 mount = ifs->mountId;
1670 }
1671
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001672 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001673 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001674 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001675 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001676 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001677 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001678}
1679
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001680int IncrementalService::isFileFullyLoaded(StorageId storage, const std::string& path) const {
1681 std::unique_lock l(mLock);
1682 const auto ifs = getIfsLocked(storage);
1683 if (!ifs) {
1684 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1685 return -EINVAL;
1686 }
1687 const auto storageInfo = ifs->storages.find(storage);
1688 if (storageInfo == ifs->storages.end()) {
1689 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1690 return -EINVAL;
1691 }
1692 l.unlock();
1693 return isFileFullyLoadedFromPath(*ifs, path);
1694}
1695
1696int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1697 std::string_view filePath) const {
1698 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1699 if (filledBlocks < 0) {
1700 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1701 << filePath << " errno: " << filledBlocks;
1702 return filledBlocks;
1703 }
1704 if (totalBlocks < filledBlocks) {
1705 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1706 return -EINVAL;
1707 }
1708 return totalBlocks - filledBlocks;
1709}
1710
Songchun Fan374f7652020-08-20 08:40:29 -07001711float IncrementalService::getLoadingProgress(StorageId storage) const {
1712 std::unique_lock l(mLock);
1713 const auto ifs = getIfsLocked(storage);
1714 if (!ifs) {
1715 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
1716 return -EINVAL;
1717 }
1718 const auto storageInfo = ifs->storages.find(storage);
1719 if (storageInfo == ifs->storages.end()) {
1720 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
1721 return -EINVAL;
1722 }
1723 l.unlock();
1724 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
1725}
1726
1727float IncrementalService::getLoadingProgressFromPath(const IncFsMount& ifs,
1728 std::string_view storagePath) const {
1729 size_t totalBlocks = 0, filledBlocks = 0;
1730 const auto filePaths = mFs->listFilesRecursive(storagePath);
1731 for (const auto& filePath : filePaths) {
1732 const auto [filledBlocksCount, totalBlocksCount] =
1733 mIncFs->countFilledBlocks(ifs.control, filePath);
1734 if (filledBlocksCount < 0) {
1735 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1736 << " errno: " << filledBlocksCount;
1737 return filledBlocksCount;
1738 }
1739 totalBlocks += totalBlocksCount;
1740 filledBlocks += filledBlocksCount;
1741 }
1742
1743 if (totalBlocks == 0) {
Songchun Fan425862f2020-08-25 13:12:16 -07001744 // No file in the storage or files are empty; regarded as fully loaded
1745 return 1;
Songchun Fan374f7652020-08-20 08:40:29 -07001746 }
1747 return (float)filledBlocks / (float)totalBlocks;
1748}
1749
Songchun Fana7098592020-09-03 11:45:53 -07001750bool IncrementalService::updateLoadingProgress(
1751 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1752 const auto progress = getLoadingProgress(storage);
1753 if (progress < 0) {
1754 // Failed to get progress from incfs, abort.
1755 return false;
1756 }
1757 progressListener->onStorageLoadingProgressChanged(storage, progress);
1758 if (progress > 1 - 0.001f) {
1759 // Stop updating progress once it is fully loaded
1760 return true;
1761 }
1762 static constexpr auto kProgressUpdateInterval = 1000ms;
1763 addTimedJob(*mProgressUpdateJobQueue, storage, kProgressUpdateInterval /* repeat after 1s */,
1764 [storage, progressListener, this]() {
1765 updateLoadingProgress(storage, progressListener);
1766 });
1767 return true;
1768}
1769
1770bool IncrementalService::registerLoadingProgressListener(
1771 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1772 return updateLoadingProgress(storage, progressListener);
1773}
1774
1775bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
1776 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
1777}
1778
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001779bool IncrementalService::perfLoggingEnabled() {
1780 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1781 return enabled;
1782}
1783
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001784void IncrementalService::runJobProcessing() {
1785 for (;;) {
1786 std::unique_lock lock(mJobMutex);
1787 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1788 if (!mRunning) {
1789 return;
1790 }
1791
1792 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001793 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001794 auto queue = std::move(it->second);
1795 mJobQueue.erase(it);
1796 lock.unlock();
1797
1798 for (auto&& job : queue) {
1799 job();
1800 }
1801
1802 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001803 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001804 lock.unlock();
1805 mJobCondition.notify_all();
1806 }
1807}
1808
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001809void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001810 sp<IAppOpsCallback> listener;
1811 {
1812 std::unique_lock lock{mCallbacksLock};
1813 auto& cb = mCallbackRegistered[packageName];
1814 if (cb) {
1815 return;
1816 }
1817 cb = new AppOpsListener(*this, packageName);
1818 listener = cb;
1819 }
1820
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001821 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1822 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001823}
1824
1825bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1826 sp<IAppOpsCallback> listener;
1827 {
1828 std::unique_lock lock{mCallbacksLock};
1829 auto found = mCallbackRegistered.find(packageName);
1830 if (found == mCallbackRegistered.end()) {
1831 return false;
1832 }
1833 listener = found->second;
1834 mCallbackRegistered.erase(found);
1835 }
1836
1837 mAppOpsManager->stopWatchingMode(listener);
1838 return true;
1839}
1840
1841void IncrementalService::onAppOpChanged(const std::string& packageName) {
1842 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001843 return;
1844 }
1845
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001846 std::vector<IfsMountPtr> affected;
1847 {
1848 std::lock_guard l(mLock);
1849 affected.reserve(mMounts.size());
1850 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001851 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001852 affected.push_back(ifs);
1853 }
1854 }
1855 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001856 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001857 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001858 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001859}
1860
Songchun Fana7098592020-09-03 11:45:53 -07001861bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
1862 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001863 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07001864 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001865 }
Songchun Fana7098592020-09-03 11:45:53 -07001866 timedQueue.addJob(id, after, std::move(what));
1867 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001868}
1869
Songchun Fana7098592020-09-03 11:45:53 -07001870bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001871 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07001872 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001873 }
Songchun Fana7098592020-09-03 11:45:53 -07001874 timedQueue.removeJobs(id);
1875 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001876}
1877
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001878IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1879 DataLoaderParamsParcel&& params,
1880 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001881 const DataLoaderStatusListener* statusListener,
1882 StorageHealthCheckParams&& healthCheckParams,
1883 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001884 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001885 : mService(service),
1886 mId(id),
1887 mParams(std::move(params)),
1888 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001889 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
1890 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001891 mHealthPath(std::move(healthPath)),
1892 mHealthCheckParams(std::move(healthCheckParams)) {
1893 if (mHealthListener) {
1894 if (!isHealthParamsValid()) {
1895 mHealthListener = {};
1896 }
1897 } else {
1898 // Disable advanced health check statuses.
1899 mHealthCheckParams.blockedTimeoutMs = -1;
1900 }
1901 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001902}
1903
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001904IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001905 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001906 cleanupResources();
1907 }
1908}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001909
1910void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001911 auto now = Clock::now();
1912 {
1913 std::unique_lock lock(mMutex);
1914 mHealthPath.clear();
1915 unregisterFromPendingReads();
1916 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07001917 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001918 }
1919
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001920 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001921
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001922 {
1923 std::unique_lock lock(mMutex);
1924 mParams = {};
1925 mControl = {};
1926 mHealthControl = {};
1927 mHealthListener = {};
1928 mStatusCondition.wait_until(lock, now + 60s, [this] {
1929 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1930 });
1931 mStatusListener = {};
1932 mId = kInvalidStorageId;
1933 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001934}
1935
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001936sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1937 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001938 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001939 if (!status.isOk()) {
1940 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1941 return {};
1942 }
1943 if (!dataloader) {
1944 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1945 return {};
1946 }
1947 return dataloader;
1948}
1949
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001950bool IncrementalService::DataLoaderStub::requestCreate() {
1951 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1952}
1953
1954bool IncrementalService::DataLoaderStub::requestStart() {
1955 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1956}
1957
1958bool IncrementalService::DataLoaderStub::requestDestroy() {
1959 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1960}
1961
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001962bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001963 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001964 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001965 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001966 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001967 return fsmStep();
1968}
1969
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001970void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001971 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001972 mTargetStatus = status;
1973 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001974 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001975 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001976}
1977
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001978bool IncrementalService::DataLoaderStub::bind() {
1979 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001980 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001981 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001982 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001983 return false;
1984 }
1985 return true;
1986}
1987
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001988bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001989 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001990 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001991 return false;
1992 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001993 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001994 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001995 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001996 return false;
1997 }
1998 return true;
1999}
2000
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002001bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002002 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002003 if (!dataloader) {
2004 return false;
2005 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002006 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002007 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002008 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002009 return false;
2010 }
2011 return true;
2012}
2013
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002014bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002015 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002016}
2017
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002018bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002019 if (!isValid()) {
2020 return false;
2021 }
2022
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002023 int currentStatus;
2024 int targetStatus;
2025 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002026 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002027 currentStatus = mCurrentStatus;
2028 targetStatus = mTargetStatus;
2029 }
2030
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002031 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002032
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002033 if (currentStatus == targetStatus) {
2034 return true;
2035 }
2036
2037 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002038 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2039 // Do nothing, this is a reset state.
2040 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002041 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
2042 return destroy();
2043 }
2044 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2045 switch (currentStatus) {
2046 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2047 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2048 return start();
2049 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002050 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002051 }
2052 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2053 switch (currentStatus) {
2054 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002055 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002056 return bind();
2057 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002058 return create();
2059 }
2060 break;
2061 default:
2062 LOG(ERROR) << "Invalid target status: " << targetStatus
2063 << ", current status: " << currentStatus;
2064 break;
2065 }
2066 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002067}
2068
2069binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002070 if (!isValid()) {
2071 return binder::Status::
2072 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2073 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002074 if (id() != mountId) {
2075 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002076 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2077 }
2078
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002079 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002080 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002081 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002082 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002083 if (mCurrentStatus == newStatus) {
2084 return binder::Status::ok();
2085 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002086
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002087 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002088 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002089 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002090
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002091 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002092
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002093 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002094 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2095 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002096 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002097 }
2098
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002099 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002100 << newStatus << " (target " << targetStatus << ")";
2101
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002102 if (listener) {
2103 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002104 }
2105
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002106 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002107
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002108 mStatusCondition.notify_all();
2109
Songchun Fan3c82a302019-11-29 14:23:45 -08002110 return binder::Status::ok();
2111}
2112
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002113bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2114 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2115 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002116}
2117
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002118void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2119 int healthStatus) {
2120 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2121 if (healthListener) {
2122 healthListener->onHealthStatus(id(), healthStatus);
2123 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002124}
2125
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002126void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2127 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002128
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002129 int healthStatusToReport = -1;
2130 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002131
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002132 {
2133 std::unique_lock lock(mMutex);
2134 unregisterFromPendingReads();
2135
2136 healthListener = mHealthListener;
2137
2138 // Healthcheck depends on timestamp of the oldest pending read.
2139 // 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 -07002140 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2141 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002142 const auto now = Clock::now();
2143 const auto kernelTsUs = getOldestPendingReadTs();
2144 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002145 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2146 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002147 mHealthBase = {now, kernelTsUs};
2148 }
2149
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002150 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2151 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002152 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2153 registerForPendingReads();
2154 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2155 lock.unlock();
2156 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002157 return;
2158 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002159
2160 resetHealthControl();
2161
2162 // Always make sure the data loader is started.
2163 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2164
2165 // Skip any further processing if health check params are invalid.
2166 if (!isHealthParamsValid()) {
2167 LOG(DEBUG) << id()
2168 << ": Skip any further processing if health check params are invalid.";
2169 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2170 lock.unlock();
2171 onHealthStatus(healthListener, healthStatusToReport);
2172 // Triggering data loader start. This is a one-time action.
2173 fsmStep();
2174 return;
2175 }
2176
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002177 // Don't schedule timer job less than 500ms in advance.
2178 static constexpr auto kTolerance = 500ms;
2179
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002180 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2181 const auto unhealthyTimeout =
2182 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2183 const auto unhealthyMonitoring =
2184 std::max(1000ms,
2185 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2186
2187 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2188 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002189 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002190
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002191 Milliseconds checkBackAfter;
2192 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002193 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002194 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002195 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002196 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002197 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002198 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002199 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2200 } else {
2201 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002202 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002203 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2204 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002205 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002206 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002207 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2208 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002209 }
2210
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002211 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002212 if (healthStatusToReport != -1) {
2213 onHealthStatus(healthListener, healthStatusToReport);
2214 }
2215
2216 fsmStep();
2217}
2218
2219const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2220 if (mHealthPath.empty()) {
2221 resetHealthControl();
2222 return mHealthControl;
2223 }
2224 if (mHealthControl.pendingReads() < 0) {
2225 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2226 }
2227 if (mHealthControl.pendingReads() < 0) {
2228 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2229 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2230 << mHealthControl.logs() << ")";
2231 }
2232 return mHealthControl;
2233}
2234
2235void IncrementalService::DataLoaderStub::resetHealthControl() {
2236 mHealthControl = {};
2237}
2238
2239BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2240 auto result = kMaxBootClockTsUs;
2241
2242 const auto& control = initializeHealthControl();
2243 if (control.pendingReads() < 0) {
2244 return result;
2245 }
2246
2247 std::vector<incfs::ReadInfo> pendingReads;
2248 if (mService.mIncFs->waitForPendingReads(control, 0ms, &pendingReads) !=
2249 android::incfs::WaitResult::HaveData ||
2250 pendingReads.empty()) {
2251 return result;
2252 }
2253
2254 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
2255 << pendingReads.size() << ": " << pendingReads.front().bootClockTsUs;
2256
2257 for (auto&& pendingRead : pendingReads) {
2258 result = std::min(result, pendingRead.bootClockTsUs);
2259 }
2260 return result;
2261}
2262
2263void IncrementalService::DataLoaderStub::registerForPendingReads() {
2264 const auto pendingReadsFd = mHealthControl.pendingReads();
2265 if (pendingReadsFd < 0) {
2266 return;
2267 }
2268
2269 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2270
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002271 mService.mLooper->addFd(
2272 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2273 [](int, int, void* data) -> int {
2274 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002275 self->updateHealthStatus(/*baseline=*/true);
2276 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002277 },
2278 this);
2279 mService.mLooper->wake();
2280}
2281
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002282void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002283 const auto pendingReadsFd = mHealthControl.pendingReads();
2284 if (pendingReadsFd < 0) {
2285 return;
2286 }
2287
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002288 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2289
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002290 mService.mLooper->removeFd(pendingReadsFd);
2291 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002292}
2293
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002294void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002295 dprintf(fd, " dataLoader: {\n");
2296 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2297 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2298 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002299 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002300 dprintf(fd, " health: {\n");
2301 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2302 dprintf(fd, " base: %lldmcs (%lld)\n",
2303 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2304 (long long)mHealthBase.kernelTsUs);
2305 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2306 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2307 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2308 int(mHealthCheckParams.unhealthyMonitoringMs));
2309 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002310 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002311 dprintf(fd, " dataLoaderParams: {\n");
2312 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2313 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2314 dprintf(fd, " className: %s\n", params.className.c_str());
2315 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2316 dprintf(fd, " }\n");
2317 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002318}
2319
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002320void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2321 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002322}
2323
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002324binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2325 bool enableReadLogs, int32_t* _aidl_return) {
2326 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2327 return binder::Status::ok();
2328}
2329
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002330FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2331 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2332}
2333
Songchun Fan3c82a302019-11-29 14:23:45 -08002334} // namespace android::incremental