blob: bbcb3122c9bb0e420e2935c7ea188b4a666e07bf [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 Buynytskyyb65a77f2020-09-22 11:39:53 -0700311 mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700312 mCmdLooperThread.join();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700313 mTimedQueue->stop();
Songchun Fana7098592020-09-03 11:45:53 -0700314 mProgressUpdateJobQueue->stop();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700315 // Ensure that mounts are destroyed while the service is still valid.
316 mBindsByPath.clear();
317 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700318}
Songchun Fan3c82a302019-11-29 14:23:45 -0800319
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700320static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800321 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800322 case IncrementalService::BindKind::Temporary:
323 return "Temporary";
324 case IncrementalService::BindKind::Permanent:
325 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800326 }
327}
328
329void IncrementalService::onDump(int fd) {
330 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
331 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
332
333 std::unique_lock l(mLock);
334
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700335 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800336 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700337 const IncFsMount& mnt = *ifs;
338 dprintf(fd, " [%d]: {\n", id);
339 if (id != mnt.mountId) {
340 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
341 } else {
342 dprintf(fd, " mountId: %d\n", mnt.mountId);
343 dprintf(fd, " root: %s\n", mnt.root.c_str());
344 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
345 if (mnt.dataLoaderStub) {
346 mnt.dataLoaderStub->onDump(fd);
347 } else {
348 dprintf(fd, " dataLoader: null\n");
349 }
350 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
351 for (auto&& [storageId, storage] : mnt.storages) {
Songchun Fan374f7652020-08-20 08:40:29 -0700352 dprintf(fd, " [%d] -> [%s] (%d %% loaded) \n", storageId, storage.name.c_str(),
353 (int)(getLoadingProgressFromPath(mnt, storage.name.c_str()) * 100));
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700354 }
355 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800356
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700357 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
358 for (auto&& [target, bind] : mnt.bindPoints) {
359 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
360 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
361 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
362 dprintf(fd, " kind: %s\n", toString(bind.kind));
363 }
364 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800365 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700366 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800367 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700368 dprintf(fd, "}\n");
369 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800370 for (auto&& [target, mountPairIt] : mBindsByPath) {
371 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700372 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
373 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
374 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
375 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800376 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700377 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800378}
379
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700380void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800381 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700382 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800383 }
384
385 std::vector<IfsMountPtr> mounts;
386 {
387 std::lock_guard l(mLock);
388 mounts.reserve(mMounts.size());
389 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -0700390 if (ifs->mountId == id &&
391 ifs->dataLoaderStub->params().packageName == Constants::systemPackage) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800392 mounts.push_back(ifs);
393 }
394 }
395 }
396
Alex Buynytskyy69941662020-04-11 21:40:37 -0700397 if (mounts.empty()) {
398 return;
399 }
400
Songchun Fan3c82a302019-11-29 14:23:45 -0800401 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700402 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800403 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700404 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800405 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800406 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800407}
408
409auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
410 for (;;) {
411 if (mNextId == kMaxStorageId) {
412 mNextId = 0;
413 }
414 auto id = ++mNextId;
415 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
416 if (inserted) {
417 return it;
418 }
419 }
420}
421
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700422StorageId IncrementalService::createStorage(std::string_view mountPoint,
423 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
424 CreateOptions options,
425 const DataLoaderStatusListener& statusListener,
426 StorageHealthCheckParams&& healthCheckParams,
427 const StorageHealthListener& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800428 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
429 if (!path::isAbsolute(mountPoint)) {
430 LOG(ERROR) << "path is not absolute: " << mountPoint;
431 return kInvalidStorageId;
432 }
433
434 auto mountNorm = path::normalize(mountPoint);
435 {
436 const auto id = findStorageId(mountNorm);
437 if (id != kInvalidStorageId) {
438 if (options & CreateOptions::OpenExisting) {
439 LOG(INFO) << "Opened existing storage " << id;
440 return id;
441 }
442 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
443 return kInvalidStorageId;
444 }
445 }
446
447 if (!(options & CreateOptions::CreateNew)) {
448 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
449 return kInvalidStorageId;
450 }
451
452 if (!path::isEmptyDir(mountNorm)) {
453 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
454 return kInvalidStorageId;
455 }
456 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
457 if (mountRoot.empty()) {
458 LOG(ERROR) << "Bad mount point";
459 return kInvalidStorageId;
460 }
461 // Make sure the code removes all crap it may create while still failing.
462 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
463 auto firstCleanupOnFailure =
464 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
465
466 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800467 const auto backing = path::join(mountRoot, constants().backing);
468 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800469 return kInvalidStorageId;
470 }
471
Songchun Fan3c82a302019-11-29 14:23:45 -0800472 IncFsMount::Control control;
473 {
474 std::lock_guard l(mMountOperationLock);
475 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800476
477 if (auto err = rmDirContent(backing.c_str())) {
478 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
479 return kInvalidStorageId;
480 }
481 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
482 return kInvalidStorageId;
483 }
484 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800485 if (!status.isOk()) {
486 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
487 return kInvalidStorageId;
488 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800489 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
490 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800491 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
492 return kInvalidStorageId;
493 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800494 int cmd = controlParcel.cmd.release().release();
495 int pendingReads = controlParcel.pendingReads.release().release();
496 int logs = controlParcel.log.release().release();
497 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800498 }
499
500 std::unique_lock l(mLock);
501 const auto mountIt = getStorageSlotLocked();
502 const auto mountId = mountIt->first;
503 l.unlock();
504
505 auto ifs =
506 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
507 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
508 // is the removal of the |ifs|.
509 firstCleanupOnFailure.release();
510
511 auto secondCleanup = [this, &l](auto itPtr) {
512 if (!l.owns_lock()) {
513 l.lock();
514 }
515 mMounts.erase(*itPtr);
516 };
517 auto secondCleanupOnFailure =
518 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
519
520 const auto storageIt = ifs->makeStorage(ifs->mountId);
521 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800522 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800523 return kInvalidStorageId;
524 }
525
526 {
527 metadata::Mount m;
528 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700529 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700530 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
531 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
532 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800533 const auto metadata = m.SerializeAsString();
534 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800535 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800536 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800537 if (auto err =
538 mIncFs->makeFile(ifs->control,
539 path::join(ifs->root, constants().mount,
540 constants().infoMdName),
541 0777, idFromMetadata(metadata),
542 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800543 LOG(ERROR) << "Saving mount metadata failed: " << -err;
544 return kInvalidStorageId;
545 }
546 }
547
548 const auto bk =
549 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800550 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
551 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800552 err < 0) {
553 LOG(ERROR) << "adding bind mount failed: " << -err;
554 return kInvalidStorageId;
555 }
556
557 // Done here as well, all data structures are in good state.
558 secondCleanupOnFailure.release();
559
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700560 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
561 std::move(healthCheckParams), &healthListener);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700562 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800563
564 mountIt->second = std::move(ifs);
565 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700566
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700567 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700568 // failed to create data loader
569 LOG(ERROR) << "initializeDataLoader() failed";
570 deleteStorage(dataLoaderStub->id());
571 return kInvalidStorageId;
572 }
573
Songchun Fan3c82a302019-11-29 14:23:45 -0800574 LOG(INFO) << "created storage " << mountId;
575 return mountId;
576}
577
578StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
579 StorageId linkedStorage,
580 IncrementalService::CreateOptions options) {
581 if (!isValidMountTarget(mountPoint)) {
582 LOG(ERROR) << "Mount point is invalid or missing";
583 return kInvalidStorageId;
584 }
585
586 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700587 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800588 if (!ifs) {
589 LOG(ERROR) << "Ifs unavailable";
590 return kInvalidStorageId;
591 }
592
593 const auto mountIt = getStorageSlotLocked();
594 const auto storageId = mountIt->first;
595 const auto storageIt = ifs->makeStorage(storageId);
596 if (storageIt == ifs->storages.end()) {
597 LOG(ERROR) << "Can't create a new storage";
598 mMounts.erase(mountIt);
599 return kInvalidStorageId;
600 }
601
602 l.unlock();
603
604 const auto bk =
605 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800606 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
607 std::string(storageIt->second.name), path::normalize(mountPoint),
608 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800609 err < 0) {
610 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700611 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
612 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800613 return kInvalidStorageId;
614 }
615
616 mountIt->second = ifs;
617 return storageId;
618}
619
620IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
621 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700622 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800623}
624
625StorageId IncrementalService::findStorageId(std::string_view path) const {
626 std::lock_guard l(mLock);
627 auto it = findStorageLocked(path);
628 if (it == mBindsByPath.end()) {
629 return kInvalidStorageId;
630 }
631 return it->second->second.storage;
632}
633
Alex Buynytskyy04035452020-06-06 20:15:58 -0700634void IncrementalService::disableReadLogs(StorageId storageId) {
635 std::unique_lock l(mLock);
636 const auto ifs = getIfsLocked(storageId);
637 if (!ifs) {
638 LOG(ERROR) << "disableReadLogs failed, invalid storageId: " << storageId;
639 return;
640 }
641 if (!ifs->readLogsEnabled()) {
642 return;
643 }
644 ifs->disableReadLogs();
645 l.unlock();
646
647 const auto metadata = constants().readLogsDisabledMarkerName;
648 if (auto err = mIncFs->makeFile(ifs->control,
649 path::join(ifs->root, constants().mount,
650 constants().readLogsDisabledMarkerName),
651 0777, idFromMetadata(metadata), {})) {
652 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
653 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
654 return;
655 }
656
657 setStorageParams(storageId, /*enableReadLogs=*/false);
658}
659
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700660int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
661 const auto ifs = getIfs(storageId);
662 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700663 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700664 return -EINVAL;
665 }
666
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700667 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700668 if (enableReadLogs) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700669 if (!ifs->readLogsEnabled()) {
670 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
671 return -EPERM;
672 }
673
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700674 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
675 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700676 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700677 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700678 return fromBinderStatus(status);
679 }
680 }
681
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700682 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
683 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
684 return fromBinderStatus(status);
685 }
686
687 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700688 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700689 }
690
691 return 0;
692}
693
694binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700695 os::incremental::IncrementalFileSystemControlParcel control;
696 control.cmd.reset(dup(ifs.control.cmd()));
697 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700698 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700699 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700700 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700701 }
702
703 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700704 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700705}
706
Songchun Fan3c82a302019-11-29 14:23:45 -0800707void IncrementalService::deleteStorage(StorageId storageId) {
708 const auto ifs = getIfs(storageId);
709 if (!ifs) {
710 return;
711 }
712 deleteStorage(*ifs);
713}
714
715void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
716 std::unique_lock l(ifs.lock);
717 deleteStorageLocked(ifs, std::move(l));
718}
719
720void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
721 std::unique_lock<std::mutex>&& ifsLock) {
722 const auto storages = std::move(ifs.storages);
723 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
724 const auto bindPoints = ifs.bindPoints;
725 ifsLock.unlock();
726
727 std::lock_guard l(mLock);
728 for (auto&& [id, _] : storages) {
729 if (id != ifs.mountId) {
730 mMounts.erase(id);
731 }
732 }
733 for (auto&& [path, _] : bindPoints) {
734 mBindsByPath.erase(path);
735 }
736 mMounts.erase(ifs.mountId);
737}
738
739StorageId IncrementalService::openStorage(std::string_view pathInMount) {
740 if (!path::isAbsolute(pathInMount)) {
741 return kInvalidStorageId;
742 }
743
744 return findStorageId(path::normalize(pathInMount));
745}
746
Songchun Fan3c82a302019-11-29 14:23:45 -0800747IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
748 std::lock_guard l(mLock);
749 return getIfsLocked(storage);
750}
751
752const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
753 auto it = mMounts.find(storage);
754 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700755 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700756 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800757 }
758 return it->second;
759}
760
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800761int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
762 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800763 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700764 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800765 return -EINVAL;
766 }
767
768 const auto ifs = getIfs(storage);
769 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700770 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800771 return -EINVAL;
772 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800773
Songchun Fan3c82a302019-11-29 14:23:45 -0800774 std::unique_lock l(ifs->lock);
775 const auto storageInfo = ifs->storages.find(storage);
776 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700777 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800778 return -EINVAL;
779 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700780 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700781 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700782 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700783 return -EINVAL;
784 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800785 l.unlock();
786 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800787 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
788 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800789}
790
791int IncrementalService::unbind(StorageId storage, std::string_view target) {
792 if (!path::isAbsolute(target)) {
793 return -EINVAL;
794 }
795
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700796 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800797
798 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
799 // otherwise there's a chance to unmount something completely unrelated
800 const auto norm = path::normalize(target);
801 std::unique_lock l(mLock);
802 const auto storageIt = mBindsByPath.find(norm);
803 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
804 return -EINVAL;
805 }
806 const auto bindIt = storageIt->second;
807 const auto storageId = bindIt->second.storage;
808 const auto ifs = getIfsLocked(storageId);
809 if (!ifs) {
810 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
811 << " is missing";
812 return -EFAULT;
813 }
814 mBindsByPath.erase(storageIt);
815 l.unlock();
816
817 mVold->unmountIncFs(bindIt->first);
818 std::unique_lock l2(ifs->lock);
819 if (ifs->bindPoints.size() <= 1) {
820 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700821 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800822 } else {
823 const std::string savedFile = std::move(bindIt->second.savedFilename);
824 ifs->bindPoints.erase(bindIt);
825 l2.unlock();
826 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800827 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800828 }
829 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700830
Songchun Fan3c82a302019-11-29 14:23:45 -0800831 return 0;
832}
833
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700834std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700835 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700836 std::string_view path) const {
837 if (!path::isAbsolute(path)) {
838 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700839 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700840 auto normPath = path::normalize(path);
841 if (path::startsWith(normPath, storageIt->second.name)) {
842 return normPath;
843 }
844 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700845 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
846 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700847 return {};
848 }
849 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700850}
851
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700852std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700853 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700854 std::unique_lock l(ifs.lock);
855 const auto storageInfo = ifs.storages.find(storage);
856 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800857 return {};
858 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700859 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800860}
861
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800862int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700863 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800864 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700865 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800866 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700867 LOG(ERROR) << "Internal error: storageId " << storage
868 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800869 return -EINVAL;
870 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700871 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); 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 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700875 if (!data.empty()) {
876 if (auto err = setFileContent(ifs, id, path, data); err) {
877 return err;
878 }
879 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800880 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800881 }
882 return -EINVAL;
883}
884
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800885int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800886 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700887 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800888 if (normPath.empty()) {
889 return -EINVAL;
890 }
891 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800892 }
893 return -EINVAL;
894}
895
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800896int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800897 const auto ifs = getIfs(storageId);
898 if (!ifs) {
899 return -EINVAL;
900 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700901 return makeDirs(*ifs, storageId, path, mode);
902}
903
904int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
905 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800906 std::string normPath = normalizePathToStorage(ifs, storageId, path);
907 if (normPath.empty()) {
908 return -EINVAL;
909 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700910 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800911}
912
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800913int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
914 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700915 std::unique_lock l(mLock);
916 auto ifsSrc = getIfsLocked(sourceStorageId);
917 if (!ifsSrc) {
918 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800919 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700920 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
921 return -EINVAL;
922 }
923 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700924 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
925 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700926 if (normOldPath.empty() || normNewPath.empty()) {
927 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
928 return -EINVAL;
929 }
930 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800931}
932
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800933int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800934 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700935 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800936 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800937 }
938 return -EINVAL;
939}
940
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800941int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
942 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800943 std::string&& target, BindKind kind,
944 std::unique_lock<std::mutex>& mainLock) {
945 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700946 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800947 return -EINVAL;
948 }
949
950 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700951 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800952 if (kind != BindKind::Temporary) {
953 metadata::BindPoint bp;
954 bp.set_storage_id(storage);
955 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800956 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800957 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800958 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800959 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800960 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700961 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
962 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
963 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800964 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700965 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800966 return int(node);
967 }
968 }
969
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700970 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
971 std::move(target), kind, mainLock);
972 if (res) {
973 mIncFs->unlink(ifs.control, metadataFullPath);
974 }
975 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800976}
977
978int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800979 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800980 std::string&& target, BindKind kind,
981 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800982 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800983 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800984 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800985 if (!status.isOk()) {
986 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
987 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
988 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
989 : status.serviceSpecificErrorCode() == 0
990 ? -EFAULT
991 : status.serviceSpecificErrorCode()
992 : -EIO;
993 }
994 }
995
996 if (!mainLock.owns_lock()) {
997 mainLock.lock();
998 }
999 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001000 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1001 std::move(target), kind);
1002 return 0;
1003}
1004
1005void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1006 std::string&& metadataName, std::string&& source,
1007 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001008 const auto [it, _] =
1009 ifs.bindPoints.insert_or_assign(target,
1010 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001011 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001012 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001013}
1014
1015RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1016 const auto ifs = getIfs(storage);
1017 if (!ifs) {
1018 return {};
1019 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001020 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001021 if (normPath.empty()) {
1022 return {};
1023 }
1024 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001025}
1026
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001027RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001028 const auto ifs = getIfs(storage);
1029 if (!ifs) {
1030 return {};
1031 }
1032 return mIncFs->getMetadata(ifs->control, node);
1033}
1034
Songchun Fan3c82a302019-11-29 14:23:45 -08001035bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001036 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001037 {
1038 std::unique_lock l(mLock);
1039 const auto& ifs = getIfsLocked(storage);
1040 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001041 return false;
1042 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001043 dataLoaderStub = ifs->dataLoaderStub;
1044 if (!dataLoaderStub) {
1045 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001046 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001047 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001048 dataLoaderStub->requestStart();
1049 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001050}
1051
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001052std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1053 std::unordered_set<std::string_view> mountedRootNames;
1054 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1055 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1056 for (auto [source, target] : binds) {
1057 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1058 LOG(INFO) << " " << path::join(root, source);
1059 }
1060
1061 // Ensure it's a kind of a mount that's managed by IncrementalService
1062 if (path::basename(root) != constants().mount ||
1063 path::basename(backingDir) != constants().backing) {
1064 return;
1065 }
1066 const auto expectedRoot = path::dirname(root);
1067 if (path::dirname(backingDir) != expectedRoot) {
1068 return;
1069 }
1070 if (path::dirname(expectedRoot) != mIncrementalDir) {
1071 return;
1072 }
1073 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1074 return;
1075 }
1076
1077 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1078
1079 // make sure we clean up the mount if it happens to be a bad one.
1080 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1081 auto cleanupFiles = makeCleanup([&]() {
1082 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1083 IncFsMount::cleanupFilesystem(expectedRoot);
1084 });
1085 auto cleanupMounts = makeCleanup([&]() {
1086 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1087 for (auto&& [_, target] : binds) {
1088 mVold->unmountIncFs(std::string(target));
1089 }
1090 mVold->unmountIncFs(std::string(root));
1091 });
1092
1093 auto control = mIncFs->openMount(root);
1094 if (!control) {
1095 LOG(INFO) << "failed to open mount " << root;
1096 return;
1097 }
1098
1099 auto mountRecord =
1100 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1101 path::join(root, constants().infoMdName));
1102 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1103 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1104 return;
1105 }
1106
1107 auto mountId = mountRecord.storage().id();
1108 mNextId = std::max(mNextId, mountId + 1);
1109
1110 DataLoaderParamsParcel dataLoaderParams;
1111 {
1112 const auto& loader = mountRecord.loader();
1113 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1114 dataLoaderParams.packageName = loader.package_name();
1115 dataLoaderParams.className = loader.class_name();
1116 dataLoaderParams.arguments = loader.arguments();
1117 }
1118
1119 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1120 std::move(control), *this);
1121 cleanupFiles.release(); // ifs will take care of that now
1122
Alex Buynytskyy04035452020-06-06 20:15:58 -07001123 // Check if marker file present.
1124 if (checkReadLogsDisabledMarker(root)) {
1125 ifs->disableReadLogs();
1126 }
1127
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001128 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1129 auto d = openDir(root);
1130 while (auto e = ::readdir(d.get())) {
1131 if (e->d_type == DT_REG) {
1132 auto name = std::string_view(e->d_name);
1133 if (name.starts_with(constants().mountpointMdPrefix)) {
1134 permanentBindPoints
1135 .emplace_back(name,
1136 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1137 ifs->control,
1138 path::join(root,
1139 name)));
1140 if (permanentBindPoints.back().second.dest_path().empty() ||
1141 permanentBindPoints.back().second.source_subdir().empty()) {
1142 permanentBindPoints.pop_back();
1143 mIncFs->unlink(ifs->control, path::join(root, name));
1144 } else {
1145 LOG(INFO) << "Permanent bind record: '"
1146 << permanentBindPoints.back().second.source_subdir() << "'->'"
1147 << permanentBindPoints.back().second.dest_path() << "'";
1148 }
1149 }
1150 } else if (e->d_type == DT_DIR) {
1151 if (e->d_name == "."sv || e->d_name == ".."sv) {
1152 continue;
1153 }
1154 auto name = std::string_view(e->d_name);
1155 if (name.starts_with(constants().storagePrefix)) {
1156 int storageId;
1157 const auto res =
1158 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1159 name.data() + name.size(), storageId);
1160 if (res.ec != std::errc{} || *res.ptr != '_') {
1161 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1162 << "' for mount " << expectedRoot;
1163 continue;
1164 }
1165 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1166 if (!inserted) {
1167 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1168 << " for mount " << expectedRoot;
1169 continue;
1170 }
1171 ifs->storages.insert_or_assign(storageId,
1172 IncFsMount::Storage{path::join(root, name)});
1173 mNextId = std::max(mNextId, storageId + 1);
1174 }
1175 }
1176 }
1177
1178 if (ifs->storages.empty()) {
1179 LOG(WARNING) << "No valid storages in mount " << root;
1180 return;
1181 }
1182
1183 // now match the mounted directories with what we expect to have in the metadata
1184 {
1185 std::unique_lock l(mLock, std::defer_lock);
1186 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1187 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1188 [&, bindRecord = bindRecord](auto&& bind) {
1189 return bind.second == bindRecord.dest_path() &&
1190 path::join(root, bind.first) ==
1191 bindRecord.source_subdir();
1192 });
1193 if (mountedIt != binds.end()) {
1194 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1195 << " to mount " << mountedIt->first;
1196 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1197 std::move(*bindRecord.mutable_source_subdir()),
1198 std::move(*bindRecord.mutable_dest_path()),
1199 BindKind::Permanent);
1200 if (mountedIt != binds.end() - 1) {
1201 std::iter_swap(mountedIt, binds.end() - 1);
1202 }
1203 binds = binds.first(binds.size() - 1);
1204 } else {
1205 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1206 << ", mounting";
1207 // doesn't exist - try mounting back
1208 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1209 std::move(*bindRecord.mutable_source_subdir()),
1210 std::move(*bindRecord.mutable_dest_path()),
1211 BindKind::Permanent, l)) {
1212 mIncFs->unlink(ifs->control, metadataFile);
1213 }
1214 }
1215 }
1216 }
1217
1218 // if anything stays in |binds| those are probably temporary binds; system restarted since
1219 // they were mounted - so let's unmount them all.
1220 for (auto&& [source, target] : binds) {
1221 if (source.empty()) {
1222 continue;
1223 }
1224 mVold->unmountIncFs(std::string(target));
1225 }
1226 cleanupMounts.release(); // ifs now manages everything
1227
1228 if (ifs->bindPoints.empty()) {
1229 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1230 deleteStorage(*ifs);
1231 return;
1232 }
1233
1234 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1235 CHECK(ifs->dataLoaderStub);
1236
1237 mountedRootNames.insert(path::basename(ifs->root));
1238
1239 // not locking here at all: we're still in the constructor, no other calls can happen
1240 mMounts[ifs->mountId] = std::move(ifs);
1241 });
1242
1243 return mountedRootNames;
1244}
1245
1246void IncrementalService::mountExistingImages(
1247 const std::unordered_set<std::string_view>& mountedRootNames) {
1248 auto dir = openDir(mIncrementalDir);
1249 if (!dir) {
1250 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1251 return;
1252 }
1253 while (auto entry = ::readdir(dir.get())) {
1254 if (entry->d_type != DT_DIR) {
1255 continue;
1256 }
1257 std::string_view name = entry->d_name;
1258 if (!name.starts_with(constants().mountKeyPrefix)) {
1259 continue;
1260 }
1261 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001262 continue;
1263 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001264 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001265 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001266 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001267 }
1268 }
1269}
1270
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001271bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001272 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001273 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001274
Songchun Fan3c82a302019-11-29 14:23:45 -08001275 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001276 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001277 if (!status.isOk()) {
1278 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1279 return false;
1280 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001281
1282 int cmd = controlParcel.cmd.release().release();
1283 int pendingReads = controlParcel.pendingReads.release().release();
1284 int logs = controlParcel.log.release().release();
1285 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001286
1287 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1288
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001289 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1290 path::join(mountTarget, constants().infoMdName));
1291 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001292 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1293 return false;
1294 }
1295
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001296 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001297 mNextId = std::max(mNextId, ifs->mountId + 1);
1298
Alex Buynytskyy04035452020-06-06 20:15:58 -07001299 // Check if marker file present.
1300 if (checkReadLogsDisabledMarker(mountTarget)) {
1301 ifs->disableReadLogs();
1302 }
1303
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001304 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001305 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001306 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001307 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001308 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001309 dataLoaderParams.packageName = loader.package_name();
1310 dataLoaderParams.className = loader.class_name();
1311 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001312 }
1313
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001314 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001315 CHECK(ifs->dataLoaderStub);
1316
Songchun Fan3c82a302019-11-29 14:23:45 -08001317 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001318 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001319 while (auto e = ::readdir(d.get())) {
1320 if (e->d_type == DT_REG) {
1321 auto name = std::string_view(e->d_name);
1322 if (name.starts_with(constants().mountpointMdPrefix)) {
1323 bindPoints.emplace_back(name,
1324 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1325 ifs->control,
1326 path::join(mountTarget,
1327 name)));
1328 if (bindPoints.back().second.dest_path().empty() ||
1329 bindPoints.back().second.source_subdir().empty()) {
1330 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001331 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001332 }
1333 }
1334 } else if (e->d_type == DT_DIR) {
1335 if (e->d_name == "."sv || e->d_name == ".."sv) {
1336 continue;
1337 }
1338 auto name = std::string_view(e->d_name);
1339 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001340 int storageId;
1341 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1342 name.data() + name.size(), storageId);
1343 if (res.ec != std::errc{} || *res.ptr != '_') {
1344 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1345 << root;
1346 continue;
1347 }
1348 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001349 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001350 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001351 << " for mount " << root;
1352 continue;
1353 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001354 ifs->storages.insert_or_assign(storageId,
1355 IncFsMount::Storage{
1356 path::join(root, constants().mount, name)});
1357 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001358 }
1359 }
1360 }
1361
1362 if (ifs->storages.empty()) {
1363 LOG(WARNING) << "No valid storages in mount " << root;
1364 return false;
1365 }
1366
1367 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001368 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001369 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001370 for (auto&& bp : bindPoints) {
1371 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1372 std::move(*bp.second.mutable_source_subdir()),
1373 std::move(*bp.second.mutable_dest_path()),
1374 BindKind::Permanent, l);
1375 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001376 }
1377
1378 if (bindCount == 0) {
1379 LOG(WARNING) << "No valid bind points for mount " << root;
1380 deleteStorage(*ifs);
1381 return false;
1382 }
1383
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001384 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001385 mMounts[ifs->mountId] = std::move(ifs);
1386 return true;
1387}
1388
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001389void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001390 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001391 while (mRunning.load(std::memory_order_relaxed)) {
1392 mLooper->pollAll(kTimeoutMsecs);
1393 }
1394}
1395
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001396IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001397 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001398 const DataLoaderStatusListener* statusListener,
1399 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001400 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001401 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1402 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001403 return ifs.dataLoaderStub;
1404}
1405
1406void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001407 const DataLoaderStatusListener* statusListener,
1408 StorageHealthCheckParams&& healthCheckParams,
1409 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001410 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001411 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001412 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001413 }
1414
Songchun Fan3c82a302019-11-29 14:23:45 -08001415 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001416 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001417 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1418 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1419 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001420 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001421
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001422 ifs.dataLoaderStub =
1423 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001424 statusListener, std::move(healthCheckParams), healthListener,
1425 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001426}
1427
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001428template <class Duration>
1429static long elapsedMcs(Duration start, Duration end) {
1430 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1431}
1432
1433// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001434// Lib files should be placed next to the APK file in the following matter:
1435// Example:
1436// /path/to/base.apk
1437// /path/to/lib/arm/first.so
1438// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001439bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1440 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001441 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001442 auto start = Clock::now();
1443
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001444 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001445 if (!ifs) {
1446 LOG(ERROR) << "Invalid storage " << storage;
1447 return false;
1448 }
1449
Songchun Fanc8975312020-07-13 12:14:37 -07001450 const auto targetLibPathRelativeToStorage =
1451 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1452 libDirRelativePath);
1453
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001454 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001455 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1456 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001457 << " errno: " << res;
1458 return false;
1459 }
1460
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001461 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001462 ZipArchiveHandle zipFileHandle;
1463 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001464 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1465 return false;
1466 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001467
1468 // Need a shared pointer: will be passing it into all unpacking jobs.
1469 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001470 void* cookie = nullptr;
Songchun Fan2ff2a482020-09-29 11:45:18 -07001471 const auto libFilePrefix = path::join(constants().libDir, abi) + "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001472 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001473 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1474 return false;
1475 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001476 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001477 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1478
1479 auto openZipTs = Clock::now();
1480
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001481 std::vector<Job> jobQueue;
1482 ZipEntry entry;
1483 std::string_view fileName;
1484 while (!Next(cookie, &entry, &fileName)) {
1485 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001486 continue;
1487 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001488
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001489 if (!extractNativeLibs) {
1490 // ensure the file is properly aligned and unpacked
1491 if (entry.method != kCompressStored) {
1492 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1493 return false;
1494 }
1495 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1496 LOG(WARNING) << "Library " << fileName
1497 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1498 << entry.offset;
1499 return false;
1500 }
1501 continue;
1502 }
1503
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001504 auto startFileTs = Clock::now();
1505
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001506 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001507 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001508 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001509 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001510 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001511 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001512 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1513 << "; skipping extraction, spent "
1514 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1515 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001516 continue;
1517 }
1518
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001519 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001520 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001521 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001522 .signature = {},
1523 // Metadata of the new lib file is its relative path
1524 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1525 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001526 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001527 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1528 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001529 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001530 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001531 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001532 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001533
1534 auto makeFileTs = Clock::now();
1535
Songchun Fanafaf6e92020-03-18 14:12:20 -07001536 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001537 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001538 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001539 LOG(INFO) << "incfs: Extracted " << libName
1540 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001541 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001542 continue;
1543 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001544
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001545 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1546 libFileId, libPath = std::move(targetLibPath),
1547 makeFileTs]() mutable {
1548 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001549 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001550
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001551 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001552 auto prepareJobTs = Clock::now();
1553 LOG(INFO) << "incfs: Processed " << libName << ": "
1554 << elapsedMcs(startFileTs, prepareJobTs)
1555 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1556 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001557 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001558 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001559
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001560 auto processedTs = Clock::now();
1561
1562 if (!jobQueue.empty()) {
1563 {
1564 std::lock_guard lock(mJobMutex);
1565 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001566 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001567 if (existingJobs.empty()) {
1568 existingJobs = std::move(jobQueue);
1569 } else {
1570 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1571 std::move_iterator(jobQueue.end()));
1572 }
1573 }
1574 }
1575 mJobCondition.notify_all();
1576 }
1577
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001578 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001579 auto end = Clock::now();
1580 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1581 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1582 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001583 << " make files: " << elapsedMcs(openZipTs, processedTs)
1584 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001585 }
1586
1587 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001588}
1589
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001590void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1591 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001592 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001593 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001594 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001595 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001596 return;
1597 }
1598
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001599 auto startedTs = Clock::now();
1600
1601 // Write extracted data to new file
1602 // NOTE: don't zero-initialize memory, it may take a while for nothing
1603 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1604 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001605 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001606 return;
1607 }
1608
1609 auto extractFileTs = Clock::now();
1610
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001611 if (setFileContent(ifs, libFileId, debugLibPath,
1612 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001613 return;
1614 }
1615
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001616 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001617 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001618 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1619 << entry.compressed_length << " -> " << entry.uncompressed_length
1620 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001621 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1622 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001623 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001624 }
1625}
1626
1627bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001628 struct WaitPrinter {
1629 const Clock::time_point startTs = Clock::now();
1630 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001631 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001632 const auto endTs = Clock::now();
1633 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1634 << elapsedMcs(startTs, endTs) << "mcs";
1635 }
1636 }
1637 } waitPrinter;
1638
1639 MountId mount;
1640 {
1641 auto ifs = getIfs(storage);
1642 if (!ifs) {
1643 return true;
1644 }
1645 mount = ifs->mountId;
1646 }
1647
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001648 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001649 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001650 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001651 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001652 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001653 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001654}
1655
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001656int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1657 std::string_view debugFilePath,
1658 std::span<const uint8_t> data) const {
1659 auto startTs = Clock::now();
1660
1661 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1662 if (!writeFd.ok()) {
1663 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1664 << " errno: " << writeFd.get();
1665 return writeFd.get();
1666 }
1667
1668 const auto dataLength = data.size();
1669
1670 auto openFileTs = Clock::now();
1671 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1672 std::vector<IncFsDataBlock> instructions(numBlocks);
1673 for (int i = 0; i < numBlocks; i++) {
1674 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1675 instructions[i] = IncFsDataBlock{
1676 .fileFd = writeFd.get(),
1677 .pageIndex = static_cast<IncFsBlockIndex>(i),
1678 .compression = INCFS_COMPRESSION_KIND_NONE,
1679 .kind = INCFS_BLOCK_KIND_DATA,
1680 .dataSize = static_cast<uint32_t>(blockSize),
1681 .data = reinterpret_cast<const char*>(data.data()),
1682 };
1683 data = data.subspan(blockSize);
1684 }
1685 auto prepareInstsTs = Clock::now();
1686
1687 size_t res = mIncFs->writeBlocks(instructions);
1688 if (res != instructions.size()) {
1689 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1690 return res;
1691 }
1692
1693 if (perfLoggingEnabled()) {
1694 auto endTs = Clock::now();
1695 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1696 << " bytes): " << elapsedMcs(startTs, endTs)
1697 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1698 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1699 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1700 }
1701
1702 return 0;
1703}
1704
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001705int IncrementalService::isFileFullyLoaded(StorageId storage, const std::string& path) const {
1706 std::unique_lock l(mLock);
1707 const auto ifs = getIfsLocked(storage);
1708 if (!ifs) {
1709 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1710 return -EINVAL;
1711 }
1712 const auto storageInfo = ifs->storages.find(storage);
1713 if (storageInfo == ifs->storages.end()) {
1714 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1715 return -EINVAL;
1716 }
1717 l.unlock();
1718 return isFileFullyLoadedFromPath(*ifs, path);
1719}
1720
1721int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1722 std::string_view filePath) const {
1723 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1724 if (filledBlocks < 0) {
1725 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1726 << filePath << " errno: " << filledBlocks;
1727 return filledBlocks;
1728 }
1729 if (totalBlocks < filledBlocks) {
1730 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1731 return -EINVAL;
1732 }
1733 return totalBlocks - filledBlocks;
1734}
1735
Songchun Fan374f7652020-08-20 08:40:29 -07001736float IncrementalService::getLoadingProgress(StorageId storage) const {
1737 std::unique_lock l(mLock);
1738 const auto ifs = getIfsLocked(storage);
1739 if (!ifs) {
1740 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
1741 return -EINVAL;
1742 }
1743 const auto storageInfo = ifs->storages.find(storage);
1744 if (storageInfo == ifs->storages.end()) {
1745 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
1746 return -EINVAL;
1747 }
1748 l.unlock();
1749 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
1750}
1751
1752float IncrementalService::getLoadingProgressFromPath(const IncFsMount& ifs,
1753 std::string_view storagePath) const {
1754 size_t totalBlocks = 0, filledBlocks = 0;
1755 const auto filePaths = mFs->listFilesRecursive(storagePath);
1756 for (const auto& filePath : filePaths) {
1757 const auto [filledBlocksCount, totalBlocksCount] =
1758 mIncFs->countFilledBlocks(ifs.control, filePath);
1759 if (filledBlocksCount < 0) {
1760 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1761 << " errno: " << filledBlocksCount;
1762 return filledBlocksCount;
1763 }
1764 totalBlocks += totalBlocksCount;
1765 filledBlocks += filledBlocksCount;
1766 }
1767
1768 if (totalBlocks == 0) {
Songchun Fan425862f2020-08-25 13:12:16 -07001769 // No file in the storage or files are empty; regarded as fully loaded
1770 return 1;
Songchun Fan374f7652020-08-20 08:40:29 -07001771 }
1772 return (float)filledBlocks / (float)totalBlocks;
1773}
1774
Songchun Fana7098592020-09-03 11:45:53 -07001775bool IncrementalService::updateLoadingProgress(
1776 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1777 const auto progress = getLoadingProgress(storage);
1778 if (progress < 0) {
1779 // Failed to get progress from incfs, abort.
1780 return false;
1781 }
1782 progressListener->onStorageLoadingProgressChanged(storage, progress);
1783 if (progress > 1 - 0.001f) {
1784 // Stop updating progress once it is fully loaded
1785 return true;
1786 }
1787 static constexpr auto kProgressUpdateInterval = 1000ms;
1788 addTimedJob(*mProgressUpdateJobQueue, storage, kProgressUpdateInterval /* repeat after 1s */,
1789 [storage, progressListener, this]() {
1790 updateLoadingProgress(storage, progressListener);
1791 });
1792 return true;
1793}
1794
1795bool IncrementalService::registerLoadingProgressListener(
1796 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1797 return updateLoadingProgress(storage, progressListener);
1798}
1799
1800bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
1801 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
1802}
1803
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001804bool IncrementalService::perfLoggingEnabled() {
1805 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1806 return enabled;
1807}
1808
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001809void IncrementalService::runJobProcessing() {
1810 for (;;) {
1811 std::unique_lock lock(mJobMutex);
1812 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1813 if (!mRunning) {
1814 return;
1815 }
1816
1817 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001818 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001819 auto queue = std::move(it->second);
1820 mJobQueue.erase(it);
1821 lock.unlock();
1822
1823 for (auto&& job : queue) {
1824 job();
1825 }
1826
1827 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001828 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001829 lock.unlock();
1830 mJobCondition.notify_all();
1831 }
1832}
1833
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001834void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001835 sp<IAppOpsCallback> listener;
1836 {
1837 std::unique_lock lock{mCallbacksLock};
1838 auto& cb = mCallbackRegistered[packageName];
1839 if (cb) {
1840 return;
1841 }
1842 cb = new AppOpsListener(*this, packageName);
1843 listener = cb;
1844 }
1845
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001846 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1847 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001848}
1849
1850bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1851 sp<IAppOpsCallback> listener;
1852 {
1853 std::unique_lock lock{mCallbacksLock};
1854 auto found = mCallbackRegistered.find(packageName);
1855 if (found == mCallbackRegistered.end()) {
1856 return false;
1857 }
1858 listener = found->second;
1859 mCallbackRegistered.erase(found);
1860 }
1861
1862 mAppOpsManager->stopWatchingMode(listener);
1863 return true;
1864}
1865
1866void IncrementalService::onAppOpChanged(const std::string& packageName) {
1867 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001868 return;
1869 }
1870
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001871 std::vector<IfsMountPtr> affected;
1872 {
1873 std::lock_guard l(mLock);
1874 affected.reserve(mMounts.size());
1875 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001876 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001877 affected.push_back(ifs);
1878 }
1879 }
1880 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001881 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001882 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001883 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001884}
1885
Songchun Fana7098592020-09-03 11:45:53 -07001886bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
1887 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001888 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07001889 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001890 }
Songchun Fana7098592020-09-03 11:45:53 -07001891 timedQueue.addJob(id, after, std::move(what));
1892 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001893}
1894
Songchun Fana7098592020-09-03 11:45:53 -07001895bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001896 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07001897 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001898 }
Songchun Fana7098592020-09-03 11:45:53 -07001899 timedQueue.removeJobs(id);
1900 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001901}
1902
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001903IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1904 DataLoaderParamsParcel&& params,
1905 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001906 const DataLoaderStatusListener* statusListener,
1907 StorageHealthCheckParams&& healthCheckParams,
1908 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001909 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001910 : mService(service),
1911 mId(id),
1912 mParams(std::move(params)),
1913 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001914 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
1915 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001916 mHealthPath(std::move(healthPath)),
1917 mHealthCheckParams(std::move(healthCheckParams)) {
1918 if (mHealthListener) {
1919 if (!isHealthParamsValid()) {
1920 mHealthListener = {};
1921 }
1922 } else {
1923 // Disable advanced health check statuses.
1924 mHealthCheckParams.blockedTimeoutMs = -1;
1925 }
1926 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001927}
1928
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001929IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001930 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001931 cleanupResources();
1932 }
1933}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001934
1935void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001936 auto now = Clock::now();
1937 {
1938 std::unique_lock lock(mMutex);
1939 mHealthPath.clear();
1940 unregisterFromPendingReads();
1941 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07001942 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001943 }
1944
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001945 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001946
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001947 {
1948 std::unique_lock lock(mMutex);
1949 mParams = {};
1950 mControl = {};
1951 mHealthControl = {};
1952 mHealthListener = {};
1953 mStatusCondition.wait_until(lock, now + 60s, [this] {
1954 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1955 });
1956 mStatusListener = {};
1957 mId = kInvalidStorageId;
1958 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001959}
1960
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001961sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1962 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001963 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001964 if (!status.isOk()) {
1965 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1966 return {};
1967 }
1968 if (!dataloader) {
1969 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1970 return {};
1971 }
1972 return dataloader;
1973}
1974
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001975bool IncrementalService::DataLoaderStub::requestCreate() {
1976 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1977}
1978
1979bool IncrementalService::DataLoaderStub::requestStart() {
1980 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1981}
1982
1983bool IncrementalService::DataLoaderStub::requestDestroy() {
1984 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1985}
1986
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001987bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001988 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001989 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001990 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001991 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001992 return fsmStep();
1993}
1994
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001995void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001996 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001997 mTargetStatus = status;
1998 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001999 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002000 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002001}
2002
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002003bool IncrementalService::DataLoaderStub::bind() {
2004 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002005 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002006 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002007 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002008 return false;
2009 }
2010 return true;
2011}
2012
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002013bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002014 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002015 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002016 return false;
2017 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002018 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002019 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002020 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002021 return false;
2022 }
2023 return true;
2024}
2025
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002026bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002027 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002028 if (!dataloader) {
2029 return false;
2030 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002031 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002032 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002033 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002034 return false;
2035 }
2036 return true;
2037}
2038
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002039bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002040 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002041}
2042
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002043bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002044 if (!isValid()) {
2045 return false;
2046 }
2047
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002048 int currentStatus;
2049 int targetStatus;
2050 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002051 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002052 currentStatus = mCurrentStatus;
2053 targetStatus = mTargetStatus;
2054 }
2055
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002056 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002057
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002058 if (currentStatus == targetStatus) {
2059 return true;
2060 }
2061
2062 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002063 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2064 // Do nothing, this is a reset state.
2065 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002066 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
2067 return destroy();
2068 }
2069 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2070 switch (currentStatus) {
2071 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2072 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2073 return start();
2074 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002075 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002076 }
2077 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2078 switch (currentStatus) {
2079 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002080 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002081 return bind();
2082 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002083 return create();
2084 }
2085 break;
2086 default:
2087 LOG(ERROR) << "Invalid target status: " << targetStatus
2088 << ", current status: " << currentStatus;
2089 break;
2090 }
2091 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002092}
2093
2094binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002095 if (!isValid()) {
2096 return binder::Status::
2097 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2098 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002099 if (id() != mountId) {
2100 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002101 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2102 }
2103
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002104 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002105 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002106 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002107 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002108 if (mCurrentStatus == newStatus) {
2109 return binder::Status::ok();
2110 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002111
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002112 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002113 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002114 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002115
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002116 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002117
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002118 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002119 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2120 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002121 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002122 }
2123
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002124 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002125 << newStatus << " (target " << targetStatus << ")";
2126
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002127 if (listener) {
2128 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002129 }
2130
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002131 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002132
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002133 mStatusCondition.notify_all();
2134
Songchun Fan3c82a302019-11-29 14:23:45 -08002135 return binder::Status::ok();
2136}
2137
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002138bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2139 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2140 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002141}
2142
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002143void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2144 int healthStatus) {
2145 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2146 if (healthListener) {
2147 healthListener->onHealthStatus(id(), healthStatus);
2148 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002149}
2150
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002151void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2152 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002153
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002154 int healthStatusToReport = -1;
2155 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002156
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002157 {
2158 std::unique_lock lock(mMutex);
2159 unregisterFromPendingReads();
2160
2161 healthListener = mHealthListener;
2162
2163 // Healthcheck depends on timestamp of the oldest pending read.
2164 // 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 -07002165 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2166 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002167 const auto now = Clock::now();
2168 const auto kernelTsUs = getOldestPendingReadTs();
2169 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002170 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2171 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002172 mHealthBase = {now, kernelTsUs};
2173 }
2174
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002175 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2176 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002177 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2178 registerForPendingReads();
2179 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2180 lock.unlock();
2181 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002182 return;
2183 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002184
2185 resetHealthControl();
2186
2187 // Always make sure the data loader is started.
2188 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2189
2190 // Skip any further processing if health check params are invalid.
2191 if (!isHealthParamsValid()) {
2192 LOG(DEBUG) << id()
2193 << ": Skip any further processing if health check params are invalid.";
2194 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2195 lock.unlock();
2196 onHealthStatus(healthListener, healthStatusToReport);
2197 // Triggering data loader start. This is a one-time action.
2198 fsmStep();
2199 return;
2200 }
2201
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002202 // Don't schedule timer job less than 500ms in advance.
2203 static constexpr auto kTolerance = 500ms;
2204
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002205 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2206 const auto unhealthyTimeout =
2207 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2208 const auto unhealthyMonitoring =
2209 std::max(1000ms,
2210 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2211
2212 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2213 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002214 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002215
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002216 Milliseconds checkBackAfter;
2217 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002218 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002219 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002220 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002221 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002222 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002223 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002224 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2225 } else {
2226 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002227 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002228 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2229 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002230 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002231 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002232 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2233 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002234 }
2235
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002236 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002237 if (healthStatusToReport != -1) {
2238 onHealthStatus(healthListener, healthStatusToReport);
2239 }
2240
2241 fsmStep();
2242}
2243
2244const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2245 if (mHealthPath.empty()) {
2246 resetHealthControl();
2247 return mHealthControl;
2248 }
2249 if (mHealthControl.pendingReads() < 0) {
2250 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2251 }
2252 if (mHealthControl.pendingReads() < 0) {
2253 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2254 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2255 << mHealthControl.logs() << ")";
2256 }
2257 return mHealthControl;
2258}
2259
2260void IncrementalService::DataLoaderStub::resetHealthControl() {
2261 mHealthControl = {};
2262}
2263
2264BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2265 auto result = kMaxBootClockTsUs;
2266
2267 const auto& control = initializeHealthControl();
2268 if (control.pendingReads() < 0) {
2269 return result;
2270 }
2271
2272 std::vector<incfs::ReadInfo> pendingReads;
2273 if (mService.mIncFs->waitForPendingReads(control, 0ms, &pendingReads) !=
2274 android::incfs::WaitResult::HaveData ||
2275 pendingReads.empty()) {
2276 return result;
2277 }
2278
2279 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
2280 << pendingReads.size() << ": " << pendingReads.front().bootClockTsUs;
2281
2282 for (auto&& pendingRead : pendingReads) {
2283 result = std::min(result, pendingRead.bootClockTsUs);
2284 }
2285 return result;
2286}
2287
2288void IncrementalService::DataLoaderStub::registerForPendingReads() {
2289 const auto pendingReadsFd = mHealthControl.pendingReads();
2290 if (pendingReadsFd < 0) {
2291 return;
2292 }
2293
2294 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2295
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002296 mService.mLooper->addFd(
2297 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2298 [](int, int, void* data) -> int {
2299 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002300 self->updateHealthStatus(/*baseline=*/true);
2301 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002302 },
2303 this);
2304 mService.mLooper->wake();
2305}
2306
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002307void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002308 const auto pendingReadsFd = mHealthControl.pendingReads();
2309 if (pendingReadsFd < 0) {
2310 return;
2311 }
2312
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002313 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2314
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002315 mService.mLooper->removeFd(pendingReadsFd);
2316 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002317}
2318
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002319void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002320 dprintf(fd, " dataLoader: {\n");
2321 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2322 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2323 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002324 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002325 dprintf(fd, " health: {\n");
2326 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2327 dprintf(fd, " base: %lldmcs (%lld)\n",
2328 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2329 (long long)mHealthBase.kernelTsUs);
2330 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2331 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2332 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2333 int(mHealthCheckParams.unhealthyMonitoringMs));
2334 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002335 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002336 dprintf(fd, " dataLoaderParams: {\n");
2337 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2338 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2339 dprintf(fd, " className: %s\n", params.className.c_str());
2340 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2341 dprintf(fd, " }\n");
2342 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002343}
2344
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002345void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2346 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002347}
2348
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002349binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2350 bool enableReadLogs, int32_t* _aidl_return) {
2351 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2352 return binder::Status::ok();
2353}
2354
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002355FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2356 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2357}
2358
Songchun Fan3c82a302019-11-29 14:23:45 -08002359} // namespace android::incremental