blob: 2fcb005e6df8aa36c3732ccc99391746a40ac486 [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>
Jooyung Han66c567a2020-03-07 21:47:09 +090026#include <binder/Nullable.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080027#include <binder/Status.h>
28#include <sys/stat.h>
29#include <uuid/uuid.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080030
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070031#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080032#include <ctime>
Songchun Fan3c82a302019-11-29 14:23:45 -080033#include <iterator>
34#include <span>
Songchun Fan3c82a302019-11-29 14:23:45 -080035#include <type_traits>
36
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070037#include "IncrementalServiceValidation.h"
Songchun Fan3c82a302019-11-29 14:23:45 -080038#include "Metadata.pb.h"
39
40using namespace std::literals;
Songchun Fan1124fd32020-02-10 12:49:41 -080041namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080042
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070043constexpr const char* kDataUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070044constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070045
Songchun Fan3c82a302019-11-29 14:23:45 -080046namespace android::incremental {
47
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070048using content::pm::DataLoaderParamsParcel;
49using content::pm::FileSystemControlParcel;
50using content::pm::IDataLoader;
51
Songchun Fan3c82a302019-11-29 14:23:45 -080052namespace {
53
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070054using IncrementalFileSystemControlParcel = os::incremental::IncrementalFileSystemControlParcel;
Songchun Fan3c82a302019-11-29 14:23:45 -080055
56struct Constants {
57 static constexpr auto backing = "backing_store"sv;
58 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080059 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080060 static constexpr auto storagePrefix = "st"sv;
61 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
62 static constexpr auto infoMdName = ".info"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080063 static constexpr auto libDir = "lib"sv;
64 static constexpr auto libSuffix = ".so"sv;
65 static constexpr auto blockSize = 4096;
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -070066 static constexpr auto systemPackage = "android"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080067};
68
69static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070070 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080071 return c;
72}
73
74template <base::LogSeverity level = base::ERROR>
75bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
76 auto cstr = path::c_str(name);
77 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080078 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080079 PLOG(level) << "Can't create directory '" << name << '\'';
80 return false;
81 }
82 struct stat st;
83 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
84 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
85 return false;
86 }
87 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080088 if (::chmod(cstr, mode)) {
89 PLOG(level) << "Changing permission failed for '" << name << '\'';
90 return false;
91 }
92
Songchun Fan3c82a302019-11-29 14:23:45 -080093 return true;
94}
95
96static std::string toMountKey(std::string_view path) {
97 if (path.empty()) {
98 return "@none";
99 }
100 if (path == "/"sv) {
101 return "@root";
102 }
103 if (path::isAbsolute(path)) {
104 path.remove_prefix(1);
105 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700106 if (path.size() > 16) {
107 path = path.substr(0, 16);
108 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800109 std::string res(path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700110 std::replace_if(
111 res.begin(), res.end(), [](char c) { return c == '/' || c == '@'; }, '_');
112 return std::string(constants().mountKeyPrefix) += res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800113}
114
115static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
116 std::string_view path) {
117 auto mountKey = toMountKey(path);
118 const auto prefixSize = mountKey.size();
119 for (int counter = 0; counter < 1000;
120 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
121 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800122 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800123 return {mountKey, mountRoot};
124 }
125 }
126 return {};
127}
128
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700129template <class Map>
130typename Map::const_iterator findParentPath(const Map& map, std::string_view path) {
131 const auto nextIt = map.upper_bound(path);
132 if (nextIt == map.begin()) {
133 return map.end();
134 }
135 const auto suspectIt = std::prev(nextIt);
136 if (!path::startsWith(path, suspectIt->first)) {
137 return map.end();
138 }
139 return suspectIt;
140}
141
142static base::unique_fd dup(base::borrowed_fd fd) {
143 const auto res = fcntl(fd.get(), F_DUPFD_CLOEXEC, 0);
144 return base::unique_fd(res);
145}
146
Songchun Fan3c82a302019-11-29 14:23:45 -0800147template <class ProtoMessage, class Control>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700148static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, const Control& control,
Songchun Fan3c82a302019-11-29 14:23:45 -0800149 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800150 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800151 ProtoMessage message;
152 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
153}
154
155static bool isValidMountTarget(std::string_view path) {
156 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
157}
158
159std::string makeBindMdName() {
160 static constexpr auto uuidStringSize = 36;
161
162 uuid_t guid;
163 uuid_generate(guid);
164
165 std::string name;
166 const auto prefixSize = constants().mountpointMdPrefix.size();
167 name.reserve(prefixSize + uuidStringSize);
168
169 name = constants().mountpointMdPrefix;
170 name.resize(prefixSize + uuidStringSize);
171 uuid_unparse(guid, name.data() + prefixSize);
172
173 return name;
174}
175} // namespace
176
177IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700178 if (dataLoaderStub) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -0700179 dataLoaderStub->cleanupResources();
180 dataLoaderStub = {};
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700181 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700182 control.close();
Songchun Fan3c82a302019-11-29 14:23:45 -0800183 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
184 for (auto&& [target, _] : bindPoints) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700185 LOG(INFO) << " bind: " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800186 incrementalService.mVold->unmountIncFs(target);
187 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700188 LOG(INFO) << " root: " << root;
Songchun Fan3c82a302019-11-29 14:23:45 -0800189 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
190 cleanupFilesystem(root);
191}
192
193auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800194 std::string name;
195 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
196 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
197 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800198 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
199 constants().storagePrefix.data(), id, no);
200 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800201 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800202 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800203 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
204 } else if (err != EEXIST) {
205 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
206 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800207 }
208 }
209 nextStorageDirNo = 0;
210 return storages.end();
211}
212
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700213template <class Func>
214static auto makeCleanup(Func&& f) {
215 auto deleter = [f = std::move(f)](auto) { f(); };
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700216 // &f is a dangling pointer here, but we actually never use it as deleter moves it in.
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700217 return std::unique_ptr<Func, decltype(deleter)>(&f, std::move(deleter));
218}
219
220static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* dir) {
221 return {::opendir(dir), ::closedir};
222}
223
224static auto openDir(std::string_view dir) {
225 return openDir(path::c_str(dir));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800226}
227
228static int rmDirContent(const char* path) {
229 auto dir = openDir(path);
230 if (!dir) {
231 return -EINVAL;
232 }
233 while (auto entry = ::readdir(dir.get())) {
234 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
235 continue;
236 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700237 auto fullPath = base::StringPrintf("%s/%s", path, entry->d_name);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800238 if (entry->d_type == DT_DIR) {
239 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
240 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
241 return err;
242 }
243 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
244 PLOG(WARNING) << "Failed to rmdir " << fullPath;
245 return err;
246 }
247 } else {
248 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
249 PLOG(WARNING) << "Failed to delete " << fullPath;
250 return err;
251 }
252 }
253 }
254 return 0;
255}
256
Songchun Fan3c82a302019-11-29 14:23:45 -0800257void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800258 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800259 ::rmdir(path::join(root, constants().backing).c_str());
260 ::rmdir(path::join(root, constants().mount).c_str());
261 ::rmdir(path::c_str(root));
262}
263
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800264IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800265 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800266 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800267 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700268 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700269 mJni(sm.getJni()),
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700270 mLooper(sm.getLooper()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800271 mIncrementalDir(rootDir) {
272 if (!mVold) {
273 LOG(FATAL) << "Vold service is unavailable";
274 }
Songchun Fan68645c42020-02-27 15:57:35 -0800275 if (!mDataLoaderManager) {
276 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800277 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700278 if (!mAppOpsManager) {
279 LOG(FATAL) << "AppOpsManager is unavailable";
280 }
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700281 if (!mJni) {
282 LOG(FATAL) << "JNI is unavailable";
283 }
284 if (!mLooper) {
285 LOG(FATAL) << "Looper is unavailable";
286 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700287
288 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700289 mJobProcessor = std::thread([this]() {
290 mJni->initializeForCurrentThread();
291 runJobProcessing();
292 });
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700293 mCmdLooperThread = std::thread([this]() {
294 mJni->initializeForCurrentThread();
295 runCmdLooper();
296 });
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700297 mTimerThread = std::thread([this]() {
298 mJni->initializeForCurrentThread();
299 runTimers();
300 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700301
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700302 const auto mountedRootNames = adoptMountedInstances();
303 mountExistingImages(mountedRootNames);
Songchun Fan3c82a302019-11-29 14:23:45 -0800304}
305
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700306IncrementalService::~IncrementalService() {
307 {
308 std::lock_guard lock(mJobMutex);
309 mRunning = false;
310 }
311 mJobCondition.notify_all();
312 mJobProcessor.join();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700313 mTimerCondition.notify_all();
314 mTimerThread.join();
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700315 mCmdLooperThread.join();
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -0700316 mTimedJobs.clear();
317 // Ensure that mounts are destroyed while the service is still valid.
318 mBindsByPath.clear();
319 mMounts.clear();
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700320}
Songchun Fan3c82a302019-11-29 14:23:45 -0800321
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700322static const char* toString(IncrementalService::BindKind kind) {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800323 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800324 case IncrementalService::BindKind::Temporary:
325 return "Temporary";
326 case IncrementalService::BindKind::Permanent:
327 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800328 }
329}
330
331void IncrementalService::onDump(int fd) {
332 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
333 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
334
335 std::unique_lock l(mLock);
336
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700337 dprintf(fd, "Mounts (%d): {\n", int(mMounts.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800338 for (auto&& [id, ifs] : mMounts) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700339 const IncFsMount& mnt = *ifs;
340 dprintf(fd, " [%d]: {\n", id);
341 if (id != mnt.mountId) {
342 dprintf(fd, " reference to mountId: %d\n", mnt.mountId);
343 } else {
344 dprintf(fd, " mountId: %d\n", mnt.mountId);
345 dprintf(fd, " root: %s\n", mnt.root.c_str());
346 dprintf(fd, " nextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
347 if (mnt.dataLoaderStub) {
348 mnt.dataLoaderStub->onDump(fd);
349 } else {
350 dprintf(fd, " dataLoader: null\n");
351 }
352 dprintf(fd, " storages (%d): {\n", int(mnt.storages.size()));
353 for (auto&& [storageId, storage] : mnt.storages) {
354 dprintf(fd, " [%d] -> [%s]\n", storageId, storage.name.c_str());
355 }
356 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800357
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700358 dprintf(fd, " bindPoints (%d): {\n", int(mnt.bindPoints.size()));
359 for (auto&& [target, bind] : mnt.bindPoints) {
360 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
361 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
362 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
363 dprintf(fd, " kind: %s\n", toString(bind.kind));
364 }
365 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800366 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700367 dprintf(fd, " }\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800368 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700369 dprintf(fd, "}\n");
370 dprintf(fd, "Sorted binds (%d): {\n", int(mBindsByPath.size()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800371 for (auto&& [target, mountPairIt] : mBindsByPath) {
372 const auto& bind = mountPairIt->second;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700373 dprintf(fd, " [%s]->[%d]:\n", target.c_str(), bind.storage);
374 dprintf(fd, " savedFilename: %s\n", bind.savedFilename.c_str());
375 dprintf(fd, " sourceDir: %s\n", bind.sourceDir.c_str());
376 dprintf(fd, " kind: %s\n", toString(bind.kind));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800377 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700378 dprintf(fd, "}\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800379}
380
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700381void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800382 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700383 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800384 }
385
386 std::vector<IfsMountPtr> mounts;
387 {
388 std::lock_guard l(mLock);
389 mounts.reserve(mMounts.size());
390 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyyea96c1f2020-05-18 10:06:01 -0700391 if (ifs->mountId == id &&
392 ifs->dataLoaderStub->params().packageName == Constants::systemPackage) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800393 mounts.push_back(ifs);
394 }
395 }
396 }
397
Alex Buynytskyy69941662020-04-11 21:40:37 -0700398 if (mounts.empty()) {
399 return;
400 }
401
Songchun Fan3c82a302019-11-29 14:23:45 -0800402 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700403 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800404 for (auto&& ifs : mounts) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700405 ifs->dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -0800406 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800407 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800408}
409
410auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
411 for (;;) {
412 if (mNextId == kMaxStorageId) {
413 mNextId = 0;
414 }
415 auto id = ++mNextId;
416 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
417 if (inserted) {
418 return it;
419 }
420 }
421}
422
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700423StorageId IncrementalService::createStorage(std::string_view mountPoint,
424 content::pm::DataLoaderParamsParcel&& dataLoaderParams,
425 CreateOptions options,
426 const DataLoaderStatusListener& statusListener,
427 StorageHealthCheckParams&& healthCheckParams,
428 const StorageHealthListener& healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800429 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
430 if (!path::isAbsolute(mountPoint)) {
431 LOG(ERROR) << "path is not absolute: " << mountPoint;
432 return kInvalidStorageId;
433 }
434
435 auto mountNorm = path::normalize(mountPoint);
436 {
437 const auto id = findStorageId(mountNorm);
438 if (id != kInvalidStorageId) {
439 if (options & CreateOptions::OpenExisting) {
440 LOG(INFO) << "Opened existing storage " << id;
441 return id;
442 }
443 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
444 return kInvalidStorageId;
445 }
446 }
447
448 if (!(options & CreateOptions::CreateNew)) {
449 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
450 return kInvalidStorageId;
451 }
452
453 if (!path::isEmptyDir(mountNorm)) {
454 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
455 return kInvalidStorageId;
456 }
457 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
458 if (mountRoot.empty()) {
459 LOG(ERROR) << "Bad mount point";
460 return kInvalidStorageId;
461 }
462 // Make sure the code removes all crap it may create while still failing.
463 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
464 auto firstCleanupOnFailure =
465 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
466
467 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800468 const auto backing = path::join(mountRoot, constants().backing);
469 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800470 return kInvalidStorageId;
471 }
472
Songchun Fan3c82a302019-11-29 14:23:45 -0800473 IncFsMount::Control control;
474 {
475 std::lock_guard l(mMountOperationLock);
476 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800477
478 if (auto err = rmDirContent(backing.c_str())) {
479 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
480 return kInvalidStorageId;
481 }
482 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
483 return kInvalidStorageId;
484 }
485 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800486 if (!status.isOk()) {
487 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
488 return kInvalidStorageId;
489 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800490 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
491 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800492 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
493 return kInvalidStorageId;
494 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800495 int cmd = controlParcel.cmd.release().release();
496 int pendingReads = controlParcel.pendingReads.release().release();
497 int logs = controlParcel.log.release().release();
498 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800499 }
500
501 std::unique_lock l(mLock);
502 const auto mountIt = getStorageSlotLocked();
503 const auto mountId = mountIt->first;
504 l.unlock();
505
506 auto ifs =
507 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
508 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
509 // is the removal of the |ifs|.
510 firstCleanupOnFailure.release();
511
512 auto secondCleanup = [this, &l](auto itPtr) {
513 if (!l.owns_lock()) {
514 l.lock();
515 }
516 mMounts.erase(*itPtr);
517 };
518 auto secondCleanupOnFailure =
519 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
520
521 const auto storageIt = ifs->makeStorage(ifs->mountId);
522 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800523 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800524 return kInvalidStorageId;
525 }
526
527 {
528 metadata::Mount m;
529 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700530 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700531 m.mutable_loader()->set_allocated_package_name(&dataLoaderParams.packageName);
532 m.mutable_loader()->set_allocated_class_name(&dataLoaderParams.className);
533 m.mutable_loader()->set_allocated_arguments(&dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800534 const auto metadata = m.SerializeAsString();
535 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800536 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800537 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800538 if (auto err =
539 mIncFs->makeFile(ifs->control,
540 path::join(ifs->root, constants().mount,
541 constants().infoMdName),
542 0777, idFromMetadata(metadata),
543 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800544 LOG(ERROR) << "Saving mount metadata failed: " << -err;
545 return kInvalidStorageId;
546 }
547 }
548
549 const auto bk =
550 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800551 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
552 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800553 err < 0) {
554 LOG(ERROR) << "adding bind mount failed: " << -err;
555 return kInvalidStorageId;
556 }
557
558 // Done here as well, all data structures are in good state.
559 secondCleanupOnFailure.release();
560
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700561 auto dataLoaderStub = prepareDataLoader(*ifs, std::move(dataLoaderParams), &statusListener,
562 std::move(healthCheckParams), &healthListener);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700563 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800564
565 mountIt->second = std::move(ifs);
566 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700567
Alex Buynytskyyab65cb12020-04-17 10:01:47 -0700568 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->requestCreate()) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700569 // failed to create data loader
570 LOG(ERROR) << "initializeDataLoader() failed";
571 deleteStorage(dataLoaderStub->id());
572 return kInvalidStorageId;
573 }
574
Songchun Fan3c82a302019-11-29 14:23:45 -0800575 LOG(INFO) << "created storage " << mountId;
576 return mountId;
577}
578
579StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
580 StorageId linkedStorage,
581 IncrementalService::CreateOptions options) {
582 if (!isValidMountTarget(mountPoint)) {
583 LOG(ERROR) << "Mount point is invalid or missing";
584 return kInvalidStorageId;
585 }
586
587 std::unique_lock l(mLock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700588 auto ifs = getIfsLocked(linkedStorage);
Songchun Fan3c82a302019-11-29 14:23:45 -0800589 if (!ifs) {
590 LOG(ERROR) << "Ifs unavailable";
591 return kInvalidStorageId;
592 }
593
594 const auto mountIt = getStorageSlotLocked();
595 const auto storageId = mountIt->first;
596 const auto storageIt = ifs->makeStorage(storageId);
597 if (storageIt == ifs->storages.end()) {
598 LOG(ERROR) << "Can't create a new storage";
599 mMounts.erase(mountIt);
600 return kInvalidStorageId;
601 }
602
603 l.unlock();
604
605 const auto bk =
606 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800607 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
608 std::string(storageIt->second.name), path::normalize(mountPoint),
609 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800610 err < 0) {
611 LOG(ERROR) << "bindMount failed with error: " << err;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700612 (void)mIncFs->unlink(ifs->control, storageIt->second.name);
613 ifs->storages.erase(storageIt);
Songchun Fan3c82a302019-11-29 14:23:45 -0800614 return kInvalidStorageId;
615 }
616
617 mountIt->second = ifs;
618 return storageId;
619}
620
621IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
622 std::string_view path) const {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700623 return findParentPath(mBindsByPath, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800624}
625
626StorageId IncrementalService::findStorageId(std::string_view path) const {
627 std::lock_guard l(mLock);
628 auto it = findStorageLocked(path);
629 if (it == mBindsByPath.end()) {
630 return kInvalidStorageId;
631 }
632 return it->second->second.storage;
633}
634
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700635int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
636 const auto ifs = getIfs(storageId);
637 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700638 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700639 return -EINVAL;
640 }
641
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700642 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700643 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700644 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
645 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700646 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700647 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700648 return fromBinderStatus(status);
649 }
650 }
651
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700652 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
653 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
654 return fromBinderStatus(status);
655 }
656
657 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700658 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700659 }
660
661 return 0;
662}
663
664binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700665 os::incremental::IncrementalFileSystemControlParcel control;
666 control.cmd.reset(dup(ifs.control.cmd()));
667 control.pendingReads.reset(dup(ifs.control.pendingReads()));
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700668 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700669 if (logsFd >= 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700670 control.log.reset(dup(logsFd));
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700671 }
672
673 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700674 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700675}
676
Songchun Fan3c82a302019-11-29 14:23:45 -0800677void IncrementalService::deleteStorage(StorageId storageId) {
678 const auto ifs = getIfs(storageId);
679 if (!ifs) {
680 return;
681 }
682 deleteStorage(*ifs);
683}
684
685void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
686 std::unique_lock l(ifs.lock);
687 deleteStorageLocked(ifs, std::move(l));
688}
689
690void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
691 std::unique_lock<std::mutex>&& ifsLock) {
692 const auto storages = std::move(ifs.storages);
693 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
694 const auto bindPoints = ifs.bindPoints;
695 ifsLock.unlock();
696
697 std::lock_guard l(mLock);
698 for (auto&& [id, _] : storages) {
699 if (id != ifs.mountId) {
700 mMounts.erase(id);
701 }
702 }
703 for (auto&& [path, _] : bindPoints) {
704 mBindsByPath.erase(path);
705 }
706 mMounts.erase(ifs.mountId);
707}
708
709StorageId IncrementalService::openStorage(std::string_view pathInMount) {
710 if (!path::isAbsolute(pathInMount)) {
711 return kInvalidStorageId;
712 }
713
714 return findStorageId(path::normalize(pathInMount));
715}
716
Songchun Fan3c82a302019-11-29 14:23:45 -0800717IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
718 std::lock_guard l(mLock);
719 return getIfsLocked(storage);
720}
721
722const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
723 auto it = mMounts.find(storage);
724 if (it == mMounts.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700725 static const base::NoDestructor<IfsMountPtr> kEmpty{};
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700726 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800727 }
728 return it->second;
729}
730
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800731int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
732 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800733 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700734 LOG(ERROR) << __func__ << ": not a valid bind target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800735 return -EINVAL;
736 }
737
738 const auto ifs = getIfs(storage);
739 if (!ifs) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700740 LOG(ERROR) << __func__ << ": no ifs object for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800741 return -EINVAL;
742 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800743
Songchun Fan3c82a302019-11-29 14:23:45 -0800744 std::unique_lock l(ifs->lock);
745 const auto storageInfo = ifs->storages.find(storage);
746 if (storageInfo == ifs->storages.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700747 LOG(ERROR) << "no storage";
Songchun Fan3c82a302019-11-29 14:23:45 -0800748 return -EINVAL;
749 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700750 std::string normSource = normalizePathToStorageLocked(*ifs, storageInfo, source);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700751 if (normSource.empty()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700752 LOG(ERROR) << "invalid source path";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700753 return -EINVAL;
754 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800755 l.unlock();
756 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800757 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
758 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800759}
760
761int IncrementalService::unbind(StorageId storage, std::string_view target) {
762 if (!path::isAbsolute(target)) {
763 return -EINVAL;
764 }
765
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -0700766 LOG(INFO) << "Removing bind point " << target << " for storage " << storage;
Songchun Fan3c82a302019-11-29 14:23:45 -0800767
768 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
769 // otherwise there's a chance to unmount something completely unrelated
770 const auto norm = path::normalize(target);
771 std::unique_lock l(mLock);
772 const auto storageIt = mBindsByPath.find(norm);
773 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
774 return -EINVAL;
775 }
776 const auto bindIt = storageIt->second;
777 const auto storageId = bindIt->second.storage;
778 const auto ifs = getIfsLocked(storageId);
779 if (!ifs) {
780 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
781 << " is missing";
782 return -EFAULT;
783 }
784 mBindsByPath.erase(storageIt);
785 l.unlock();
786
787 mVold->unmountIncFs(bindIt->first);
788 std::unique_lock l2(ifs->lock);
789 if (ifs->bindPoints.size() <= 1) {
790 ifs->bindPoints.clear();
Alex Buynytskyy64067b22020-04-25 15:56:52 -0700791 deleteStorageLocked(*ifs, std::move(l2));
Songchun Fan3c82a302019-11-29 14:23:45 -0800792 } else {
793 const std::string savedFile = std::move(bindIt->second.savedFilename);
794 ifs->bindPoints.erase(bindIt);
795 l2.unlock();
796 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800797 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800798 }
799 }
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -0700800
Songchun Fan3c82a302019-11-29 14:23:45 -0800801 return 0;
802}
803
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700804std::string IncrementalService::normalizePathToStorageLocked(
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700805 const IncFsMount& incfs, IncFsMount::StorageMap::const_iterator storageIt,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700806 std::string_view path) const {
807 if (!path::isAbsolute(path)) {
808 return path::normalize(path::join(storageIt->second.name, path));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700809 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700810 auto normPath = path::normalize(path);
811 if (path::startsWith(normPath, storageIt->second.name)) {
812 return normPath;
813 }
814 // not that easy: need to find if any of the bind points match
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700815 const auto bindIt = findParentPath(incfs.bindPoints, normPath);
816 if (bindIt == incfs.bindPoints.end()) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700817 return {};
818 }
819 return path::join(bindIt->second.sourceDir, path::relativize(bindIt->first, normPath));
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700820}
821
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700822std::string IncrementalService::normalizePathToStorage(const IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700823 std::string_view path) const {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700824 std::unique_lock l(ifs.lock);
825 const auto storageInfo = ifs.storages.find(storage);
826 if (storageInfo == ifs.storages.end()) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800827 return {};
828 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700829 return normalizePathToStorageLocked(ifs, storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800830}
831
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800832int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
833 incfs::NewFileParams params) {
834 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700835 std::string normPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800836 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700837 LOG(ERROR) << "Internal error: storageId " << storage
838 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800839 return -EINVAL;
840 }
841 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800842 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700843 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800844 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800845 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800846 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800847 }
848 return -EINVAL;
849}
850
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800851int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800852 if (auto ifs = getIfs(storageId)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700853 std::string normPath = normalizePathToStorage(*ifs, storageId, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800854 if (normPath.empty()) {
855 return -EINVAL;
856 }
857 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800858 }
859 return -EINVAL;
860}
861
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800862int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800863 const auto ifs = getIfs(storageId);
864 if (!ifs) {
865 return -EINVAL;
866 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700867 return makeDirs(*ifs, storageId, path, mode);
868}
869
870int IncrementalService::makeDirs(const IncFsMount& ifs, StorageId storageId, std::string_view path,
871 int mode) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800872 std::string normPath = normalizePathToStorage(ifs, storageId, path);
873 if (normPath.empty()) {
874 return -EINVAL;
875 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700876 return mIncFs->makeDirs(ifs.control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800877}
878
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800879int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
880 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700881 std::unique_lock l(mLock);
882 auto ifsSrc = getIfsLocked(sourceStorageId);
883 if (!ifsSrc) {
884 return -EINVAL;
Songchun Fan3c82a302019-11-29 14:23:45 -0800885 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700886 if (sourceStorageId != destStorageId && getIfsLocked(destStorageId) != ifsSrc) {
887 return -EINVAL;
888 }
889 l.unlock();
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700890 std::string normOldPath = normalizePathToStorage(*ifsSrc, sourceStorageId, oldPath);
891 std::string normNewPath = normalizePathToStorage(*ifsSrc, destStorageId, newPath);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700892 if (normOldPath.empty() || normNewPath.empty()) {
893 LOG(ERROR) << "Invalid paths in link(): " << normOldPath << " | " << normNewPath;
894 return -EINVAL;
895 }
896 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800897}
898
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800899int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800900 if (auto ifs = getIfs(storage)) {
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700901 std::string normOldPath = normalizePathToStorage(*ifs, storage, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800902 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800903 }
904 return -EINVAL;
905}
906
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800907int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
908 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800909 std::string&& target, BindKind kind,
910 std::unique_lock<std::mutex>& mainLock) {
911 if (!isValidMountTarget(target)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700912 LOG(ERROR) << __func__ << ": invalid mount target " << target;
Songchun Fan3c82a302019-11-29 14:23:45 -0800913 return -EINVAL;
914 }
915
916 std::string mdFileName;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700917 std::string metadataFullPath;
Songchun Fan3c82a302019-11-29 14:23:45 -0800918 if (kind != BindKind::Temporary) {
919 metadata::BindPoint bp;
920 bp.set_storage_id(storage);
921 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800922 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800923 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800924 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800925 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800926 mdFileName = makeBindMdName();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700927 metadataFullPath = path::join(ifs.root, constants().mount, mdFileName);
928 auto node = mIncFs->makeFile(ifs.control, metadataFullPath, 0444, idFromMetadata(metadata),
929 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800930 if (node) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700931 LOG(ERROR) << __func__ << ": couldn't create a mount node " << mdFileName;
Songchun Fan3c82a302019-11-29 14:23:45 -0800932 return int(node);
933 }
934 }
935
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700936 const auto res = addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
937 std::move(target), kind, mainLock);
938 if (res) {
939 mIncFs->unlink(ifs.control, metadataFullPath);
940 }
941 return res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800942}
943
944int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800945 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800946 std::string&& target, BindKind kind,
947 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800948 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800949 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800950 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800951 if (!status.isOk()) {
952 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
953 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
954 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
955 : status.serviceSpecificErrorCode() == 0
956 ? -EFAULT
957 : status.serviceSpecificErrorCode()
958 : -EIO;
959 }
960 }
961
962 if (!mainLock.owns_lock()) {
963 mainLock.lock();
964 }
965 std::lock_guard l(ifs.lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700966 addBindMountRecordLocked(ifs, storage, std::move(metadataName), std::move(source),
967 std::move(target), kind);
968 return 0;
969}
970
971void IncrementalService::addBindMountRecordLocked(IncFsMount& ifs, StorageId storage,
972 std::string&& metadataName, std::string&& source,
973 std::string&& target, BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800974 const auto [it, _] =
975 ifs.bindPoints.insert_or_assign(target,
976 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800977 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800978 mBindsByPath[std::move(target)] = it;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700979}
980
981RawMetadata IncrementalService::getMetadata(StorageId storage, std::string_view path) const {
982 const auto ifs = getIfs(storage);
983 if (!ifs) {
984 return {};
985 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700986 const auto normPath = normalizePathToStorage(*ifs, storage, path);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700987 if (normPath.empty()) {
988 return {};
989 }
990 return mIncFs->getMetadata(ifs->control, normPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800991}
992
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800993RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800994 const auto ifs = getIfs(storage);
995 if (!ifs) {
996 return {};
997 }
998 return mIncFs->getMetadata(ifs->control, node);
999}
1000
Songchun Fan3c82a302019-11-29 14:23:45 -08001001bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001002 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001003 {
1004 std::unique_lock l(mLock);
1005 const auto& ifs = getIfsLocked(storage);
1006 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001007 return false;
1008 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001009 dataLoaderStub = ifs->dataLoaderStub;
1010 if (!dataLoaderStub) {
1011 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001012 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001013 }
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001014 dataLoaderStub->requestStart();
1015 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001016}
1017
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001018std::unordered_set<std::string_view> IncrementalService::adoptMountedInstances() {
1019 std::unordered_set<std::string_view> mountedRootNames;
1020 mIncFs->listExistingMounts([this, &mountedRootNames](auto root, auto backingDir, auto binds) {
1021 LOG(INFO) << "Existing mount: " << backingDir << "->" << root;
1022 for (auto [source, target] : binds) {
1023 LOG(INFO) << " bind: '" << source << "'->'" << target << "'";
1024 LOG(INFO) << " " << path::join(root, source);
1025 }
1026
1027 // Ensure it's a kind of a mount that's managed by IncrementalService
1028 if (path::basename(root) != constants().mount ||
1029 path::basename(backingDir) != constants().backing) {
1030 return;
1031 }
1032 const auto expectedRoot = path::dirname(root);
1033 if (path::dirname(backingDir) != expectedRoot) {
1034 return;
1035 }
1036 if (path::dirname(expectedRoot) != mIncrementalDir) {
1037 return;
1038 }
1039 if (!path::basename(expectedRoot).starts_with(constants().mountKeyPrefix)) {
1040 return;
1041 }
1042
1043 LOG(INFO) << "Looks like an IncrementalService-owned: " << expectedRoot;
1044
1045 // make sure we clean up the mount if it happens to be a bad one.
1046 // Note: unmounting needs to run first, so the cleanup object is created _last_.
1047 auto cleanupFiles = makeCleanup([&]() {
1048 LOG(INFO) << "Failed to adopt existing mount, deleting files: " << expectedRoot;
1049 IncFsMount::cleanupFilesystem(expectedRoot);
1050 });
1051 auto cleanupMounts = makeCleanup([&]() {
1052 LOG(INFO) << "Failed to adopt existing mount, cleaning up: " << expectedRoot;
1053 for (auto&& [_, target] : binds) {
1054 mVold->unmountIncFs(std::string(target));
1055 }
1056 mVold->unmountIncFs(std::string(root));
1057 });
1058
1059 auto control = mIncFs->openMount(root);
1060 if (!control) {
1061 LOG(INFO) << "failed to open mount " << root;
1062 return;
1063 }
1064
1065 auto mountRecord =
1066 parseFromIncfs<metadata::Mount>(mIncFs.get(), control,
1067 path::join(root, constants().infoMdName));
1068 if (!mountRecord.has_loader() || !mountRecord.has_storage()) {
1069 LOG(ERROR) << "Bad mount metadata in mount at " << expectedRoot;
1070 return;
1071 }
1072
1073 auto mountId = mountRecord.storage().id();
1074 mNextId = std::max(mNextId, mountId + 1);
1075
1076 DataLoaderParamsParcel dataLoaderParams;
1077 {
1078 const auto& loader = mountRecord.loader();
1079 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
1080 dataLoaderParams.packageName = loader.package_name();
1081 dataLoaderParams.className = loader.class_name();
1082 dataLoaderParams.arguments = loader.arguments();
1083 }
1084
1085 auto ifs = std::make_shared<IncFsMount>(std::string(expectedRoot), mountId,
1086 std::move(control), *this);
1087 cleanupFiles.release(); // ifs will take care of that now
1088
1089 std::vector<std::pair<std::string, metadata::BindPoint>> permanentBindPoints;
1090 auto d = openDir(root);
1091 while (auto e = ::readdir(d.get())) {
1092 if (e->d_type == DT_REG) {
1093 auto name = std::string_view(e->d_name);
1094 if (name.starts_with(constants().mountpointMdPrefix)) {
1095 permanentBindPoints
1096 .emplace_back(name,
1097 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1098 ifs->control,
1099 path::join(root,
1100 name)));
1101 if (permanentBindPoints.back().second.dest_path().empty() ||
1102 permanentBindPoints.back().second.source_subdir().empty()) {
1103 permanentBindPoints.pop_back();
1104 mIncFs->unlink(ifs->control, path::join(root, name));
1105 } else {
1106 LOG(INFO) << "Permanent bind record: '"
1107 << permanentBindPoints.back().second.source_subdir() << "'->'"
1108 << permanentBindPoints.back().second.dest_path() << "'";
1109 }
1110 }
1111 } else if (e->d_type == DT_DIR) {
1112 if (e->d_name == "."sv || e->d_name == ".."sv) {
1113 continue;
1114 }
1115 auto name = std::string_view(e->d_name);
1116 if (name.starts_with(constants().storagePrefix)) {
1117 int storageId;
1118 const auto res =
1119 std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1120 name.data() + name.size(), storageId);
1121 if (res.ec != std::errc{} || *res.ptr != '_') {
1122 LOG(WARNING) << "Ignoring storage with invalid name '" << name
1123 << "' for mount " << expectedRoot;
1124 continue;
1125 }
1126 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
1127 if (!inserted) {
1128 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
1129 << " for mount " << expectedRoot;
1130 continue;
1131 }
1132 ifs->storages.insert_or_assign(storageId,
1133 IncFsMount::Storage{path::join(root, name)});
1134 mNextId = std::max(mNextId, storageId + 1);
1135 }
1136 }
1137 }
1138
1139 if (ifs->storages.empty()) {
1140 LOG(WARNING) << "No valid storages in mount " << root;
1141 return;
1142 }
1143
1144 // now match the mounted directories with what we expect to have in the metadata
1145 {
1146 std::unique_lock l(mLock, std::defer_lock);
1147 for (auto&& [metadataFile, bindRecord] : permanentBindPoints) {
1148 auto mountedIt = std::find_if(binds.begin(), binds.end(),
1149 [&, bindRecord = bindRecord](auto&& bind) {
1150 return bind.second == bindRecord.dest_path() &&
1151 path::join(root, bind.first) ==
1152 bindRecord.source_subdir();
1153 });
1154 if (mountedIt != binds.end()) {
1155 LOG(INFO) << "Matched permanent bound " << bindRecord.source_subdir()
1156 << " to mount " << mountedIt->first;
1157 addBindMountRecordLocked(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1158 std::move(*bindRecord.mutable_source_subdir()),
1159 std::move(*bindRecord.mutable_dest_path()),
1160 BindKind::Permanent);
1161 if (mountedIt != binds.end() - 1) {
1162 std::iter_swap(mountedIt, binds.end() - 1);
1163 }
1164 binds = binds.first(binds.size() - 1);
1165 } else {
1166 LOG(INFO) << "Didn't match permanent bound " << bindRecord.source_subdir()
1167 << ", mounting";
1168 // doesn't exist - try mounting back
1169 if (addBindMountWithMd(*ifs, bindRecord.storage_id(), std::move(metadataFile),
1170 std::move(*bindRecord.mutable_source_subdir()),
1171 std::move(*bindRecord.mutable_dest_path()),
1172 BindKind::Permanent, l)) {
1173 mIncFs->unlink(ifs->control, metadataFile);
1174 }
1175 }
1176 }
1177 }
1178
1179 // if anything stays in |binds| those are probably temporary binds; system restarted since
1180 // they were mounted - so let's unmount them all.
1181 for (auto&& [source, target] : binds) {
1182 if (source.empty()) {
1183 continue;
1184 }
1185 mVold->unmountIncFs(std::string(target));
1186 }
1187 cleanupMounts.release(); // ifs now manages everything
1188
1189 if (ifs->bindPoints.empty()) {
1190 LOG(WARNING) << "No valid bind points for mount " << expectedRoot;
1191 deleteStorage(*ifs);
1192 return;
1193 }
1194
1195 prepareDataLoaderLocked(*ifs, std::move(dataLoaderParams));
1196 CHECK(ifs->dataLoaderStub);
1197
1198 mountedRootNames.insert(path::basename(ifs->root));
1199
1200 // not locking here at all: we're still in the constructor, no other calls can happen
1201 mMounts[ifs->mountId] = std::move(ifs);
1202 });
1203
1204 return mountedRootNames;
1205}
1206
1207void IncrementalService::mountExistingImages(
1208 const std::unordered_set<std::string_view>& mountedRootNames) {
1209 auto dir = openDir(mIncrementalDir);
1210 if (!dir) {
1211 PLOG(WARNING) << "Couldn't open the root incremental dir " << mIncrementalDir;
1212 return;
1213 }
1214 while (auto entry = ::readdir(dir.get())) {
1215 if (entry->d_type != DT_DIR) {
1216 continue;
1217 }
1218 std::string_view name = entry->d_name;
1219 if (!name.starts_with(constants().mountKeyPrefix)) {
1220 continue;
1221 }
1222 if (mountedRootNames.find(name) != mountedRootNames.end()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001223 continue;
1224 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001225 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001226 if (!mountExistingImage(root)) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001227 IncFsMount::cleanupFilesystem(root);
Songchun Fan3c82a302019-11-29 14:23:45 -08001228 }
1229 }
1230}
1231
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001232bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001233 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001234 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001235
Songchun Fan3c82a302019-11-29 14:23:45 -08001236 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001237 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001238 if (!status.isOk()) {
1239 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1240 return false;
1241 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001242
1243 int cmd = controlParcel.cmd.release().release();
1244 int pendingReads = controlParcel.pendingReads.release().release();
1245 int logs = controlParcel.log.release().release();
1246 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001247
1248 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1249
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001250 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1251 path::join(mountTarget, constants().infoMdName));
1252 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001253 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1254 return false;
1255 }
1256
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001257 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001258 mNextId = std::max(mNextId, ifs->mountId + 1);
1259
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001260 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001261 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001262 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001263 const auto& loader = mount.loader();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001264 dataLoaderParams.type = (content::pm::DataLoaderType)loader.type();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001265 dataLoaderParams.packageName = loader.package_name();
1266 dataLoaderParams.className = loader.class_name();
1267 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001268 }
1269
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001270 prepareDataLoader(*ifs, std::move(dataLoaderParams));
Alex Buynytskyy69941662020-04-11 21:40:37 -07001271 CHECK(ifs->dataLoaderStub);
1272
Songchun Fan3c82a302019-11-29 14:23:45 -08001273 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001274 auto d = openDir(mountTarget);
Songchun Fan3c82a302019-11-29 14:23:45 -08001275 while (auto e = ::readdir(d.get())) {
1276 if (e->d_type == DT_REG) {
1277 auto name = std::string_view(e->d_name);
1278 if (name.starts_with(constants().mountpointMdPrefix)) {
1279 bindPoints.emplace_back(name,
1280 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1281 ifs->control,
1282 path::join(mountTarget,
1283 name)));
1284 if (bindPoints.back().second.dest_path().empty() ||
1285 bindPoints.back().second.source_subdir().empty()) {
1286 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001287 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001288 }
1289 }
1290 } else if (e->d_type == DT_DIR) {
1291 if (e->d_name == "."sv || e->d_name == ".."sv) {
1292 continue;
1293 }
1294 auto name = std::string_view(e->d_name);
1295 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001296 int storageId;
1297 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1298 name.data() + name.size(), storageId);
1299 if (res.ec != std::errc{} || *res.ptr != '_') {
1300 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1301 << root;
1302 continue;
1303 }
1304 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001305 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001306 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001307 << " for mount " << root;
1308 continue;
1309 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001310 ifs->storages.insert_or_assign(storageId,
1311 IncFsMount::Storage{
1312 path::join(root, constants().mount, name)});
1313 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001314 }
1315 }
1316 }
1317
1318 if (ifs->storages.empty()) {
1319 LOG(WARNING) << "No valid storages in mount " << root;
1320 return false;
1321 }
1322
1323 int bindCount = 0;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001324 {
Songchun Fan3c82a302019-11-29 14:23:45 -08001325 std::unique_lock l(mLock, std::defer_lock);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001326 for (auto&& bp : bindPoints) {
1327 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1328 std::move(*bp.second.mutable_source_subdir()),
1329 std::move(*bp.second.mutable_dest_path()),
1330 BindKind::Permanent, l);
1331 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001332 }
1333
1334 if (bindCount == 0) {
1335 LOG(WARNING) << "No valid bind points for mount " << root;
1336 deleteStorage(*ifs);
1337 return false;
1338 }
1339
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001340 // not locking here at all: we're still in the constructor, no other calls can happen
Songchun Fan3c82a302019-11-29 14:23:45 -08001341 mMounts[ifs->mountId] = std::move(ifs);
1342 return true;
1343}
1344
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001345void IncrementalService::runCmdLooper() {
1346 constexpr auto kTimeoutMsecs = 1000;
1347 while (mRunning.load(std::memory_order_relaxed)) {
1348 mLooper->pollAll(kTimeoutMsecs);
1349 }
1350}
1351
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001352IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001353 IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001354 const DataLoaderStatusListener* statusListener,
1355 StorageHealthCheckParams&& healthCheckParams, const StorageHealthListener* healthListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001356 std::unique_lock l(ifs.lock);
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001357 prepareDataLoaderLocked(ifs, std::move(params), statusListener, std::move(healthCheckParams),
1358 healthListener);
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001359 return ifs.dataLoaderStub;
1360}
1361
1362void IncrementalService::prepareDataLoaderLocked(IncFsMount& ifs, DataLoaderParamsParcel&& params,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001363 const DataLoaderStatusListener* statusListener,
1364 StorageHealthCheckParams&& healthCheckParams,
1365 const StorageHealthListener* healthListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001366 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001367 LOG(INFO) << "Skipped data loader preparation because it already exists";
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001368 return;
Songchun Fan3c82a302019-11-29 14:23:45 -08001369 }
1370
Songchun Fan3c82a302019-11-29 14:23:45 -08001371 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001372 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001373 fsControlParcel.incremental->cmd.reset(dup(ifs.control.cmd()));
1374 fsControlParcel.incremental->pendingReads.reset(dup(ifs.control.pendingReads()));
1375 fsControlParcel.incremental->log.reset(dup(ifs.control.logs()));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001376 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001377
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001378 ifs.dataLoaderStub =
1379 new DataLoaderStub(*this, ifs.mountId, std::move(params), std::move(fsControlParcel),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001380 statusListener, std::move(healthCheckParams), healthListener,
1381 path::join(ifs.root, constants().mount));
Songchun Fan3c82a302019-11-29 14:23:45 -08001382}
1383
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001384template <class Duration>
1385static long elapsedMcs(Duration start, Duration end) {
1386 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1387}
1388
1389// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001390bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1391 std::string_view libDirRelativePath,
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001392 std::string_view abi, bool extractNativeLibs) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001393 auto start = Clock::now();
1394
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001395 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001396 if (!ifs) {
1397 LOG(ERROR) << "Invalid storage " << storage;
1398 return false;
1399 }
1400
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001401 // First prepare target directories if they don't exist yet
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001402 if (auto res = makeDirs(*ifs, storage, libDirRelativePath, 0755)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001403 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1404 << " errno: " << res;
1405 return false;
1406 }
1407
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001408 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001409 ZipArchiveHandle zipFileHandle;
1410 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001411 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1412 return false;
1413 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001414
1415 // Need a shared pointer: will be passing it into all unpacking jobs.
1416 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001417 void* cookie = nullptr;
1418 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001419 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001420 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1421 return false;
1422 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001423 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001424 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1425
1426 auto openZipTs = Clock::now();
1427
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001428 std::vector<Job> jobQueue;
1429 ZipEntry entry;
1430 std::string_view fileName;
1431 while (!Next(cookie, &entry, &fileName)) {
1432 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001433 continue;
1434 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001435
Songchun Fan14f6c3c2020-05-21 18:19:07 -07001436 if (!extractNativeLibs) {
1437 // ensure the file is properly aligned and unpacked
1438 if (entry.method != kCompressStored) {
1439 LOG(WARNING) << "Library " << fileName << " must be uncompressed to mmap it";
1440 return false;
1441 }
1442 if ((entry.offset & (constants().blockSize - 1)) != 0) {
1443 LOG(WARNING) << "Library " << fileName
1444 << " must be page-aligned to mmap it, offset = 0x" << std::hex
1445 << entry.offset;
1446 return false;
1447 }
1448 continue;
1449 }
1450
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001451 auto startFileTs = Clock::now();
1452
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001453 const auto libName = path::basename(fileName);
Yurii Zubrytskyi510037b2020-04-22 15:46:21 -07001454 auto targetLibPath = path::join(libDirRelativePath, libName);
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -07001455 const auto targetLibPathAbsolute = normalizePathToStorage(*ifs, storage, targetLibPath);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001456 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001457 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001458 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001459 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1460 << "; skipping extraction, spent "
1461 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1462 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001463 continue;
1464 }
1465
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001466 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001467 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001468 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001469 .signature = {},
1470 // Metadata of the new lib file is its relative path
1471 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1472 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001473 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001474 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1475 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001476 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001477 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001478 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001479 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001480
1481 auto makeFileTs = Clock::now();
1482
Songchun Fanafaf6e92020-03-18 14:12:20 -07001483 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001484 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001485 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001486 LOG(INFO) << "incfs: Extracted " << libName
1487 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001488 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001489 continue;
1490 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001491
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001492 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1493 libFileId, libPath = std::move(targetLibPath),
1494 makeFileTs]() mutable {
1495 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001496 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001497
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001498 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001499 auto prepareJobTs = Clock::now();
1500 LOG(INFO) << "incfs: Processed " << libName << ": "
1501 << elapsedMcs(startFileTs, prepareJobTs)
1502 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1503 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001504 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001505 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001506
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001507 auto processedTs = Clock::now();
1508
1509 if (!jobQueue.empty()) {
1510 {
1511 std::lock_guard lock(mJobMutex);
1512 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001513 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001514 if (existingJobs.empty()) {
1515 existingJobs = std::move(jobQueue);
1516 } else {
1517 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1518 std::move_iterator(jobQueue.end()));
1519 }
1520 }
1521 }
1522 mJobCondition.notify_all();
1523 }
1524
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001525 if (perfLoggingEnabled()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001526 auto end = Clock::now();
1527 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1528 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1529 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001530 << " make files: " << elapsedMcs(openZipTs, processedTs)
1531 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001532 }
1533
1534 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001535}
1536
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001537void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1538 ZipEntry& entry, const incfs::FileId& libFileId,
1539 std::string_view targetLibPath,
1540 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001541 if (!ifs) {
1542 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1543 return;
1544 }
1545
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001546 auto libName = path::basename(targetLibPath);
1547 auto startedTs = Clock::now();
1548
1549 // Write extracted data to new file
1550 // NOTE: don't zero-initialize memory, it may take a while for nothing
1551 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1552 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1553 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1554 return;
1555 }
1556
1557 auto extractFileTs = Clock::now();
1558
1559 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1560 if (!writeFd.ok()) {
1561 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1562 return;
1563 }
1564
1565 auto openFileTs = Clock::now();
1566 const int numBlocks =
1567 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1568 std::vector<IncFsDataBlock> instructions(numBlocks);
1569 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1570 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001571 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001572 instructions[i] = IncFsDataBlock{
1573 .fileFd = writeFd.get(),
1574 .pageIndex = static_cast<IncFsBlockIndex>(i),
1575 .compression = INCFS_COMPRESSION_KIND_NONE,
1576 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001577 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001578 .data = reinterpret_cast<const char*>(remainingData.data()),
1579 };
1580 remainingData = remainingData.subspan(blockSize);
1581 }
1582 auto prepareInstsTs = Clock::now();
1583
1584 size_t res = mIncFs->writeBlocks(instructions);
1585 if (res != instructions.size()) {
1586 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1587 return;
1588 }
1589
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001590 if (perfLoggingEnabled()) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001591 auto endFileTs = Clock::now();
1592 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1593 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1594 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1595 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1596 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1597 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1598 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1599 }
1600}
1601
1602bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001603 struct WaitPrinter {
1604 const Clock::time_point startTs = Clock::now();
1605 ~WaitPrinter() noexcept {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001606 if (perfLoggingEnabled()) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001607 const auto endTs = Clock::now();
1608 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1609 << elapsedMcs(startTs, endTs) << "mcs";
1610 }
1611 }
1612 } waitPrinter;
1613
1614 MountId mount;
1615 {
1616 auto ifs = getIfs(storage);
1617 if (!ifs) {
1618 return true;
1619 }
1620 mount = ifs->mountId;
1621 }
1622
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001623 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001624 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001625 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001626 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001627 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001628 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001629}
1630
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001631bool IncrementalService::perfLoggingEnabled() {
1632 static const bool enabled = base::GetBoolProperty("incremental.perflogging", false);
1633 return enabled;
1634}
1635
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001636void IncrementalService::runJobProcessing() {
1637 for (;;) {
1638 std::unique_lock lock(mJobMutex);
1639 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1640 if (!mRunning) {
1641 return;
1642 }
1643
1644 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001645 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001646 auto queue = std::move(it->second);
1647 mJobQueue.erase(it);
1648 lock.unlock();
1649
1650 for (auto&& job : queue) {
1651 job();
1652 }
1653
1654 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001655 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001656 lock.unlock();
1657 mJobCondition.notify_all();
1658 }
1659}
1660
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001661void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001662 sp<IAppOpsCallback> listener;
1663 {
1664 std::unique_lock lock{mCallbacksLock};
1665 auto& cb = mCallbackRegistered[packageName];
1666 if (cb) {
1667 return;
1668 }
1669 cb = new AppOpsListener(*this, packageName);
1670 listener = cb;
1671 }
1672
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001673 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1674 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001675}
1676
1677bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1678 sp<IAppOpsCallback> listener;
1679 {
1680 std::unique_lock lock{mCallbacksLock};
1681 auto found = mCallbackRegistered.find(packageName);
1682 if (found == mCallbackRegistered.end()) {
1683 return false;
1684 }
1685 listener = found->second;
1686 mCallbackRegistered.erase(found);
1687 }
1688
1689 mAppOpsManager->stopWatchingMode(listener);
1690 return true;
1691}
1692
1693void IncrementalService::onAppOpChanged(const std::string& packageName) {
1694 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001695 return;
1696 }
1697
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001698 std::vector<IfsMountPtr> affected;
1699 {
1700 std::lock_guard l(mLock);
1701 affected.reserve(mMounts.size());
1702 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001703 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001704 affected.push_back(ifs);
1705 }
1706 }
1707 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001708 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001709 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001710 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001711}
1712
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001713void IncrementalService::addTimedJob(MountId id, TimePoint when, Job what) {
1714 if (id == kInvalidStorageId) {
1715 return;
1716 }
1717 {
1718 std::unique_lock lock(mTimerMutex);
1719 mTimedJobs.insert(TimedJob{id, when, std::move(what)});
1720 }
1721 mTimerCondition.notify_all();
1722}
1723
1724void IncrementalService::removeTimedJobs(MountId id) {
1725 if (id == kInvalidStorageId) {
1726 return;
1727 }
1728 {
1729 std::unique_lock lock(mTimerMutex);
1730 std::erase_if(mTimedJobs, [id](auto&& item) { return item.id == id; });
1731 }
1732}
1733
1734void IncrementalService::runTimers() {
1735 static constexpr TimePoint kInfinityTs{Clock::duration::max()};
1736 TimePoint nextTaskTs = kInfinityTs;
1737 for (;;) {
1738 std::unique_lock lock(mTimerMutex);
1739 mTimerCondition.wait_until(lock, nextTaskTs, [this]() {
1740 auto now = Clock::now();
1741 return !mRunning || (!mTimedJobs.empty() && mTimedJobs.begin()->when <= now);
1742 });
1743 if (!mRunning) {
1744 return;
1745 }
1746
1747 auto now = Clock::now();
1748 auto it = mTimedJobs.begin();
1749 // Always acquire begin(). We can't use it after unlock as mTimedJobs can change.
1750 for (; it != mTimedJobs.end() && it->when <= now; it = mTimedJobs.begin()) {
1751 auto job = it->what;
1752 mTimedJobs.erase(it);
1753
1754 lock.unlock();
1755 job();
1756 lock.lock();
1757 }
1758 nextTaskTs = it != mTimedJobs.end() ? it->when : kInfinityTs;
1759 }
1760}
1761
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001762IncrementalService::DataLoaderStub::DataLoaderStub(IncrementalService& service, MountId id,
1763 DataLoaderParamsParcel&& params,
1764 FileSystemControlParcel&& control,
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001765 const DataLoaderStatusListener* statusListener,
1766 StorageHealthCheckParams&& healthCheckParams,
1767 const StorageHealthListener* healthListener,
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001768 std::string&& healthPath)
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001769 : mService(service),
1770 mId(id),
1771 mParams(std::move(params)),
1772 mControl(std::move(control)),
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001773 mStatusListener(statusListener ? *statusListener : DataLoaderStatusListener()),
1774 mHealthListener(healthListener ? *healthListener : StorageHealthListener()),
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001775 mHealthPath(std::move(healthPath)),
1776 mHealthCheckParams(std::move(healthCheckParams)) {
1777 if (mHealthListener) {
1778 if (!isHealthParamsValid()) {
1779 mHealthListener = {};
1780 }
1781 } else {
1782 // Disable advanced health check statuses.
1783 mHealthCheckParams.blockedTimeoutMs = -1;
1784 }
1785 updateHealthStatus();
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001786}
1787
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001788IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001789 if (isValid()) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001790 cleanupResources();
1791 }
1792}
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001793
1794void IncrementalService::DataLoaderStub::cleanupResources() {
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001795 auto now = Clock::now();
1796 {
1797 std::unique_lock lock(mMutex);
1798 mHealthPath.clear();
1799 unregisterFromPendingReads();
1800 resetHealthControl();
1801 mService.removeTimedJobs(mId);
1802 }
1803
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001804 requestDestroy();
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001805
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001806 {
1807 std::unique_lock lock(mMutex);
1808 mParams = {};
1809 mControl = {};
1810 mHealthControl = {};
1811 mHealthListener = {};
1812 mStatusCondition.wait_until(lock, now + 60s, [this] {
1813 return mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1814 });
1815 mStatusListener = {};
1816 mId = kInvalidStorageId;
1817 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001818}
1819
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001820sp<content::pm::IDataLoader> IncrementalService::DataLoaderStub::getDataLoader() {
1821 sp<IDataLoader> dataloader;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001822 auto status = mService.mDataLoaderManager->getDataLoader(id(), &dataloader);
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001823 if (!status.isOk()) {
1824 LOG(ERROR) << "Failed to get dataloader: " << status.toString8();
1825 return {};
1826 }
1827 if (!dataloader) {
1828 LOG(ERROR) << "DataLoader is null: " << status.toString8();
1829 return {};
1830 }
1831 return dataloader;
1832}
1833
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001834bool IncrementalService::DataLoaderStub::requestCreate() {
1835 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_CREATED);
1836}
1837
1838bool IncrementalService::DataLoaderStub::requestStart() {
1839 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_STARTED);
1840}
1841
1842bool IncrementalService::DataLoaderStub::requestDestroy() {
1843 return setTargetStatus(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
1844}
1845
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001846bool IncrementalService::DataLoaderStub::setTargetStatus(int newStatus) {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001847 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001848 std::unique_lock lock(mMutex);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001849 setTargetStatusLocked(newStatus);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001850 }
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001851 return fsmStep();
1852}
1853
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001854void IncrementalService::DataLoaderStub::setTargetStatusLocked(int status) {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001855 auto oldStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001856 mTargetStatus = status;
1857 mTargetStatusTs = Clock::now();
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001858 LOG(DEBUG) << "Target status update for DataLoader " << id() << ": " << oldStatus << " -> "
Alex Buynytskyycca2c112020-05-05 12:48:41 -07001859 << status << " (current " << mCurrentStatus << ")";
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001860}
1861
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001862bool IncrementalService::DataLoaderStub::bind() {
1863 bool result = false;
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001864 auto status = mService.mDataLoaderManager->bindToDataLoader(id(), mParams, this, &result);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001865 if (!status.isOk() || !result) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001866 LOG(ERROR) << "Failed to bind a data loader for mount " << id();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001867 return false;
1868 }
1869 return true;
1870}
1871
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001872bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001873 auto dataloader = getDataLoader();
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001874 if (!dataloader) {
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001875 return false;
1876 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001877 auto status = dataloader->create(id(), mParams, mControl, this);
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001878 if (!status.isOk()) {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001879 LOG(ERROR) << "Failed to create DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001880 return false;
1881 }
1882 return true;
1883}
1884
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001885bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001886 auto dataloader = getDataLoader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001887 if (!dataloader) {
1888 return false;
1889 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001890 auto status = dataloader->start(id());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001891 if (!status.isOk()) {
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001892 LOG(ERROR) << "Failed to start DataLoader: " << status.toString8();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001893 return false;
1894 }
1895 return true;
1896}
1897
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001898bool IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001899 return mService.mDataLoaderManager->unbindFromDataLoader(id()).isOk();
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001900}
1901
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001902bool IncrementalService::DataLoaderStub::fsmStep() {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001903 if (!isValid()) {
1904 return false;
1905 }
1906
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001907 int currentStatus;
1908 int targetStatus;
1909 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001910 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001911 currentStatus = mCurrentStatus;
1912 targetStatus = mTargetStatus;
1913 }
1914
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001915 LOG(DEBUG) << "fsmStep: " << id() << ": " << currentStatus << " -> " << targetStatus;
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001916
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001917 if (currentStatus == targetStatus) {
1918 return true;
1919 }
1920
1921 switch (targetStatus) {
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001922 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
1923 // Do nothing, this is a reset state.
1924 break;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001925 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
1926 return destroy();
1927 }
1928 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
1929 switch (currentStatus) {
1930 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1931 case IDataLoaderStatusListener::DATA_LOADER_STOPPED:
1932 return start();
1933 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07001934 [[fallthrough]];
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001935 }
1936 case IDataLoaderStatusListener::DATA_LOADER_CREATED:
1937 switch (currentStatus) {
1938 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED:
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001939 case IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE:
Alex Buynytskyyea1390f2020-04-22 16:08:50 -07001940 return bind();
1941 case IDataLoaderStatusListener::DATA_LOADER_BOUND:
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001942 return create();
1943 }
1944 break;
1945 default:
1946 LOG(ERROR) << "Invalid target status: " << targetStatus
1947 << ", current status: " << currentStatus;
1948 break;
1949 }
1950 return false;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001951}
1952
1953binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001954 if (!isValid()) {
1955 return binder::Status::
1956 fromServiceSpecificError(-EINVAL, "onStatusChange came to invalid DataLoaderStub");
1957 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001958 if (id() != mountId) {
1959 LOG(ERROR) << "Mount ID mismatch: expected " << id() << ", but got: " << mountId;
Alex Buynytskyy9a54579a2020-04-17 15:34:47 -07001960 return binder::Status::fromServiceSpecificError(-EPERM, "Mount ID mismatch.");
1961 }
1962
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001963 int targetStatus, oldStatus;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001964 DataLoaderStatusListener listener;
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001965 {
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001966 std::unique_lock lock(mMutex);
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001967 if (mCurrentStatus == newStatus) {
1968 return binder::Status::ok();
1969 }
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001970
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001971 oldStatus = mCurrentStatus;
Alex Buynytskyy0bdbccf2020-04-23 20:36:42 -07001972 mCurrentStatus = newStatus;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001973 targetStatus = mTargetStatus;
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001974
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001975 listener = mStatusListener;
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001976
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001977 if (mCurrentStatus == IDataLoaderStatusListener::DATA_LOADER_UNAVAILABLE) {
Alex Buynytskyy4dbc0602020-05-12 11:24:14 -07001978 // For unavailable, unbind from DataLoader to ensure proper re-commit.
1979 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_DESTROYED);
Alex Buynytskyy7e0a1a82020-04-27 17:06:10 -07001980 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001981 }
1982
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -07001983 LOG(DEBUG) << "Current status update for DataLoader " << id() << ": " << oldStatus << " -> "
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07001984 << newStatus << " (target " << targetStatus << ")";
1985
Alex Buynytskyyb0ea4482020-05-04 18:39:58 -07001986 if (listener) {
1987 listener->onStatusChanged(mountId, newStatus);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001988 }
1989
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07001990 fsmStep();
Songchun Fan3c82a302019-11-29 14:23:45 -08001991
Alex Buynytskyyc2a645d2020-04-20 14:11:55 -07001992 mStatusCondition.notify_all();
1993
Songchun Fan3c82a302019-11-29 14:23:45 -08001994 return binder::Status::ok();
1995}
1996
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07001997bool IncrementalService::DataLoaderStub::isHealthParamsValid() const {
1998 return mHealthCheckParams.blockedTimeoutMs > 0 &&
1999 mHealthCheckParams.blockedTimeoutMs < mHealthCheckParams.unhealthyTimeoutMs;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002000}
2001
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002002void IncrementalService::DataLoaderStub::onHealthStatus(StorageHealthListener healthListener,
2003 int healthStatus) {
2004 LOG(DEBUG) << id() << ": healthStatus: " << healthStatus;
2005 if (healthListener) {
2006 healthListener->onHealthStatus(id(), healthStatus);
2007 }
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002008}
2009
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002010void IncrementalService::DataLoaderStub::updateHealthStatus(bool baseline) {
2011 LOG(DEBUG) << id() << ": updateHealthStatus" << (baseline ? " (baseline)" : "");
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002012
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002013 int healthStatusToReport = -1;
2014 StorageHealthListener healthListener;
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002015
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002016 {
2017 std::unique_lock lock(mMutex);
2018 unregisterFromPendingReads();
2019
2020 healthListener = mHealthListener;
2021
2022 // Healthcheck depends on timestamp of the oldest pending read.
2023 // To get it, we need to re-open a pendingReads FD to get a full list of reads.
2024 // Additionally we need to re-register for epoll with fresh FDs in case there are no reads.
2025 const auto now = Clock::now();
2026 const auto kernelTsUs = getOldestPendingReadTs();
2027 if (baseline) {
2028 // Updating baseline only on looper/epoll callback, i.e. on new set of pending reads.
2029 mHealthBase = {now, kernelTsUs};
2030 }
2031
2032 if (kernelTsUs == kMaxBootClockTsUs || mHealthBase.userTs > now ||
2033 mHealthBase.kernelTsUs > kernelTsUs) {
2034 LOG(DEBUG) << id() << ": No pending reads or invalid base, report Ok and wait.";
2035 registerForPendingReads();
2036 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_OK;
2037 lock.unlock();
2038 onHealthStatus(healthListener, healthStatusToReport);
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002039 return;
2040 }
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002041
2042 resetHealthControl();
2043
2044 // Always make sure the data loader is started.
2045 setTargetStatusLocked(IDataLoaderStatusListener::DATA_LOADER_STARTED);
2046
2047 // Skip any further processing if health check params are invalid.
2048 if (!isHealthParamsValid()) {
2049 LOG(DEBUG) << id()
2050 << ": Skip any further processing if health check params are invalid.";
2051 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2052 lock.unlock();
2053 onHealthStatus(healthListener, healthStatusToReport);
2054 // Triggering data loader start. This is a one-time action.
2055 fsmStep();
2056 return;
2057 }
2058
2059 const auto blockedTimeout = std::chrono::milliseconds(mHealthCheckParams.blockedTimeoutMs);
2060 const auto unhealthyTimeout =
2061 std::chrono::milliseconds(mHealthCheckParams.unhealthyTimeoutMs);
2062 const auto unhealthyMonitoring =
2063 std::max(1000ms,
2064 std::chrono::milliseconds(mHealthCheckParams.unhealthyMonitoringMs));
2065
2066 const auto kernelDeltaUs = kernelTsUs - mHealthBase.kernelTsUs;
2067 const auto userTs = mHealthBase.userTs + std::chrono::microseconds(kernelDeltaUs);
2068 const auto delta = now - userTs;
2069
2070 TimePoint whenToCheckBack;
2071 if (delta < blockedTimeout) {
2072 LOG(DEBUG) << id() << ": Report reads pending and wait for blocked status.";
2073 whenToCheckBack = userTs + blockedTimeout;
2074 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_READS_PENDING;
2075 } else if (delta < unhealthyTimeout) {
2076 LOG(DEBUG) << id() << ": Report blocked and wait for unhealthy.";
2077 whenToCheckBack = userTs + unhealthyTimeout;
2078 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_BLOCKED;
2079 } else {
2080 LOG(DEBUG) << id() << ": Report unhealthy and continue monitoring.";
2081 whenToCheckBack = now + unhealthyMonitoring;
2082 healthStatusToReport = IStorageHealthListener::HEALTH_STATUS_UNHEALTHY;
2083 }
2084 LOG(DEBUG) << id() << ": updateHealthStatus in "
2085 << double(std::chrono::duration_cast<std::chrono::milliseconds>(whenToCheckBack -
2086 now)
2087 .count()) /
2088 1000.0
2089 << "secs";
2090 mService.addTimedJob(id(), whenToCheckBack, [this]() { updateHealthStatus(); });
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002091 }
2092
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002093 if (healthStatusToReport != -1) {
2094 onHealthStatus(healthListener, healthStatusToReport);
2095 }
2096
2097 fsmStep();
2098}
2099
2100const incfs::UniqueControl& IncrementalService::DataLoaderStub::initializeHealthControl() {
2101 if (mHealthPath.empty()) {
2102 resetHealthControl();
2103 return mHealthControl;
2104 }
2105 if (mHealthControl.pendingReads() < 0) {
2106 mHealthControl = mService.mIncFs->openMount(mHealthPath);
2107 }
2108 if (mHealthControl.pendingReads() < 0) {
2109 LOG(ERROR) << "Failed to open health control for: " << id() << ", path: " << mHealthPath
2110 << "(" << mHealthControl.cmd() << ":" << mHealthControl.pendingReads() << ":"
2111 << mHealthControl.logs() << ")";
2112 }
2113 return mHealthControl;
2114}
2115
2116void IncrementalService::DataLoaderStub::resetHealthControl() {
2117 mHealthControl = {};
2118}
2119
2120BootClockTsUs IncrementalService::DataLoaderStub::getOldestPendingReadTs() {
2121 auto result = kMaxBootClockTsUs;
2122
2123 const auto& control = initializeHealthControl();
2124 if (control.pendingReads() < 0) {
2125 return result;
2126 }
2127
2128 std::vector<incfs::ReadInfo> pendingReads;
2129 if (mService.mIncFs->waitForPendingReads(control, 0ms, &pendingReads) !=
2130 android::incfs::WaitResult::HaveData ||
2131 pendingReads.empty()) {
2132 return result;
2133 }
2134
2135 LOG(DEBUG) << id() << ": pendingReads: " << control.pendingReads() << ", "
2136 << pendingReads.size() << ": " << pendingReads.front().bootClockTsUs;
2137
2138 for (auto&& pendingRead : pendingReads) {
2139 result = std::min(result, pendingRead.bootClockTsUs);
2140 }
2141 return result;
2142}
2143
2144void IncrementalService::DataLoaderStub::registerForPendingReads() {
2145 const auto pendingReadsFd = mHealthControl.pendingReads();
2146 if (pendingReadsFd < 0) {
2147 return;
2148 }
2149
2150 LOG(DEBUG) << id() << ": addFd(pendingReadsFd): " << pendingReadsFd;
2151
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002152 mService.mLooper->addFd(
2153 pendingReadsFd, android::Looper::POLL_CALLBACK, android::Looper::EVENT_INPUT,
2154 [](int, int, void* data) -> int {
2155 auto&& self = (DataLoaderStub*)data;
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002156 self->updateHealthStatus(/*baseline=*/true);
2157 return 0;
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002158 },
2159 this);
2160 mService.mLooper->wake();
2161}
2162
Alex Buynytskyyd0855a32020-05-07 18:40:51 -07002163void IncrementalService::DataLoaderStub::unregisterFromPendingReads() {
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002164 const auto pendingReadsFd = mHealthControl.pendingReads();
2165 if (pendingReadsFd < 0) {
2166 return;
2167 }
2168
Alex Buynytskyy4760d8f2020-05-08 16:18:52 -07002169 LOG(DEBUG) << id() << ": removeFd(pendingReadsFd): " << pendingReadsFd;
2170
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002171 mService.mLooper->removeFd(pendingReadsFd);
2172 mService.mLooper->wake();
Alex Buynytskyycca2c112020-05-05 12:48:41 -07002173}
2174
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002175void IncrementalService::DataLoaderStub::onDump(int fd) {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002176 dprintf(fd, " dataLoader: {\n");
2177 dprintf(fd, " currentStatus: %d\n", mCurrentStatus);
2178 dprintf(fd, " targetStatus: %d\n", mTargetStatus);
2179 dprintf(fd, " targetStatusTs: %lldmcs\n",
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002180 (long long)(elapsedMcs(mTargetStatusTs, Clock::now())));
2181 const auto& params = mParams;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -07002182 dprintf(fd, " dataLoaderParams: {\n");
2183 dprintf(fd, " type: %s\n", toString(params.type).c_str());
2184 dprintf(fd, " packageName: %s\n", params.packageName.c_str());
2185 dprintf(fd, " className: %s\n", params.className.c_str());
2186 dprintf(fd, " arguments: %s\n", params.arguments.c_str());
2187 dprintf(fd, " }\n");
2188 dprintf(fd, " }\n");
Alex Buynytskyyab65cb12020-04-17 10:01:47 -07002189}
2190
Alex Buynytskyy1d892162020-04-03 23:00:19 -07002191void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
2192 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07002193}
2194
Alex Buynytskyyf4156792020-04-07 14:26:55 -07002195binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
2196 bool enableReadLogs, int32_t* _aidl_return) {
2197 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
2198 return binder::Status::ok();
2199}
2200
Alex Buynytskyy0b202662020-04-13 09:53:04 -07002201FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
2202 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
2203}
2204
Songchun Fan3c82a302019-11-29 14:23:45 -08002205} // namespace android::incremental