blob: 99795576696d6f35186841ed22bb2eb9e0e0edfa [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 }
Paul Lawrence87a92e12020-11-20 13:15:56 -0800484 if (!mkdirOrLog(path::join(backing, ".incomplete"), 0777)) {
485 return kInvalidStorageId;
486 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800487 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800488 if (!status.isOk()) {
489 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
490 return kInvalidStorageId;
491 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800492 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
493 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800494 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
495 return kInvalidStorageId;
496 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800497 int cmd = controlParcel.cmd.release().release();
498 int pendingReads = controlParcel.pendingReads.release().release();
499 int logs = controlParcel.log.release().release();
500 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800501 }
502
503 std::unique_lock l(mLock);
504 const auto mountIt = getStorageSlotLocked();
505 const auto mountId = mountIt->first;
506 l.unlock();
507
508 auto ifs =
509 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
510 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
511 // is the removal of the |ifs|.
512 firstCleanupOnFailure.release();
513
514 auto secondCleanup = [this, &l](auto itPtr) {
515 if (!l.owns_lock()) {
516 l.lock();
517 }
518 mMounts.erase(*itPtr);
519 };
520 auto secondCleanupOnFailure =
521 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
522
523 const auto storageIt = ifs->makeStorage(ifs->mountId);
524 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800525 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800526 return kInvalidStorageId;
527 }
528
529 {
530 metadata::Mount m;
531 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700532 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700533 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
534 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
535 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800536 const auto metadata = m.SerializeAsString();
537 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800538 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800539 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800540 if (auto err =
541 mIncFs->makeFile(ifs->control,
542 path::join(ifs->root, constants().mount,
543 constants().infoMdName),
544 0777, idFromMetadata(metadata),
545 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800546 LOG(ERROR) << "Saving mount metadata failed: " << -err;
547 return kInvalidStorageId;
548 }
549 }
550
551 const auto bk =
552 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800553 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
554 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800555 err < 0) {
556 LOG(ERROR) << "adding bind mount failed: " << -err;
557 return kInvalidStorageId;
558 }
559
560 // Done here as well, all data structures are in good state.
561 secondCleanupOnFailure.release();
562
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700563 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
564 std::move(healthCheckParams), &healthListener);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700565 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800566
567 mountIt->second = std::move(ifs);
568 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700569
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700570 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700571 // failed to create data loader
572 LOG(ERROR) << "initializeDataLoader() failed";
573 deleteStorage(dataLoaderStub->id());
574 return kInvalidStorageId;
575 }
576
Songchun Fan3c82a302019-11-29 14:23:45 -0800577 LOG(INFO) << "created storage " << mountId;
578 return mountId;
579}
580
581StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
582 StorageId linkedStorage,
583 IncrementalService::CreateOptions options) {
584 if (!isValidMountTarget(mountPoint)) {
585 LOG(ERROR) << "Mount point is invalid or missing";
586 return kInvalidStorageId;
587 }
588
589 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700590 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800591 if (!ifs) {
592 LOG(ERROR) << "Ifs unavailable";
593 return kInvalidStorageId;
594 }
595
596 const auto mountIt = getStorageSlotLocked();
597 const auto storageId = mountIt->first;
598 const auto storageIt = ifs->makeStorage(storageId);
599 if (storageIt == ifs->storages.end()) {
600 LOG(ERROR) << "Can't create a new storage";
601 mMounts.erase(mountIt);
602 return kInvalidStorageId;
603 }
604
605 l.unlock();
606
607 const auto bk =
608 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800609 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
610 std::string(storageIt->second.name), path::normalize(mountPoint),
611 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800612 err < 0) {
613 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700614 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
615 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800616 return kInvalidStorageId;
617 }
618
619 mountIt->second = ifs;
620 return storageId;
621}
622
623IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
624 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700625 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800626}
627
628StorageId IncrementalService::findStorageId(std::string_view path) const {
629 std::lock_guard l(mLock);
630 auto it = findStorageLocked(path);
631 if (it == mBindsByPath.end()) {
632 return kInvalidStorageId;
633 }
634 return it->second->second.storage;
635}
636
Alex Buynytskyy04035452020-06-06 20:15:58 -0700637void IncrementalService::disableReadLogs(StorageId storageId) {
638 std::unique_lock l(mLock);
639 const auto ifs = getIfsLocked(storageId);
640 if (!ifs) {
641 LOG(ERROR) << "disableReadLogs failed, invalid storageId: " << storageId;
642 return;
643 }
644 if (!ifs->readLogsEnabled()) {
645 return;
646 }
647 ifs->disableReadLogs();
648 l.unlock();
649
650 const auto metadata = constants().readLogsDisabledMarkerName;
651 if (auto err = mIncFs->makeFile(ifs->control,
652 path::join(ifs->root, constants().mount,
653 constants().readLogsDisabledMarkerName),
654 0777, idFromMetadata(metadata), {})) {
655 //{.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
656 LOG(ERROR) << "Failed to make marker file for storageId: " << storageId;
657 return;
658 }
659
660 setStorageParams(storageId, /*enableReadLogs=*/false);
661}
662
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700663int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
664 const auto ifs = getIfs(storageId);
665 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700666 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700667 return -EINVAL;
668 }
669
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700670 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700671 if (enableReadLogs) {
Alex Buynytskyy04035452020-06-06 20:15:58 -0700672 if (!ifs->readLogsEnabled()) {
673 LOG(ERROR) << "setStorageParams failed, readlogs disabled for storageId: " << storageId;
674 return -EPERM;
675 }
676
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700677 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
678 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700679 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700680 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700681 return fromBinderStatus(status);
682 }
683 }
684
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700685 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
686 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
687 return fromBinderStatus(status);
688 }
689
690 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700691 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700692 }
693
694 return 0;
695}
696
697binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700698 os::incremental::IncrementalFileSystemControlParcel control;
699 control.cmd.reset(dup(ifs.control.cmd()));
700 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700701 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700702 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700703 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700704 }
705
706 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700707 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700708}
709
Songchun Fan3c82a302019-11-29 14:23:45 -0800710void IncrementalService::deleteStorage(StorageId storageId) {
711 const auto ifs = getIfs(storageId);
712 if (!ifs) {
713 return;
714 }
715 deleteStorage(*ifs);
716}
717
718void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
719 std::unique_lock l(ifs.lock);
720 deleteStorageLocked(ifs, std::move(l));
721}
722
723void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
724 std::unique_lock<std::mutex>&& ifsLock) {
725 const auto storages = std::move(ifs.storages);
726 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
727 const auto bindPoints = ifs.bindPoints;
728 ifsLock.unlock();
729
730 std::lock_guard l(mLock);
731 for (auto&& [id, _] : storages) {
732 if (id != ifs.mountId) {
733 mMounts.erase(id);
734 }
735 }
736 for (auto&& [path, _] : bindPoints) {
737 mBindsByPath.erase(path);
738 }
739 mMounts.erase(ifs.mountId);
740}
741
742StorageId IncrementalService::openStorage(std::string_view pathInMount) {
743 if (!path::isAbsolute(pathInMount)) {
744 return kInvalidStorageId;
745 }
746
747 return findStorageId(path::normalize(pathInMount));
748}
749
Songchun Fan3c82a302019-11-29 14:23:45 -0800750IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
751 std::lock_guard l(mLock);
752 return getIfsLocked(storage);
753}
754
755const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
756 auto it = mMounts.find(storage);
757 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700758 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700759 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800760 }
761 return it->second;
762}
763
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800764int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
765 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800766 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700767 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800768 return -EINVAL;
769 }
770
771 const auto ifs = getIfs(storage);
772 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700773 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800774 return -EINVAL;
775 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800776
Songchun Fan3c82a302019-11-29 14:23:45 -0800777 std::unique_lock l(ifs->lock);
778 const auto storageInfo = ifs->storages.find(storage);
779 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700780 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800781 return -EINVAL;
782 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700783 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700784 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700785 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700786 return -EINVAL;
787 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800788 l.unlock();
789 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800790 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
791 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800792}
793
794int IncrementalService::unbind(StorageId storage, std::string_view target) {
795 if (!path::isAbsolute(target)) {
796 return -EINVAL;
797 }
798
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700799 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800800
801 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
802 // otherwise there's a chance to unmount something completely unrelated
803 const auto norm = path::normalize(target);
804 std::unique_lock l(mLock);
805 const auto storageIt = mBindsByPath.find(norm);
806 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
807 return -EINVAL;
808 }
809 const auto bindIt = storageIt->second;
810 const auto storageId = bindIt->second.storage;
811 const auto ifs = getIfsLocked(storageId);
812 if (!ifs) {
813 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
814 << " is missing";
815 return -EFAULT;
816 }
817 mBindsByPath.erase(storageIt);
818 l.unlock();
819
820 mVold->unmountIncFs(bindIt->first);
821 std::unique_lock l2(ifs->lock);
822 if (ifs->bindPoints.size() <= 1) {
823 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700824 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800825 } else {
826 const std::string savedFile = std::move(bindIt->second.savedFilename);
827 ifs->bindPoints.erase(bindIt);
828 l2.unlock();
829 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800830 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800831 }
832 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700833
Songchun Fan3c82a302019-11-29 14:23:45 -0800834 return 0;
835}
836
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700837std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700838 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700839 std::string_view path) const {
840 if (!path::isAbsolute(path)) {
841 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700842 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700843 auto normPath = path::normalize(path);
844 if (path::startsWith(normPath, storageIt->second.name)) {
845 return normPath;
846 }
847 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700848 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
849 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700850 return {};
851 }
852 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700853}
854
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700855std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700856 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700857 std::unique_lock l(ifs.lock);
858 const auto storageInfo = ifs.storages.find(storage);
859 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800860 return {};
861 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700862 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800863}
864
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800865int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700866 incfs::NewFileParams params, std::span<const uint8_t> data) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800867 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700868 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800869 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700870 LOG(ERROR) << "Internal error: storageId " << storage
871 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800872 return -EINVAL;
873 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700874 if (auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params); err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700875 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800876 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800877 }
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -0700878 if (!data.empty()) {
879 if (auto err = setFileContent(ifs, id, path, data); err) {
880 return err;
881 }
882 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800883 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800884 }
885 return -EINVAL;
886}
887
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800888int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800889 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700890 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800891 if (normPath.empty()) {
892 return -EINVAL;
893 }
894 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800895 }
896 return -EINVAL;
897}
898
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800899int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800900 const auto ifs = getIfs(storageId);
901 if (!ifs) {
902 return -EINVAL;
903 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700904 return makeDirs(*ifs, storageId, path, mode);
905}
906
907int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
908 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800909 std::string normPath = normalizePathToStorage(ifs, storageId, path);
910 if (normPath.empty()) {
911 return -EINVAL;
912 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700913 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800914}
915
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800916int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
917 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700918 std::unique_lock l(mLock);
919 auto ifsSrc = getIfsLocked(sourceStorageId);
920 if (!ifsSrc) {
921 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800922 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700923 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
924 return -EINVAL;
925 }
926 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700927 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
928 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700929 if (normOldPath.empty() || normNewPath.empty()) {
930 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
931 return -EINVAL;
932 }
933 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800934}
935
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800936int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800937 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700938 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800939 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800940 }
941 return -EINVAL;
942}
943
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800944int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
945 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800946 std::string&& target, BindKind kind,
947 std::unique_lock<std::mutex>& mainLock) {
948 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700949 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800950 return -EINVAL;
951 }
952
953 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700954 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800955 if (kind != BindKind::Temporary) {
956 metadata::BindPoint bp;
957 bp.set_storage_id(storage);
958 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800959 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800960 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800961 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800962 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800963 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700964 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
965 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
966 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800967 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700968 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800969 return int(node);
970 }
971 }
972
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700973 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
974 std::move(target), kind, mainLock);
975 if (res) {
976 mIncFs->unlink(ifs.control, metadataFullPath);
977 }
978 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800979}
980
981int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800982 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800983 std::string&& target, BindKind kind,
984 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800985 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800986 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800987 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800988 if (!status.isOk()) {
989 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
990 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
991 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
992 : status.serviceSpecificErrorCode() == 0
993 ? -EFAULT
994 : status.serviceSpecificErrorCode()
995 : -EIO;
996 }
997 }
998
999 if (!mainLock.owns_lock()) {
1000 mainLock.lock();
1001 }
1002 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001003 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
1004 std::move(target), kind);
1005 return 0;
1006}
1007
1008void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
1009 std::string&& metadataName, std::string&& source,
1010 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001011 const auto [it, _] =
1012 ifs.bindPoints.insert_or_assign(target,
1013 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001014 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -08001015 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001016}
1017
1018RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
1019 const auto ifs = getIfs(storage);
1020 if (!ifs) {
1021 return {};
1022 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001023 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001024 if (normPath.empty()) {
1025 return {};
1026 }
1027 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -08001028}
1029
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001030RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -08001031 const auto ifs = getIfs(storage);
1032 if (!ifs) {
1033 return {};
1034 }
1035 return mIncFs->getMetadata(ifs->control, node);
1036}
1037
Songchun Fan3c82a302019-11-29 14:23:45 -08001038bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001039 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001040 {
1041 std::unique_lock l(mLock);
1042 const auto& ifs = getIfsLocked(storage);
1043 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001044 return false;
1045 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001046 dataLoaderStub = ifs->dataLoaderStub;
1047 if (!dataLoaderStub) {
1048 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001049 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001050 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001051 dataLoaderStub->requestStart();
1052 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001053}
1054
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001055std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1056 std::unordered_set<std::string_view> mountedRootNames;
1057 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1058 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1059 for (auto [source, target] : binds) {
1060 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1061 LOG(INFO) << " " << path::join(root, source);
1062 }
1063
1064 // Ensure it's a kind of a mount that's managed by IncrementalService
1065 if (path::basename(root) != constants().mount ||
1066 path::basename(backingDir) != constants().backing) {
1067 return;
1068 }
1069 const auto expectedRoot = path::dirname(root);
1070 if (path::dirname(backingDir) != expectedRoot) {
1071 return;
1072 }
1073 if (path::dirname(expectedRoot) != mIncrementalDir) {
1074 return;
1075 }
1076 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1077 return;
1078 }
1079
1080 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1081
1082 // make sure we clean up the mount if it happens to be a bad one.
1083 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1084 auto cleanupFiles = makeCleanup([&]() {
1085 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1086 IncFsMount::cleanupFilesystem(expectedRoot);
1087 });
1088 auto cleanupMounts = makeCleanup([&]() {
1089 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1090 for (auto&& [_, target] : binds) {
1091 mVold->unmountIncFs(std::string(target));
1092 }
1093 mVold->unmountIncFs(std::string(root));
1094 });
1095
1096 auto control = mIncFs->openMount(root);
1097 if (!control) {
1098 LOG(INFO) << "failed to open mount " << root;
1099 return;
1100 }
1101
1102 auto mountRecord =
1103 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1104 path::join(root, constants().infoMdName));
1105 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1106 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1107 return;
1108 }
1109
1110 auto mountId = mountRecord.storage().id();
1111 mNextId = std::max(mNextId, mountId + 1);
1112
1113 DataLoaderParamsParcel dataLoaderParams;
1114 {
1115 const auto& loader = mountRecord.loader();
1116 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1117 dataLoaderParams.packageName = loader.package_name();
1118 dataLoaderParams.className = loader.class_name();
1119 dataLoaderParams.arguments = loader.arguments();
1120 }
1121
1122 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1123 std::move(control), *this);
1124 cleanupFiles.release(); // ifs will take care of that now
1125
Alex Buynytskyy04035452020-06-06 20:15:58 -07001126 // Check if marker file present.
1127 if (checkReadLogsDisabledMarker(root)) {
1128 ifs->disableReadLogs();
1129 }
1130
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001131 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1132 auto d = openDir(root);
1133 while (auto e = ::readdir(d.get())) {
1134 if (e->d_type == DT_REG) {
1135 auto name = std::string_view(e->d_name);
1136 if (name.starts_with(constants().mountpointMdPrefix)) {
1137 permanentBindPoints
1138 .emplace_back(name,
1139 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1140 ifs->control,
1141 path::join(root,
1142 name)));
1143 if (permanentBindPoints.back().second.dest_path().empty() ||
1144 permanentBindPoints.back().second.source_subdir().empty()) {
1145 permanentBindPoints.pop_back();
1146 mIncFs->unlink(ifs->control, path::join(root, name));
1147 } else {
1148 LOG(INFO) << "Permanent bind record: '"
1149 << permanentBindPoints.back().second.source_subdir() << "'->'"
1150 << permanentBindPoints.back().second.dest_path() << "'";
1151 }
1152 }
1153 } else if (e->d_type == DT_DIR) {
1154 if (e->d_name == "."sv || e->d_name == ".."sv) {
1155 continue;
1156 }
1157 auto name = std::string_view(e->d_name);
1158 if (name.starts_with(constants().storagePrefix)) {
1159 int storageId;
1160 const auto res =
1161 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1162 name.data() + name.size(), storageId);
1163 if (res.ec != std::errc{} || *res.ptr != '_') {
1164 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1165 << "' for mount " << expectedRoot;
1166 continue;
1167 }
1168 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1169 if (!inserted) {
1170 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1171 << " for mount " << expectedRoot;
1172 continue;
1173 }
1174 ifs->storages.insert_or_assign(storageId,
1175 IncFsMount::Storage{path::join(root, name)});
1176 mNextId = std::max(mNextId, storageId + 1);
1177 }
1178 }
1179 }
1180
1181 if (ifs->storages.empty()) {
1182 LOG(WARNING) << "No valid storages in mount " << root;
1183 return;
1184 }
1185
1186 // now match the mounted directories with what we expect to have in the metadata
1187 {
1188 std::unique_lock l(mLock, std::defer_lock);
1189 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1190 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1191 [&, bindRecord = bindRecord](auto&& bind) {
1192 return bind.second == bindRecord.dest_path() &&
1193 path::join(root, bind.first) ==
1194 bindRecord.source_subdir();
1195 });
1196 if (mountedIt != binds.end()) {
1197 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1198 << " to mount " << mountedIt->first;
1199 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1200 std::move(*bindRecord.mutable_source_subdir()),
1201 std::move(*bindRecord.mutable_dest_path()),
1202 BindKind::Permanent);
1203 if (mountedIt != binds.end() - 1) {
1204 std::iter_swap(mountedIt, binds.end() - 1);
1205 }
1206 binds = binds.first(binds.size() - 1);
1207 } else {
1208 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1209 << ", mounting";
1210 // doesn't exist - try mounting back
1211 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1212 std::move(*bindRecord.mutable_source_subdir()),
1213 std::move(*bindRecord.mutable_dest_path()),
1214 BindKind::Permanent, l)) {
1215 mIncFs->unlink(ifs->control, metadataFile);
1216 }
1217 }
1218 }
1219 }
1220
1221 // if anything stays in |binds| those are probably temporary binds; system restarted since
1222 // they were mounted - so let's unmount them all.
1223 for (auto&& [source, target] : binds) {
1224 if (source.empty()) {
1225 continue;
1226 }
1227 mVold->unmountIncFs(std::string(target));
1228 }
1229 cleanupMounts.release(); // ifs now manages everything
1230
1231 if (ifs->bindPoints.empty()) {
1232 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1233 deleteStorage(*ifs);
1234 return;
1235 }
1236
1237 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1238 CHECK(ifs->dataLoaderStub);
1239
1240 mountedRootNames.insert(path::basename(ifs->root));
1241
1242 // not locking here at all: we're still in the constructor, no other calls can happen
1243 mMounts[ifs->mountId] = std::move(ifs);
1244 });
1245
1246 return mountedRootNames;
1247}
1248
1249void IncrementalService::mountExistingImages(
1250 const std::unordered_set<std::string_view>& mountedRootNames) {
1251 auto dir = openDir(mIncrementalDir);
1252 if (!dir) {
1253 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1254 return;
1255 }
1256 while (auto entry = ::readdir(dir.get())) {
1257 if (entry->d_type != DT_DIR) {
1258 continue;
1259 }
1260 std::string_view name = entry->d_name;
1261 if (!name.starts_with(constants().mountKeyPrefix)) {
1262 continue;
1263 }
1264 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001265 continue;
1266 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001267 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001268 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001269 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001270 }
1271 }
1272}
1273
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001274bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001275 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001276 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001277
Songchun Fan3c82a302019-11-29 14:23:45 -08001278 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001279 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001280 if (!status.isOk()) {
1281 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1282 return false;
1283 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001284
1285 int cmd = controlParcel.cmd.release().release();
1286 int pendingReads = controlParcel.pendingReads.release().release();
1287 int logs = controlParcel.log.release().release();
1288 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001289
1290 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1291
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001292 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1293 path::join(mountTarget, constants().infoMdName));
1294 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001295 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1296 return false;
1297 }
1298
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001299 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001300 mNextId = std::max(mNextId, ifs->mountId + 1);
1301
Alex Buynytskyy04035452020-06-06 20:15:58 -07001302 // Check if marker file present.
1303 if (checkReadLogsDisabledMarker(mountTarget)) {
1304 ifs->disableReadLogs();
1305 }
1306
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001307 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001308 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001309 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001310 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001311 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001312 dataLoaderParams.packageName = loader.package_name();
1313 dataLoaderParams.className = loader.class_name();
1314 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001315 }
1316
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001317 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001318 CHECK(ifs->dataLoaderStub);
1319
Songchun Fan3c82a302019-11-29 14:23:45 -08001320 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001321 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001322 while (auto e = ::readdir(d.get())) {
1323 if (e->d_type == DT_REG) {
1324 auto name = std::string_view(e->d_name);
1325 if (name.starts_with(constants().mountpointMdPrefix)) {
1326 bindPoints.emplace_back(name,
1327 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1328 ifs->control,
1329 path::join(mountTarget,
1330 name)));
1331 if (bindPoints.back().second.dest_path().empty() ||
1332 bindPoints.back().second.source_subdir().empty()) {
1333 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001334 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001335 }
1336 }
1337 } else if (e->d_type == DT_DIR) {
1338 if (e->d_name == "."sv || e->d_name == ".."sv) {
1339 continue;
1340 }
1341 auto name = std::string_view(e->d_name);
1342 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001343 int storageId;
1344 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1345 name.data() + name.size(), storageId);
1346 if (res.ec != std::errc{} || *res.ptr != '_') {
1347 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1348 << root;
1349 continue;
1350 }
1351 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001352 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001353 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001354 << " for mount " << root;
1355 continue;
1356 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001357 ifs->storages.insert_or_assign(storageId,
1358 IncFsMount::Storage{
1359 path::join(root, constants().mount, name)});
1360 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001361 }
1362 }
1363 }
1364
1365 if (ifs->storages.empty()) {
1366 LOG(WARNING) << "No valid storages in mount " << root;
1367 return false;
1368 }
1369
1370 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001371 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001372 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001373 for (auto&& bp : bindPoints) {
1374 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1375 std::move(*bp.second.mutable_source_subdir()),
1376 std::move(*bp.second.mutable_dest_path()),
1377 BindKind::Permanent, l);
1378 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001379 }
1380
1381 if (bindCount == 0) {
1382 LOG(WARNING) << "No valid bind points for mount " << root;
1383 deleteStorage(*ifs);
1384 return false;
1385 }
1386
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001387 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001388 mMounts[ifs->mountId] = std::move(ifs);
1389 return true;
1390}
1391
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001392void IncrementalService::runCmdLooper() {
Alex Buynytskyyb65a77f2020-09-22 11:39:53 -07001393 constexpr auto kTimeoutMsecs = -1;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001394 while (mRunning.load(std::memory_order_relaxed)) {
1395 mLooper->pollAll(kTimeoutMsecs);
1396 }
1397}
1398
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001399IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001400 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001401 const DataLoaderStatusListener* statusListener,
1402 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001403 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001404 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1405 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001406 return ifs.dataLoaderStub;
1407}
1408
1409void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001410 const DataLoaderStatusListener* statusListener,
1411 StorageHealthCheckParams&& healthCheckParams,
1412 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001413 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001414 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001415 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001416 }
1417
Songchun Fan3c82a302019-11-29 14:23:45 -08001418 FileSystemControlParcel fsControlParcel;
Jooyung Han16bac852020-08-10 12:53:14 +09001419 fsControlParcel.incremental = std::make_optional<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001420 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1421 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1422 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001423 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001424
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001425 ifs.dataLoaderStub =
1426 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001427 statusListener, std::move(healthCheckParams), healthListener,
1428 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001429}
1430
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001431template <class Duration>
1432static long elapsedMcs(Duration start, Duration end) {
1433 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1434}
1435
1436// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fanc8975312020-07-13 12:14:37 -07001437// Lib files should be placed next to the APK file in the following matter:
1438// Example:
1439// /path/to/base.apk
1440// /path/to/lib/arm/first.so
1441// /path/to/lib/arm/second.so
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001442bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1443 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001444 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001445 auto start = Clock::now();
1446
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001447 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001448 if (!ifs) {
1449 LOG(ERROR) << "Invalid storage " << storage;
1450 return false;
1451 }
1452
Songchun Fanc8975312020-07-13 12:14:37 -07001453 const auto targetLibPathRelativeToStorage =
1454 path::join(path::dirname(normalizePathToStorage(*ifs, storage, apkFullPath)),
1455 libDirRelativePath);
1456
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001457 // First prepare target directories if they don't exist yet
Songchun Fanc8975312020-07-13 12:14:37 -07001458 if (auto res = makeDirs(*ifs, storage, targetLibPathRelativeToStorage, 0755)) {
1459 LOG(ERROR) << "Failed to prepare target lib directory " << targetLibPathRelativeToStorage
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001460 << " errno: " << res;
1461 return false;
1462 }
1463
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001464 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001465 ZipArchiveHandle zipFileHandle;
1466 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001467 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1468 return false;
1469 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001470
1471 // Need a shared pointer: will be passing it into all unpacking jobs.
1472 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001473 void* cookie = nullptr;
Songchun Fan2ff2a482020-09-29 11:45:18 -07001474 const auto libFilePrefix = path::join(constants().libDir, abi) + "/";
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001475 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001476 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1477 return false;
1478 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001479 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001480 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1481
1482 auto openZipTs = Clock::now();
1483
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001484 std::vector<Job> jobQueue;
1485 ZipEntry entry;
1486 std::string_view fileName;
1487 while (!Next(cookie, &entry, &fileName)) {
1488 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001489 continue;
1490 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001491
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001492 if (!extractNativeLibs) {
1493 // ensure the file is properly aligned and unpacked
1494 if (entry.method != kCompressStored) {
1495 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1496 return false;
1497 }
1498 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1499 LOG(WARNING) << "Library " << fileName
1500 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1501 << entry.offset;
1502 return false;
1503 }
1504 continue;
1505 }
1506
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001507 auto startFileTs = Clock::now();
1508
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001509 const auto libName = path::basename(fileName);
Songchun Fanc8975312020-07-13 12:14:37 -07001510 auto targetLibPath = path::join(targetLibPathRelativeToStorage, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001511 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001512 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001513 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001514 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001515 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1516 << "; skipping extraction, spent "
1517 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1518 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001519 continue;
1520 }
1521
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001522 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001523 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001524 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001525 .signature = {},
1526 // Metadata of the new lib file is its relative path
1527 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1528 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001529 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001530 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1531 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001532 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001533 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001534 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001535 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001536
1537 auto makeFileTs = Clock::now();
1538
Songchun Fanafaf6e92020-03-18 14:12:20 -07001539 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001540 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001541 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001542 LOG(INFO) << "incfs: Extracted " << libName
1543 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001544 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001545 continue;
1546 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001547
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001548 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1549 libFileId, libPath = std::move(targetLibPath),
1550 makeFileTs]() mutable {
1551 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001552 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001553
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001554 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001555 auto prepareJobTs = Clock::now();
1556 LOG(INFO) << "incfs: Processed " << libName << ": "
1557 << elapsedMcs(startFileTs, prepareJobTs)
1558 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1559 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001560 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001561 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001562
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001563 auto processedTs = Clock::now();
1564
1565 if (!jobQueue.empty()) {
1566 {
1567 std::lock_guard lock(mJobMutex);
1568 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001569 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001570 if (existingJobs.empty()) {
1571 existingJobs = std::move(jobQueue);
1572 } else {
1573 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1574 std::move_iterator(jobQueue.end()));
1575 }
1576 }
1577 }
1578 mJobCondition.notify_all();
1579 }
1580
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001581 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001582 auto end = Clock::now();
1583 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1584 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1585 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001586 << " make files: " << elapsedMcs(openZipTs, processedTs)
1587 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001588 }
1589
1590 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001591}
1592
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001593void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1594 ZipEntry& entry, const incfs::FileId& libFileId,
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001595 std::string_view debugLibPath,
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001596 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001597 if (!ifs) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001598 LOG(INFO) << "Skipping zip file " << debugLibPath << " extraction for an expired mount";
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001599 return;
1600 }
1601
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001602 auto startedTs = Clock::now();
1603
1604 // Write extracted data to new file
1605 // NOTE: don't zero-initialize memory, it may take a while for nothing
1606 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1607 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001608 LOG(ERROR) << "Failed to extract native lib zip entry: " << path::basename(debugLibPath);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001609 return;
1610 }
1611
1612 auto extractFileTs = Clock::now();
1613
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001614 if (setFileContent(ifs, libFileId, debugLibPath,
1615 std::span(libData.get(), entry.uncompressed_length))) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001616 return;
1617 }
1618
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001619 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001620 auto endFileTs = Clock::now();
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001621 LOG(INFO) << "incfs: Extracted " << path::basename(debugLibPath) << "("
1622 << entry.compressed_length << " -> " << entry.uncompressed_length
1623 << " bytes): " << elapsedMcs(startedTs, endFileTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001624 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1625 << " extract: " << elapsedMcs(startedTs, extractFileTs)
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001626 << " open/prepare/write: " << elapsedMcs(extractFileTs, endFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001627 }
1628}
1629
1630bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001631 struct WaitPrinter {
1632 const Clock::time_point startTs = Clock::now();
1633 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001634 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001635 const auto endTs = Clock::now();
1636 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1637 << elapsedMcs(startTs, endTs) << "mcs";
1638 }
1639 }
1640 } waitPrinter;
1641
1642 MountId mount;
1643 {
1644 auto ifs = getIfs(storage);
1645 if (!ifs) {
1646 return true;
1647 }
1648 mount = ifs->mountId;
1649 }
1650
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001651 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001652 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001653 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001654 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001655 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001656 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001657}
1658
Alex Buynytskyyb39d13e2020-09-12 16:12:36 -07001659int IncrementalService::setFileContent(const IfsMountPtr& ifs, const incfs::FileId& fileId,
1660 std::string_view debugFilePath,
1661 std::span<const uint8_t> data) const {
1662 auto startTs = Clock::now();
1663
1664 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, fileId);
1665 if (!writeFd.ok()) {
1666 LOG(ERROR) << "Failed to open write fd for: " << debugFilePath
1667 << " errno: " << writeFd.get();
1668 return writeFd.get();
1669 }
1670
1671 const auto dataLength = data.size();
1672
1673 auto openFileTs = Clock::now();
1674 const int numBlocks = (data.size() + constants().blockSize - 1) / constants().blockSize;
1675 std::vector<IncFsDataBlock> instructions(numBlocks);
1676 for (int i = 0; i < numBlocks; i++) {
1677 const auto blockSize = std::min<long>(constants().blockSize, data.size());
1678 instructions[i] = IncFsDataBlock{
1679 .fileFd = writeFd.get(),
1680 .pageIndex = static_cast<IncFsBlockIndex>(i),
1681 .compression = INCFS_COMPRESSION_KIND_NONE,
1682 .kind = INCFS_BLOCK_KIND_DATA,
1683 .dataSize = static_cast<uint32_t>(blockSize),
1684 .data = reinterpret_cast<const char*>(data.data()),
1685 };
1686 data = data.subspan(blockSize);
1687 }
1688 auto prepareInstsTs = Clock::now();
1689
1690 size_t res = mIncFs->writeBlocks(instructions);
1691 if (res != instructions.size()) {
1692 LOG(ERROR) << "Failed to write data into: " << debugFilePath;
1693 return res;
1694 }
1695
1696 if (perfLoggingEnabled()) {
1697 auto endTs = Clock::now();
1698 LOG(INFO) << "incfs: Set file content " << debugFilePath << "(" << dataLength
1699 << " bytes): " << elapsedMcs(startTs, endTs)
1700 << "mcs, open: " << elapsedMcs(startTs, openFileTs)
1701 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1702 << " write: " << elapsedMcs(prepareInstsTs, endTs);
1703 }
1704
1705 return 0;
1706}
1707
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -07001708int IncrementalService::isFileFullyLoaded(StorageId storage, const std::string& path) const {
1709 std::unique_lock l(mLock);
1710 const auto ifs = getIfsLocked(storage);
1711 if (!ifs) {
1712 LOG(ERROR) << "isFileFullyLoaded failed, invalid storageId: " << storage;
1713 return -EINVAL;
1714 }
1715 const auto storageInfo = ifs->storages.find(storage);
1716 if (storageInfo == ifs->storages.end()) {
1717 LOG(ERROR) << "isFileFullyLoaded failed, no storage: " << storage;
1718 return -EINVAL;
1719 }
1720 l.unlock();
1721 return isFileFullyLoadedFromPath(*ifs, path);
1722}
1723
1724int IncrementalService::isFileFullyLoadedFromPath(const IncFsMount& ifs,
1725 std::string_view filePath) const {
1726 const auto [filledBlocks, totalBlocks] = mIncFs->countFilledBlocks(ifs.control, filePath);
1727 if (filledBlocks < 0) {
1728 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get filled blocks count for: "
1729 << filePath << " errno: " << filledBlocks;
1730 return filledBlocks;
1731 }
1732 if (totalBlocks < filledBlocks) {
1733 LOG(ERROR) << "isFileFullyLoadedFromPath failed to get total num of blocks";
1734 return -EINVAL;
1735 }
1736 return totalBlocks - filledBlocks;
1737}
1738
Songchun Fan374f7652020-08-20 08:40:29 -07001739float IncrementalService::getLoadingProgress(StorageId storage) const {
1740 std::unique_lock l(mLock);
1741 const auto ifs = getIfsLocked(storage);
1742 if (!ifs) {
1743 LOG(ERROR) << "getLoadingProgress failed, invalid storageId: " << storage;
1744 return -EINVAL;
1745 }
1746 const auto storageInfo = ifs->storages.find(storage);
1747 if (storageInfo == ifs->storages.end()) {
1748 LOG(ERROR) << "getLoadingProgress failed, no storage: " << storage;
1749 return -EINVAL;
1750 }
1751 l.unlock();
1752 return getLoadingProgressFromPath(*ifs, storageInfo->second.name);
1753}
1754
1755float IncrementalService::getLoadingProgressFromPath(const IncFsMount& ifs,
1756 std::string_view storagePath) const {
1757 size_t totalBlocks = 0, filledBlocks = 0;
1758 const auto filePaths = mFs->listFilesRecursive(storagePath);
1759 for (const auto& filePath : filePaths) {
1760 const auto [filledBlocksCount, totalBlocksCount] =
1761 mIncFs->countFilledBlocks(ifs.control, filePath);
1762 if (filledBlocksCount < 0) {
1763 LOG(ERROR) << "getLoadingProgress failed to get filled blocks count for: " << filePath
1764 << " errno: " << filledBlocksCount;
1765 return filledBlocksCount;
1766 }
1767 totalBlocks += totalBlocksCount;
1768 filledBlocks += filledBlocksCount;
1769 }
1770
1771 if (totalBlocks == 0) {
Songchun Fan425862f2020-08-25 13:12:16 -07001772 // No file in the storage or files are empty; regarded as fully loaded
1773 return 1;
Songchun Fan374f7652020-08-20 08:40:29 -07001774 }
1775 return (float)filledBlocks / (float)totalBlocks;
1776}
1777
Songchun Fana7098592020-09-03 11:45:53 -07001778bool IncrementalService::updateLoadingProgress(
1779 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1780 const auto progress = getLoadingProgress(storage);
1781 if (progress < 0) {
1782 // Failed to get progress from incfs, abort.
1783 return false;
1784 }
1785 progressListener->onStorageLoadingProgressChanged(storage, progress);
1786 if (progress > 1 - 0.001f) {
1787 // Stop updating progress once it is fully loaded
1788 return true;
1789 }
1790 static constexpr auto kProgressUpdateInterval = 1000ms;
1791 addTimedJob(*mProgressUpdateJobQueue, storage, kProgressUpdateInterval /* repeat after 1s */,
1792 [storage, progressListener, this]() {
1793 updateLoadingProgress(storage, progressListener);
1794 });
1795 return true;
1796}
1797
1798bool IncrementalService::registerLoadingProgressListener(
1799 StorageId storage, const StorageLoadingProgressListener& progressListener) {
1800 return updateLoadingProgress(storage, progressListener);
1801}
1802
1803bool IncrementalService::unregisterLoadingProgressListener(StorageId storage) {
1804 return removeTimedJobs(*mProgressUpdateJobQueue, storage);
1805}
1806
Songchun Fan2570ec02020-10-08 17:22:33 -07001807bool IncrementalService::registerStorageHealthListener(
1808 StorageId storage, StorageHealthCheckParams&& healthCheckParams,
1809 const StorageHealthListener& healthListener) {
1810 DataLoaderStubPtr dataLoaderStub;
1811 {
1812 std::unique_lock l(mLock);
1813 const auto& ifs = getIfsLocked(storage);
1814 if (!ifs) {
1815 return false;
1816 }
1817 dataLoaderStub = ifs->dataLoaderStub;
1818 if (!dataLoaderStub) {
1819 return false;
1820 }
1821 }
1822 dataLoaderStub->setHealthListener(std::move(healthCheckParams), &healthListener);
1823 return true;
1824}
1825
1826void IncrementalService::unregisterStorageHealthListener(StorageId storage) {
1827 StorageHealthCheckParams invalidCheckParams;
1828 invalidCheckParams.blockedTimeoutMs = -1;
1829 registerStorageHealthListener(storage, std::move(invalidCheckParams), {});
1830}
1831
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001832bool IncrementalService::perfLoggingEnabled() {
1833 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1834 return enabled;
1835}
1836
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001837void IncrementalService::runJobProcessing() {
1838 for (;;) {
1839 std::unique_lock lock(mJobMutex);
1840 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1841 if (!mRunning) {
1842 return;
1843 }
1844
1845 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001846 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001847 auto queue = std::move(it->second);
1848 mJobQueue.erase(it);
1849 lock.unlock();
1850
1851 for (auto&& job : queue) {
1852 job();
1853 }
1854
1855 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001856 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001857 lock.unlock();
1858 mJobCondition.notify_all();
1859 }
1860}
1861
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001862void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001863 sp<IAppOpsCallback> listener;
1864 {
1865 std::unique_lock lock{mCallbacksLock};
1866 auto& cb = mCallbackRegistered[packageName];
1867 if (cb) {
1868 return;
1869 }
1870 cb = new AppOpsListener(*this, packageName);
1871 listener = cb;
1872 }
1873
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001874 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1875 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001876}
1877
1878bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1879 sp<IAppOpsCallback> listener;
1880 {
1881 std::unique_lock lock{mCallbacksLock};
1882 auto found = mCallbackRegistered.find(packageName);
1883 if (found == mCallbackRegistered.end()) {
1884 return false;
1885 }
1886 listener = found->second;
1887 mCallbackRegistered.erase(found);
1888 }
1889
1890 mAppOpsManager->stopWatchingMode(listener);
1891 return true;
1892}
1893
1894void IncrementalService::onAppOpChanged(const std::string& packageName) {
1895 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001896 return;
1897 }
1898
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001899 std::vector<IfsMountPtr> affected;
1900 {
1901 std::lock_guard l(mLock);
1902 affected.reserve(mMounts.size());
1903 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001904 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001905 affected.push_back(ifs);
1906 }
1907 }
1908 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001909 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001910 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001911 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001912}
1913
Songchun Fana7098592020-09-03 11:45:53 -07001914bool IncrementalService::addTimedJob(TimedQueueWrapper& timedQueue, MountId id, Milliseconds after,
1915 Job what) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001916 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07001917 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001918 }
Songchun Fana7098592020-09-03 11:45:53 -07001919 timedQueue.addJob(id, after, std::move(what));
1920 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001921}
1922
Songchun Fana7098592020-09-03 11:45:53 -07001923bool IncrementalService::removeTimedJobs(TimedQueueWrapper& timedQueue, MountId id) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001924 if (id == kInvalidStorageId) {
Songchun Fana7098592020-09-03 11:45:53 -07001925 return false;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001926 }
Songchun Fana7098592020-09-03 11:45:53 -07001927 timedQueue.removeJobs(id);
1928 return true;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001929}
1930
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001931IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1932 DataLoaderParamsParcel&& params,
1933 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001934 const DataLoaderStatusListener* statusListener,
1935 StorageHealthCheckParams&& healthCheckParams,
1936 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001937 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001938 : mService(service),
1939 mId(id),
1940 mParams(std::move(params)),
1941 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001942 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
1943 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001944 mHealthPath(std::move(healthPath)),
1945 mHealthCheckParams(std::move(healthCheckParams)) {
1946 if (mHealthListener) {
1947 if (!isHealthParamsValid()) {
1948 mHealthListener = {};
1949 }
1950 } else {
1951 // Disable advanced health check statuses.
1952 mHealthCheckParams.blockedTimeoutMs = -1;
1953 }
1954 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001955}
1956
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001957IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001958 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001959 cleanupResources();
1960 }
1961}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001962
1963void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001964 auto now = Clock::now();
1965 {
1966 std::unique_lock lock(mMutex);
1967 mHealthPath.clear();
1968 unregisterFromPendingReads();
1969 resetHealthControl();
Songchun Fana7098592020-09-03 11:45:53 -07001970 mService.removeTimedJobs(*mService.mTimedQueue, mId);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001971 }
1972
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001973 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001974
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001975 {
1976 std::unique_lock lock(mMutex);
1977 mParams = {};
1978 mControl = {};
1979 mHealthControl = {};
1980 mHealthListener = {};
1981 mStatusCondition.wait_until(lock, now + 60s, [this] {
1982 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1983 });
1984 mStatusListener = {};
1985 mId = kInvalidStorageId;
1986 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001987}
1988
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001989sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1990 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001991 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001992 if (!status.isOk()) {
1993 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1994 return {};
1995 }
1996 if (!dataloader) {
1997 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1998 return {};
1999 }
2000 return dataloader;
2001}
2002
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002003bool IncrementalService::DataLoaderStub::requestCreate() {
2004 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
2005}
2006
2007bool IncrementalService::DataLoaderStub::requestStart() {
2008 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2009}
2010
2011bool IncrementalService::DataLoaderStub::requestDestroy() {
2012 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
2013}
2014
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002015bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002016 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002017 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002018 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002019 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002020 return fsmStep();
2021}
2022
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002023void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002024 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002025 mTargetStatus = status;
2026 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002027 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002028 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002029}
2030
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002031bool IncrementalService::DataLoaderStub::bind() {
2032 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002033 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002034 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002035 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002036 return false;
2037 }
2038 return true;
2039}
2040
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002041bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002042 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002043 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002044 return false;
2045 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002046 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002047 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002048 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002049 return false;
2050 }
2051 return true;
2052}
2053
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002054bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002055 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002056 if (!dataloader) {
2057 return false;
2058 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002059 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002060 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002061 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002062 return false;
2063 }
2064 return true;
2065}
2066
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002067bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002068 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002069}
2070
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002071bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002072 if (!isValid()) {
2073 return false;
2074 }
2075
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002076 int currentStatus;
2077 int targetStatus;
2078 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002079 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002080 currentStatus = mCurrentStatus;
2081 targetStatus = mTargetStatus;
2082 }
2083
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002084 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002085
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002086 if (currentStatus == targetStatus) {
2087 return true;
2088 }
2089
2090 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002091 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
2092 // Do nothing, this is a reset state.
2093 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002094 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
2095 return destroy();
2096 }
2097 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
2098 switch (currentStatus) {
2099 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2100 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
2101 return start();
2102 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002103 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002104 }
2105 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
2106 switch (currentStatus) {
2107 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002108 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07002109 return bind();
2110 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002111 return create();
2112 }
2113 break;
2114 default:
2115 LOG(ERROR) << "Invalid target status: " << targetStatus
2116 << ", current status: " << currentStatus;
2117 break;
2118 }
2119 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002120}
2121
2122binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002123 if (!isValid()) {
2124 return binder::Status::
2125 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
2126 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002127 if (id() != mountId) {
2128 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07002129 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2130 }
2131
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002132 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002133 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002134 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002135 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002136 if (mCurrentStatus == newStatus) {
2137 return binder::Status::ok();
2138 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002139
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002140 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07002141 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002142 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002143
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002144 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002145
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002146 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07002147 // For unavailable, unbind from DataLoader to ensure proper re-commit.
2148 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07002149 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002150 }
2151
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07002152 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002153 << newStatus << " (target " << targetStatus << ")";
2154
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07002155 if (listener) {
2156 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07002157 }
2158
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002159 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08002160
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07002161 mStatusCondition.notify_all();
2162
Songchun Fan3c82a302019-11-29 14:23:45 -08002163 return binder::Status::ok();
2164}
2165
Songchun Fan33093982020-09-10 13:12:39 -07002166binder::Status IncrementalService::DataLoaderStub::reportStreamHealth(MountId mountId,
2167 int newStatus) {
Songchun Fan2570ec02020-10-08 17:22:33 -07002168 if (!isValid()) {
2169 return binder::Status::
2170 fromServiceSpecificError(-EINVAL,
2171 "reportStreamHealth came to invalid DataLoaderStub");
2172 }
2173 if (id() != mountId) {
2174 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
2175 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
2176 }
2177 {
2178 std::lock_guard lock(mMutex);
2179 mStreamStatus = newStatus;
2180 }
Songchun Fan33093982020-09-10 13:12:39 -07002181 return binder::Status::ok();
2182}
2183
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002184bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
2185 return mHealthCheckParams.blockedTimeoutMs > 0 &&
2186 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002187}
2188
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002189void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2190 int healthStatus) {
2191 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2192 if (healthListener) {
2193 healthListener->onHealthStatus(id(), healthStatus);
2194 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002195}
2196
Songchun Fan2570ec02020-10-08 17:22:33 -07002197static int adjustHealthStatus(int healthStatus, int streamStatus) {
2198 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_OK) {
2199 // everything is good; no need to change status
2200 return healthStatus;
2201 }
2202 int newHeathStatus = healthStatus;
2203 switch (streamStatus) {
2204 case IDataLoaderStatusListener::STREAM_STORAGE_ERROR:
2205 // storage is limited and storage not healthy
2206 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_STORAGE;
2207 break;
2208 case IDataLoaderStatusListener::STREAM_INTEGRITY_ERROR:
2209 // fall through
2210 case IDataLoaderStatusListener::STREAM_SOURCE_ERROR:
2211 // fall through
2212 case IDataLoaderStatusListener::STREAM_TRANSPORT_ERROR:
2213 if (healthStatus == IStorageHealthListener::HEALTH_STATUS_UNHEALTHY) {
2214 newHeathStatus = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY_TRANSPORT;
2215 }
2216 // pending/blocked status due to transportation issues is not regarded as unhealthy
2217 break;
2218 default:
2219 break;
2220 }
2221 return newHeathStatus;
2222}
2223
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002224void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2225 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002226
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002227 int healthStatusToReport = -1;
2228 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002229
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002230 {
2231 std::unique_lock lock(mMutex);
2232 unregisterFromPendingReads();
2233
2234 healthListener = mHealthListener;
2235
2236 // Healthcheck depends on timestamp of the oldest pending read.
2237 // 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 -07002238 // Additionally we need to re-register for epoll with fresh FDs in case there are no
2239 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002240 const auto now = Clock::now();
2241 const auto kernelTsUs = getOldestPendingReadTs();
2242 if (baseline) {
Songchun Fan374f7652020-08-20 08:40:29 -07002243 // Updating baseline only on looper/epoll callback, i.e. on new set of pending
2244 // reads.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002245 mHealthBase = {now, kernelTsUs};
2246 }
2247
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002248 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.kernelTsUs == kMaxBootClockTsUs ||
2249 mHealthBase.userTs > now) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002250 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2251 registerForPendingReads();
2252 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2253 lock.unlock();
2254 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002255 return;
2256 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002257
2258 resetHealthControl();
2259
2260 // Always make sure the data loader is started.
2261 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2262
2263 // Skip any further processing if health check params are invalid.
2264 if (!isHealthParamsValid()) {
2265 LOG(DEBUG) << id()
2266 << ": Skip any further processing if health check params are invalid.";
2267 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2268 lock.unlock();
2269 onHealthStatus(healthListener, healthStatusToReport);
2270 // Triggering data loader start. This is a one-time action.
2271 fsmStep();
2272 return;
2273 }
2274
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002275 // Don't schedule timer job less than 500ms in advance.
2276 static constexpr auto kTolerance = 500ms;
2277
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002278 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2279 const auto unhealthyTimeout =
2280 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2281 const auto unhealthyMonitoring =
2282 std::max(1000ms,
2283 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2284
2285 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2286 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002287 const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - userTs);
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002288
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002289 Milliseconds checkBackAfter;
2290 if (delta + kTolerance < blockedTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002291 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002292 checkBackAfter = blockedTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002293 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002294 } else if (delta + kTolerance < unhealthyTimeout) {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002295 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002296 checkBackAfter = unhealthyTimeout - delta;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002297 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2298 } else {
2299 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002300 checkBackAfter = unhealthyMonitoring;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002301 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2302 }
Songchun Fan2570ec02020-10-08 17:22:33 -07002303 // Adjust health status based on stream status
2304 healthStatusToReport = adjustHealthStatus(healthStatusToReport, mStreamStatus);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002305 LOG(DEBUG) << id() << ": updateHealthStatus in " << double(checkBackAfter.count()) / 1000.0
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002306 << "secs";
Songchun Fana7098592020-09-03 11:45:53 -07002307 mService.addTimedJob(*mService.mTimedQueue, id(), checkBackAfter,
2308 [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002309 }
2310
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002311 // With kTolerance we are expecting these to execute before the next update.
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002312 if (healthStatusToReport != -1) {
2313 onHealthStatus(healthListener, healthStatusToReport);
2314 }
2315
2316 fsmStep();
2317}
2318
2319const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2320 if (mHealthPath.empty()) {
2321 resetHealthControl();
2322 return mHealthControl;
2323 }
2324 if (mHealthControl.pendingReads() < 0) {
2325 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2326 }
2327 if (mHealthControl.pendingReads() < 0) {
2328 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2329 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2330 << mHealthControl.logs() << ")";
2331 }
2332 return mHealthControl;
2333}
2334
2335void IncrementalService::DataLoaderStub::resetHealthControl() {
2336 mHealthControl = {};
2337}
2338
2339BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2340 auto result = kMaxBootClockTsUs;
2341
2342 const auto& control = initializeHealthControl();
2343 if (control.pendingReads() < 0) {
2344 return result;
2345 }
2346
2347 std::vector<incfs::ReadInfo> pendingReads;
2348 if (mService.mIncFs->waitForPendingReads(control, 0ms, &pendingReads) !=
2349 android::incfs::WaitResult::HaveData ||
2350 pendingReads.empty()) {
2351 return result;
2352 }
2353
2354 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
2355 << pendingReads.size() << ": " << pendingReads.front().bootClockTsUs;
2356
2357 for (auto&& pendingRead : pendingReads) {
2358 result = std::min(result, pendingRead.bootClockTsUs);
2359 }
2360 return result;
2361}
2362
2363void IncrementalService::DataLoaderStub::registerForPendingReads() {
2364 const auto pendingReadsFd = mHealthControl.pendingReads();
2365 if (pendingReadsFd < 0) {
2366 return;
2367 }
2368
2369 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2370
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002371 mService.mLooper->addFd(
2372 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2373 [](int, int, void* data) -> int {
2374 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002375 self->updateHealthStatus(/*baseline=*/true);
2376 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002377 },
2378 this);
2379 mService.mLooper->wake();
2380}
2381
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002382void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002383 const auto pendingReadsFd = mHealthControl.pendingReads();
2384 if (pendingReadsFd < 0) {
2385 return;
2386 }
2387
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002388 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2389
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002390 mService.mLooper->removeFd(pendingReadsFd);
2391 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002392}
2393
Songchun Fan2570ec02020-10-08 17:22:33 -07002394void IncrementalService::DataLoaderStub::setHealthListener(
2395 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
2396 std::lock_guard lock(mMutex);
2397 mHealthCheckParams = std::move(healthCheckParams);
2398 if (healthListener == nullptr) {
2399 // reset listener and params
2400 mHealthListener = {};
2401 } else {
2402 mHealthListener = *healthListener;
2403 }
2404}
2405
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002406void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002407 dprintf(fd, " dataLoader: {\n");
2408 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2409 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2410 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002411 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -07002412 dprintf(fd, " health: {\n");
2413 dprintf(fd, " path: %s\n", mHealthPath.c_str());
2414 dprintf(fd, " base: %lldmcs (%lld)\n",
2415 (long long)(elapsedMcs(mHealthBase.userTs, Clock::now())),
2416 (long long)mHealthBase.kernelTsUs);
2417 dprintf(fd, " blockedTimeoutMs: %d\n", int(mHealthCheckParams.blockedTimeoutMs));
2418 dprintf(fd, " unhealthyTimeoutMs: %d\n", int(mHealthCheckParams.unhealthyTimeoutMs));
2419 dprintf(fd, " unhealthyMonitoringMs: %d\n",
2420 int(mHealthCheckParams.unhealthyMonitoringMs));
2421 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002422 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002423 dprintf(fd, " dataLoaderParams: {\n");
2424 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2425 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2426 dprintf(fd, " className: %s\n", params.className.c_str());
2427 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2428 dprintf(fd, " }\n");
2429 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002430}
2431
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002432void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2433 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002434}
2435
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002436binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2437 bool enableReadLogs, int32_t* _aidl_return) {
2438 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2439 return binder::Status::ok();
2440}
2441
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002442FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2443 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2444}
2445
Songchun Fan3c82a302019-11-29 14:23:45 -08002446} // namespace android::incremental