1 /*
2  * Copyright (C) 2018 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 #include <dirent.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <linux/fs.h>
21 #include <stdlib.h>
22 #include <sys/stat.h>
23 #include <sys/statvfs.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26 
27 #include <algorithm>
28 #include <memory>
29 #include <optional>
30 #include <string>
31 #include <vector>
32 
33 #include <android-base/file.h>
34 #include <android-base/properties.h>
35 #include <android-base/strings.h>
36 #include <fs_mgr.h>
37 #include <fs_mgr_dm_linear.h>
38 #include <fs_mgr_overlayfs.h>
39 #include <fstab/fstab.h>
40 #include <libdm/dm.h>
41 #include <libfiemap/image_manager.h>
42 #include <libgsi/libgsi.h>
43 #include <liblp/builder.h>
44 #include <liblp/liblp.h>
45 #include <storage_literals/storage_literals.h>
46 
47 #include "fs_mgr_overlayfs_control.h"
48 #include "fs_mgr_overlayfs_mount.h"
49 #include "fs_mgr_priv.h"
50 #include "libfiemap/utility.h"
51 
52 using namespace std::literals;
53 using namespace android::dm;
54 using namespace android::fs_mgr;
55 using namespace android::storage_literals;
56 using android::fiemap::FilesystemHasReliablePinning;
57 using android::fiemap::IImageManager;
58 
59 namespace {
60 
61 constexpr char kDataScratchSizeMbProp[] = "fs_mgr.overlayfs.data_scratch_size_mb";
62 
63 constexpr char kPhysicalDevice[] = "/dev/block/by-name/";
64 constexpr char kScratchImageMetadata[] = "/metadata/gsi/remount/lp_metadata";
65 
66 constexpr char kMkF2fs[] = "/system/bin/make_f2fs";
67 constexpr char kMkExt4[] = "/system/bin/mke2fs";
68 
69 // Return true if everything is mounted, but before adb is started.  Right
70 // after 'trigger load_persist_props_action' is done.
fs_mgr_boot_completed()71 static bool fs_mgr_boot_completed() {
72     return android::base::GetBoolProperty("ro.persistent_properties.ready", false);
73 }
74 
75 // Note: this is meant only for recovery/first-stage init.
ScratchIsOnData()76 static bool ScratchIsOnData() {
77     // The scratch partition of DSU is managed by gsid.
78     if (fs_mgr_is_dsu_running()) {
79         return false;
80     }
81     return access(kScratchImageMetadata, F_OK) == 0;
82 }
83 
fs_mgr_rm_all(const std::string & path,bool * change=nullptr,int level=0)84 static bool fs_mgr_rm_all(const std::string& path, bool* change = nullptr, int level = 0) {
85     std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
86     if (!dir) {
87         if (errno == ENOENT) {
88             return true;
89         }
90         PERROR << "opendir " << path << " depth=" << level;
91         if ((errno == EPERM) && (level != 0)) {
92             return true;
93         }
94         return false;
95     }
96     dirent* entry;
97     auto ret = true;
98     while ((entry = readdir(dir.get()))) {
99         if (("."s == entry->d_name) || (".."s == entry->d_name)) continue;
100         auto file = path + "/" + entry->d_name;
101         if (entry->d_type == DT_UNKNOWN) {
102             struct stat st;
103             if (!lstat(file.c_str(), &st) && (st.st_mode & S_IFDIR)) entry->d_type = DT_DIR;
104         }
105         if (entry->d_type == DT_DIR) {
106             ret &= fs_mgr_rm_all(file, change, level + 1);
107             if (!rmdir(file.c_str())) {
108                 if (change) *change = true;
109             } else {
110                 if (errno != ENOENT) ret = false;
111                 PERROR << "rmdir " << file << " depth=" << level;
112             }
113             continue;
114         }
115         if (!unlink(file.c_str())) {
116             if (change) *change = true;
117         } else {
118             if (errno != ENOENT) ret = false;
119             PERROR << "rm " << file << " depth=" << level;
120         }
121     }
122     return ret;
123 }
124 
fs_mgr_overlayfs_setup_dir(const std::string & dir)125 std::string fs_mgr_overlayfs_setup_dir(const std::string& dir) {
126     auto top = dir + "/" + kOverlayTopDir;
127 
128     AutoSetFsCreateCon createcon(kOverlayfsFileContext);
129     if (!createcon.Ok()) {
130         return {};
131     }
132     if (mkdir(top.c_str(), 0755) != 0 && errno != EEXIST) {
133         PERROR << "mkdir " << top;
134         return {};
135     }
136     if (!createcon.Restore()) {
137         return {};
138     }
139     return top;
140 }
141 
fs_mgr_overlayfs_setup_one(const std::string & overlay,const std::string & mount_point,bool * want_reboot)142 bool fs_mgr_overlayfs_setup_one(const std::string& overlay, const std::string& mount_point,
143                                 bool* want_reboot) {
144     if (fs_mgr_overlayfs_already_mounted(mount_point)) {
145         return true;
146     }
147     const auto base = GetEncodedBaseDirForMountPoint(mount_point);
148     auto fsrec_mount_point = overlay + "/" + base + "/";
149 
150     AutoSetFsCreateCon createcon(kOverlayfsFileContext);
151     if (!createcon.Ok()) {
152         return false;
153     }
154     if (mkdir(fsrec_mount_point.c_str(), 0755) != 0 && errno != EEXIST) {
155         PERROR << "mkdir " << fsrec_mount_point;
156         return false;
157     }
158     if (mkdir((fsrec_mount_point + kWorkName).c_str(), 0755) != 0 && errno != EEXIST) {
159         PERROR << "mkdir " << fsrec_mount_point << kWorkName;
160         return false;
161     }
162     if (!createcon.Restore()) {
163         return false;
164     }
165 
166     createcon = {};
167 
168     auto new_context = fs_mgr_get_context(mount_point);
169     if (new_context.empty() || !createcon.Set(new_context)) {
170         return false;
171     }
172 
173     auto upper = fsrec_mount_point + kUpperName;
174     if (mkdir(upper.c_str(), 0755) != 0 && errno != EEXIST) {
175         PERROR << "mkdir " << upper;
176         return false;
177     }
178     if (!createcon.Restore()) {
179         return false;
180     }
181 
182     if (want_reboot) *want_reboot = true;
183 
184     return true;
185 }
186 
fs_mgr_overlayfs_slot_number()187 static uint32_t fs_mgr_overlayfs_slot_number() {
188     return SlotNumberForSlotSuffix(fs_mgr_get_slot_suffix());
189 }
190 
fs_mgr_overlayfs_has_logical(const Fstab & fstab)191 static bool fs_mgr_overlayfs_has_logical(const Fstab& fstab) {
192     for (const auto& entry : fstab) {
193         if (entry.fs_mgr_flags.logical) {
194             return true;
195         }
196     }
197     return false;
198 }
199 
TeardownDataScratch(IImageManager * images,const std::string & partition_name,bool was_mounted)200 OverlayfsTeardownResult TeardownDataScratch(IImageManager* images,
201                                             const std::string& partition_name, bool was_mounted) {
202     if (!images) {
203         return OverlayfsTeardownResult::Error;
204     }
205     if (!images->DisableImage(partition_name)) {
206         return OverlayfsTeardownResult::Error;
207     }
208     if (was_mounted) {
209         // If overlayfs was mounted, don't bother trying to unmap since
210         // it'll fail and create error spam.
211         return OverlayfsTeardownResult::Busy;
212     }
213     if (!images->UnmapImageIfExists(partition_name)) {
214         return OverlayfsTeardownResult::Busy;
215     }
216     if (!images->DeleteBackingImage(partition_name)) {
217         return OverlayfsTeardownResult::Busy;
218     }
219     return OverlayfsTeardownResult::Ok;
220 }
221 
GetOverlaysActiveFlag()222 bool GetOverlaysActiveFlag() {
223     auto slot_number = fs_mgr_overlayfs_slot_number();
224     const auto super_device = kPhysicalDevice + fs_mgr_get_super_partition_name();
225 
226     auto metadata = ReadMetadata(super_device, slot_number);
227     if (!metadata) {
228         return false;
229     }
230     return !!(metadata->header.flags & LP_HEADER_FLAG_OVERLAYS_ACTIVE);
231 }
232 
SetOverlaysActiveFlag(bool flag)233 bool SetOverlaysActiveFlag(bool flag) {
234     // Mark overlays as active in the partition table, to detect re-flash.
235     auto slot_number = fs_mgr_overlayfs_slot_number();
236     const auto super_device = kPhysicalDevice + fs_mgr_get_super_partition_name();
237     auto builder = MetadataBuilder::New(super_device, slot_number);
238     if (!builder) {
239         LERROR << "open " << super_device << " metadata";
240         return false;
241     }
242     builder->SetOverlaysActiveFlag(flag);
243     auto metadata = builder->Export();
244     if (!metadata || !UpdatePartitionTable(super_device, *metadata.get(), slot_number)) {
245         LERROR << "update super metadata";
246         return false;
247     }
248     return true;
249 }
250 
fs_mgr_overlayfs_teardown_scratch(const std::string & overlay,bool * change)251 OverlayfsTeardownResult fs_mgr_overlayfs_teardown_scratch(const std::string& overlay,
252                                                           bool* change) {
253     // umount and delete kScratchMountPoint storage if we have logical partitions
254     if (overlay != kScratchMountPoint) {
255         return OverlayfsTeardownResult::Ok;
256     }
257 
258     // Validation check.
259     if (fs_mgr_is_dsu_running()) {
260         LERROR << "Destroying DSU scratch is not allowed.";
261         return OverlayfsTeardownResult::Error;
262     }
263 
264     // Note: we don't care if SetOverlaysActiveFlag fails, since
265     // the overlays are removed no matter what.
266     SetOverlaysActiveFlag(false);
267 
268     bool was_mounted = fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false);
269     if (was_mounted) {
270         fs_mgr_overlayfs_umount_scratch();
271     }
272 
273     const auto partition_name = android::base::Basename(kScratchMountPoint);
274 
275     auto images = IImageManager::Open("remount", 10s);
276     if (images && images->BackingImageExists(partition_name)) {
277         // No need to check super partition, if we knew we had a scratch device
278         // in /data.
279         return TeardownDataScratch(images.get(), partition_name, was_mounted);
280     }
281 
282     auto slot_number = fs_mgr_overlayfs_slot_number();
283     const auto super_device = kPhysicalDevice + fs_mgr_get_super_partition_name();
284     if (access(super_device.c_str(), R_OK | W_OK)) {
285         return OverlayfsTeardownResult::Ok;
286     }
287 
288     auto builder = MetadataBuilder::New(super_device, slot_number);
289     if (!builder) {
290         return OverlayfsTeardownResult::Ok;
291     }
292     if (builder->FindPartition(partition_name) == nullptr) {
293         return OverlayfsTeardownResult::Ok;
294     }
295     builder->RemovePartition(partition_name);
296     auto metadata = builder->Export();
297     if (metadata && UpdatePartitionTable(super_device, *metadata.get(), slot_number)) {
298         if (change) *change = true;
299         if (!DestroyLogicalPartition(partition_name)) {
300             return OverlayfsTeardownResult::Error;
301         }
302     } else {
303         LERROR << "delete partition " << overlay;
304         return OverlayfsTeardownResult::Error;
305     }
306 
307     if (was_mounted) {
308         return OverlayfsTeardownResult::Busy;
309     }
310     return OverlayfsTeardownResult::Ok;
311 }
312 
fs_mgr_overlayfs_teardown_one(const std::string & overlay,const std::string & mount_point,bool * change,bool * should_destroy_scratch=nullptr)313 bool fs_mgr_overlayfs_teardown_one(const std::string& overlay, const std::string& mount_point,
314                                    bool* change, bool* should_destroy_scratch = nullptr) {
315     const auto top = overlay + "/" + kOverlayTopDir;
316 
317     if (access(top.c_str(), F_OK)) {
318         if (should_destroy_scratch) *should_destroy_scratch = true;
319         return true;
320     }
321 
322     auto cleanup_all = mount_point.empty();
323     const auto base = GetEncodedBaseDirForMountPoint(mount_point);
324     const auto oldpath = top + (cleanup_all ? "" : ("/" + base));
325     const auto newpath = cleanup_all ? overlay + "/." + kOverlayTopDir + ".teardown"
326                                      : top + "/." + base + ".teardown";
327     auto ret = fs_mgr_rm_all(newpath);
328     if (!rename(oldpath.c_str(), newpath.c_str())) {
329         if (change) *change = true;
330     } else if (errno != ENOENT) {
331         ret = false;
332         PERROR << "mv " << oldpath << " " << newpath;
333     }
334     ret &= fs_mgr_rm_all(newpath, change);
335     if (!rmdir(newpath.c_str())) {
336         if (change) *change = true;
337     } else if (errno != ENOENT) {
338         ret = false;
339         PERROR << "rmdir " << newpath;
340     }
341     if (!cleanup_all) {
342         if (!rmdir(top.c_str())) {
343             if (change) *change = true;
344             cleanup_all = true;
345         } else if (errno == ENOTEMPTY) {
346             cleanup_all = true;
347             // cleanup all if the content is all hidden (leading .)
348             std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(top.c_str()), closedir);
349             if (!dir) {
350                 PERROR << "opendir " << top;
351             } else {
352                 dirent* entry;
353                 while ((entry = readdir(dir.get()))) {
354                     if (entry->d_name[0] != '.') {
355                         cleanup_all = false;
356                         break;
357                     }
358                 }
359             }
360         } else if (errno == ENOENT) {
361             cleanup_all = true;
362         } else {
363             ret = false;
364             PERROR << "rmdir " << top;
365         }
366     }
367     if (should_destroy_scratch) *should_destroy_scratch = cleanup_all;
368     return ret;
369 }
370 
371 // Note: The scratch partition of DSU is managed by gsid, and should be initialized during
372 // first-stage-mount. Just check if the DM device for DSU scratch partition is created or not.
GetDsuScratchDevice()373 static std::string GetDsuScratchDevice() {
374     auto& dm = DeviceMapper::Instance();
375     std::string device;
376     if (dm.GetState(android::gsi::kDsuScratch) != DmDeviceState::INVALID &&
377         dm.GetDmDevicePathByName(android::gsi::kDsuScratch, &device)) {
378         return device;
379     }
380     return "";
381 }
382 
MakeScratchFilesystem(const std::string & scratch_device)383 bool MakeScratchFilesystem(const std::string& scratch_device) {
384     // Force mkfs by design for overlay support of adb remount, simplify and
385     // thus do not rely on fsck to correct problems that could creep in.
386     auto fs_type = ""s;
387     auto command = ""s;
388     if (!access(kMkF2fs, X_OK) && fs_mgr_filesystem_available("f2fs")) {
389         fs_type = "f2fs";
390         command = kMkF2fs + " -w "s;
391         command += std::to_string(getpagesize());
392         command = kMkF2fs + " -b "s;
393         command += std::to_string(getpagesize());
394         command += " -f -d1 -l" + android::base::Basename(kScratchMountPoint);
395     } else if (!access(kMkExt4, X_OK) && fs_mgr_filesystem_available("ext4")) {
396         fs_type = "ext4";
397         command = kMkExt4 + " -F -b 4096 -t ext4 -m 0 -O has_journal -M "s + kScratchMountPoint;
398     } else {
399         LERROR << "No supported mkfs command or filesystem driver available, supported filesystems "
400                   "are: f2fs, ext4";
401         return false;
402     }
403     command += " " + scratch_device + " >/dev/null 2>/dev/null </dev/null";
404     fs_mgr_set_blk_ro(scratch_device, false);
405     auto ret = system(command.c_str());
406     if (ret) {
407         LERROR << "make " << fs_type << " filesystem on " << scratch_device << " return=" << ret;
408         return false;
409     }
410     return true;
411 }
412 
TruncatePartitionsWithSuffix(MetadataBuilder * builder,const std::string & suffix)413 static void TruncatePartitionsWithSuffix(MetadataBuilder* builder, const std::string& suffix) {
414     auto& dm = DeviceMapper::Instance();
415 
416     // Remove <other> partitions
417     for (const auto& group : builder->ListGroups()) {
418         for (const auto& part : builder->ListPartitionsInGroup(group)) {
419             const auto& name = part->name();
420             if (!android::base::EndsWith(name, suffix)) {
421                 continue;
422             }
423             if (dm.GetState(name) != DmDeviceState::INVALID && !DestroyLogicalPartition(name)) {
424                 continue;
425             }
426             builder->ResizePartition(builder->FindPartition(name), 0);
427         }
428     }
429 }
430 
431 // Create or update a scratch partition within super.
CreateDynamicScratch(std::string * scratch_device,bool * partition_exists)432 static bool CreateDynamicScratch(std::string* scratch_device, bool* partition_exists) {
433     const auto partition_name = android::base::Basename(kScratchMountPoint);
434 
435     auto& dm = DeviceMapper::Instance();
436     *partition_exists = dm.GetState(partition_name) != DmDeviceState::INVALID;
437 
438     auto partition_create = !*partition_exists;
439     auto slot_number = fs_mgr_overlayfs_slot_number();
440     const auto super_device = kPhysicalDevice + fs_mgr_get_super_partition_name();
441     auto builder = MetadataBuilder::New(super_device, slot_number);
442     if (!builder) {
443         LERROR << "open " << super_device << " metadata";
444         return false;
445     }
446     auto partition = builder->FindPartition(partition_name);
447     *partition_exists = partition != nullptr;
448     auto changed = false;
449     if (!*partition_exists) {
450         partition = builder->AddPartition(partition_name, LP_PARTITION_ATTR_NONE);
451         if (!partition) {
452             LERROR << "create " << partition_name;
453             return false;
454         }
455         changed = true;
456     }
457     // Take half of free space, minimum 512MB or maximum free - margin.
458     static constexpr auto kMinimumSize = uint64_t(512 * 1024 * 1024);
459     if (partition->size() < kMinimumSize) {
460         auto partition_size =
461                 builder->AllocatableSpace() - builder->UsedSpace() + partition->size();
462         if ((partition_size > kMinimumSize) || !partition->size()) {
463             partition_size = std::max(std::min(kMinimumSize, partition_size), partition_size / 2);
464             if (partition_size > partition->size()) {
465                 if (!builder->ResizePartition(partition, partition_size)) {
466                     // Try to free up space by deallocating partitions in the other slot.
467                     TruncatePartitionsWithSuffix(builder.get(), fs_mgr_get_other_slot_suffix());
468 
469                     partition_size =
470                             builder->AllocatableSpace() - builder->UsedSpace() + partition->size();
471                     partition_size =
472                             std::max(std::min(kMinimumSize, partition_size), partition_size / 2);
473                     if (!builder->ResizePartition(partition, partition_size)) {
474                         LERROR << "resize " << partition_name;
475                         return false;
476                     }
477                 }
478                 if (!partition_create) DestroyLogicalPartition(partition_name);
479                 changed = true;
480                 *partition_exists = false;
481             }
482         }
483     }
484 
485     // land the update back on to the partition
486     if (changed) {
487         auto metadata = builder->Export();
488         if (!metadata || !UpdatePartitionTable(super_device, *metadata.get(), slot_number)) {
489             LERROR << "add partition " << partition_name;
490             return false;
491         }
492     }
493 
494     if (changed || partition_create) {
495         CreateLogicalPartitionParams params = {
496                 .block_device = super_device,
497                 .metadata_slot = slot_number,
498                 .partition_name = partition_name,
499                 .force_writable = true,
500                 .timeout_ms = 10s,
501         };
502         if (!CreateLogicalPartition(params, scratch_device)) {
503             return false;
504         }
505     } else if (scratch_device->empty()) {
506         *scratch_device = GetBootScratchDevice();
507     }
508     return true;
509 }
510 
GetIdealDataScratchSize()511 static inline uint64_t GetIdealDataScratchSize() {
512     BlockDeviceInfo super_info;
513     PartitionOpener opener;
514     if (!opener.GetInfo(fs_mgr_get_super_partition_name(), &super_info)) {
515         LERROR << "could not get block device info for super";
516         return 0;
517     }
518 
519     struct statvfs s;
520     if (statvfs("/data", &s) < 0) {
521         PERROR << "could not statfs /data";
522         return 0;
523     }
524 
525     auto ideal_size = std::min(super_info.size, uint64_t(uint64_t(s.f_frsize) * s.f_bfree * 0.85));
526 
527     // Align up to the filesystem block size.
528     if (auto remainder = ideal_size % s.f_bsize; remainder > 0) {
529         ideal_size += s.f_bsize - remainder;
530     }
531     return ideal_size;
532 }
533 
CreateScratchOnData(std::string * scratch_device,bool * partition_exists)534 static bool CreateScratchOnData(std::string* scratch_device, bool* partition_exists) {
535     *partition_exists = false;
536 
537     auto images = IImageManager::Open("remount", 10s);
538     if (!images) {
539         return false;
540     }
541 
542     auto partition_name = android::base::Basename(kScratchMountPoint);
543     if (images->GetMappedImageDevice(partition_name, scratch_device)) {
544         *partition_exists = true;
545         return true;
546     }
547 
548     // Note: calling RemoveDisabledImages here ensures that we do not race with
549     // clean_scratch_files and accidentally try to map an image that will be
550     // deleted.
551     if (!images->RemoveDisabledImages()) {
552         return false;
553     }
554     if (!images->BackingImageExists(partition_name)) {
555         auto size = android::base::GetUintProperty<uint64_t>(kDataScratchSizeMbProp, 0) * 1_MiB;
556         if (!size) {
557             size = GetIdealDataScratchSize();
558         }
559         if (!size) {
560             size = 2_GiB;
561         }
562 
563         auto flags = IImageManager::CREATE_IMAGE_DEFAULT;
564 
565         if (!images->CreateBackingImage(partition_name, size, flags)) {
566             LERROR << "could not create scratch image of " << size << " bytes";
567             return false;
568         }
569     }
570     if (!images->MapImageDevice(partition_name, 10s, scratch_device)) {
571         LERROR << "could not map scratch image";
572         // If we cannot use this image, then remove it.
573         TeardownDataScratch(images.get(), partition_name, false /* was_mounted */);
574         return false;
575     }
576     return true;
577 }
578 
CanUseSuperPartition(const Fstab & fstab)579 static bool CanUseSuperPartition(const Fstab& fstab) {
580     auto slot_number = fs_mgr_overlayfs_slot_number();
581     const auto super_device = kPhysicalDevice + fs_mgr_get_super_partition_name();
582     if (access(super_device.c_str(), R_OK | W_OK) || !fs_mgr_overlayfs_has_logical(fstab)) {
583         return false;
584     }
585     auto metadata = ReadMetadata(super_device, slot_number);
586     if (!metadata) {
587         return false;
588     }
589     return true;
590 }
591 
fs_mgr_overlayfs_create_scratch(const Fstab & fstab,std::string * scratch_device,bool * partition_exists)592 bool fs_mgr_overlayfs_create_scratch(const Fstab& fstab, std::string* scratch_device,
593                                      bool* partition_exists) {
594     // Use the DSU scratch device managed by gsid if within a DSU system.
595     if (fs_mgr_is_dsu_running()) {
596         *scratch_device = GetDsuScratchDevice();
597         *partition_exists = !scratch_device->empty();
598         return *partition_exists;
599     }
600 
601     // Try ImageManager on /data first.
602     bool can_use_data = false;
603     if (FilesystemHasReliablePinning("/data", &can_use_data) && can_use_data) {
604         if (CreateScratchOnData(scratch_device, partition_exists)) {
605             return true;
606         }
607         LOG(WARNING) << "Failed to allocate scratch on /data, fallback to use free space on super";
608     }
609     // If that fails, see if we can land on super.
610     if (CanUseSuperPartition(fstab)) {
611         return CreateDynamicScratch(scratch_device, partition_exists);
612     }
613     return false;
614 }
615 
616 // Create and mount kScratchMountPoint storage if we have logical partitions
fs_mgr_overlayfs_setup_scratch(const Fstab & fstab)617 bool fs_mgr_overlayfs_setup_scratch(const Fstab& fstab) {
618     if (fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) {
619         return true;
620     }
621 
622     std::string scratch_device;
623     bool partition_exists;
624     if (!fs_mgr_overlayfs_create_scratch(fstab, &scratch_device, &partition_exists)) {
625         LOG(ERROR) << "Failed to create scratch partition";
626         return false;
627     }
628 
629     if (!SetOverlaysActiveFlag(true)) {
630         LOG(ERROR) << "Failed to update dynamic partition data";
631         fs_mgr_overlayfs_teardown_scratch(kScratchMountPoint, nullptr);
632         return false;
633     }
634 
635     // If the partition exists, assume first that it can be mounted.
636     if (partition_exists) {
637         if (MountScratch(scratch_device)) {
638             const auto top = kScratchMountPoint + "/"s + kOverlayTopDir;
639             if (access(top.c_str(), F_OK) == 0 || fs_mgr_filesystem_has_space(kScratchMountPoint)) {
640                 return true;
641             }
642             // declare it useless, no overrides and no free space
643             if (!fs_mgr_overlayfs_umount_scratch()) {
644                 LOG(ERROR) << "Unable to unmount scratch partition";
645                 return false;
646             }
647         }
648     }
649 
650     if (!MakeScratchFilesystem(scratch_device)) {
651         LOG(ERROR) << "Failed to format scratch partition";
652         return false;
653     }
654 
655     return MountScratch(scratch_device);
656 }
657 
OverlayfsTeardownAllowed()658 constexpr bool OverlayfsTeardownAllowed() {
659     // Never allow on non-debuggable build.
660     return kAllowOverlayfs;
661 }
662 
663 }  // namespace
664 
fs_mgr_overlayfs_setup(const Fstab & fstab,const char * mount_point,bool * want_reboot,bool just_disabled_verity)665 bool fs_mgr_overlayfs_setup(const Fstab& fstab, const char* mount_point, bool* want_reboot,
666                             bool just_disabled_verity) {
667     if (!OverlayfsSetupAllowed(/*verbose=*/true)) {
668         return false;
669     }
670 
671     if (!fs_mgr_boot_completed()) {
672         LOG(ERROR) << "Cannot setup overlayfs before persistent properties are ready";
673         return false;
674     }
675 
676     auto candidates = fs_mgr_overlayfs_candidate_list(fstab);
677     for (auto it = candidates.begin(); it != candidates.end();) {
678         if (mount_point &&
679             (fs_mgr_mount_point(it->mount_point) != fs_mgr_mount_point(mount_point))) {
680             it = candidates.erase(it);
681             continue;
682         }
683 
684         auto verity_enabled = !just_disabled_verity && fs_mgr_is_verity_enabled(*it);
685         if (verity_enabled) {
686             it = candidates.erase(it);
687             continue;
688         }
689         ++it;
690     }
691 
692     if (candidates.empty()) {
693         if (mount_point) {
694             LOG(ERROR) << "No overlayfs candidate was found for " << mount_point;
695             return false;
696         }
697         return true;
698     }
699 
700     std::string dir;
701     for (const auto& overlay_mount_point : OverlayMountPoints()) {
702         if (overlay_mount_point == kScratchMountPoint) {
703             if (!fs_mgr_overlayfs_setup_scratch(fstab)) {
704                 continue;
705             }
706         } else {
707             if (!fs_mgr_overlayfs_already_mounted(overlay_mount_point, false /* overlay */)) {
708                 continue;
709             }
710         }
711         dir = overlay_mount_point;
712         break;
713     }
714     if (dir.empty()) {
715         LOG(ERROR) << "Could not allocate backing storage for overlays";
716         return false;
717     }
718 
719     const auto overlay = fs_mgr_overlayfs_setup_dir(dir);
720     if (overlay.empty()) {
721         return false;
722     }
723 
724     bool ok = true;
725     for (const auto& entry : candidates) {
726         auto fstab_mount_point = fs_mgr_mount_point(entry.mount_point);
727         ok &= fs_mgr_overlayfs_setup_one(overlay, fstab_mount_point, want_reboot);
728     }
729     return ok;
730 }
731 
732 struct MapInfo {
733     // If set, partition is owned by ImageManager.
734     std::unique_ptr<IImageManager> images;
735     // If set, and images is null, this is a DAP partition.
736     std::string name;
737     // If set, and images and name are empty, this is a non-dynamic partition.
738     std::string device;
739 
740     MapInfo() = default;
741     MapInfo(MapInfo&&) = default;
~MapInfoMapInfo742     ~MapInfo() {
743         if (images) {
744             images->UnmapImageDevice(name);
745         } else if (!name.empty()) {
746             DestroyLogicalPartition(name);
747         }
748     }
749 };
750 
751 // Note: This function never returns the DSU scratch device in recovery or fastbootd,
752 // because the DSU scratch is created in the first-stage-mount, which is not run in recovery.
EnsureScratchMapped()753 static std::optional<MapInfo> EnsureScratchMapped() {
754     MapInfo info;
755     info.device = GetBootScratchDevice();
756     if (!info.device.empty()) {
757         return {std::move(info)};
758     }
759     if (!InRecovery()) {
760         return {};
761     }
762 
763     auto partition_name = android::base::Basename(kScratchMountPoint);
764 
765     // Check for scratch on /data first, before looking for a modified super
766     // partition. We should only reach this code in recovery, because scratch
767     // would otherwise always be mapped.
768     auto images = IImageManager::Open("remount", 10s);
769     if (images && images->BackingImageExists(partition_name)) {
770         if (images->IsImageDisabled(partition_name)) {
771             return {};
772         }
773         if (!images->MapImageDevice(partition_name, 10s, &info.device)) {
774             return {};
775         }
776         info.name = partition_name;
777         info.images = std::move(images);
778         return {std::move(info)};
779     }
780 
781     // Avoid uart spam by first checking for a scratch partition.
782     const auto super_device = kPhysicalDevice + fs_mgr_get_super_partition_name();
783     auto metadata = ReadCurrentMetadata(super_device);
784     if (!metadata) {
785         return {};
786     }
787 
788     auto partition = FindPartition(*metadata.get(), partition_name);
789     if (!partition) {
790         return {};
791     }
792 
793     CreateLogicalPartitionParams params = {
794             .block_device = super_device,
795             .metadata = metadata.get(),
796             .partition = partition,
797             .force_writable = true,
798             .timeout_ms = 10s,
799     };
800     if (!CreateLogicalPartition(params, &info.device)) {
801         return {};
802     }
803     info.name = partition_name;
804     return {std::move(info)};
805 }
806 
807 // This should only be reachable in recovery, where DSU scratch is not
808 // automatically mapped.
MapDsuScratchDevice(std::string * device)809 static bool MapDsuScratchDevice(std::string* device) {
810     std::string dsu_slot;
811     if (!android::gsi::IsGsiInstalled() || !android::gsi::GetActiveDsu(&dsu_slot) ||
812         dsu_slot.empty()) {
813         // Nothing to do if no DSU installation present.
814         return false;
815     }
816 
817     auto images = IImageManager::Open("dsu/" + dsu_slot, 10s);
818     if (!images || !images->BackingImageExists(android::gsi::kDsuScratch)) {
819         // Nothing to do if DSU scratch device doesn't exist.
820         return false;
821     }
822 
823     images->UnmapImageDevice(android::gsi::kDsuScratch);
824     if (!images->MapImageDevice(android::gsi::kDsuScratch, 10s, device)) {
825         return false;
826     }
827     return true;
828 }
829 
TeardownMountsAndScratch(const char * mount_point,bool * want_reboot)830 static OverlayfsTeardownResult TeardownMountsAndScratch(const char* mount_point,
831                                                         bool* want_reboot) {
832     bool should_destroy_scratch = false;
833     auto rv = OverlayfsTeardownResult::Ok;
834     for (const auto& overlay_mount_point : OverlayMountPoints()) {
835         auto ok = fs_mgr_overlayfs_teardown_one(
836                 overlay_mount_point, mount_point ? fs_mgr_mount_point(mount_point) : "",
837                 want_reboot,
838                 overlay_mount_point == kScratchMountPoint ? &should_destroy_scratch : nullptr);
839         if (!ok) {
840             rv = OverlayfsTeardownResult::Error;
841         }
842     }
843 
844     // Do not attempt to destroy DSU scratch if within a DSU system,
845     // because DSU scratch partition is managed by gsid.
846     if (should_destroy_scratch && !fs_mgr_is_dsu_running()) {
847         auto rv = fs_mgr_overlayfs_teardown_scratch(kScratchMountPoint, want_reboot);
848         if (rv != OverlayfsTeardownResult::Ok) {
849             return rv;
850         }
851     }
852     // And now that we did what we could, lets inform
853     // caller that there may still be more to do.
854     if (!fs_mgr_boot_completed()) {
855         LOG(ERROR) << "Cannot teardown overlayfs before persistent properties are ready";
856         return OverlayfsTeardownResult::Error;
857     }
858     return rv;
859 }
860 
861 // Returns false if teardown not permitted. If something is altered, set *want_reboot.
fs_mgr_overlayfs_teardown(const char * mount_point,bool * want_reboot)862 OverlayfsTeardownResult fs_mgr_overlayfs_teardown(const char* mount_point, bool* want_reboot) {
863     if (!OverlayfsTeardownAllowed()) {
864         // Nothing to teardown.
865         return OverlayfsTeardownResult::Ok;
866     }
867     // If scratch exists, but is not mounted, lets gain access to clean
868     // specific override entries.
869     auto mount_scratch = false;
870     if ((mount_point != nullptr) && !fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) {
871         std::string scratch_device = GetBootScratchDevice();
872         if (!scratch_device.empty()) {
873             mount_scratch = MountScratch(scratch_device);
874         }
875     }
876 
877     auto rv = TeardownMountsAndScratch(mount_point, want_reboot);
878 
879     if (mount_scratch) {
880         if (!fs_mgr_overlayfs_umount_scratch()) {
881             return OverlayfsTeardownResult::Busy;
882         }
883     }
884     return rv;
885 }
886 
887 namespace android {
888 namespace fs_mgr {
889 
MapScratchPartitionIfNeeded(Fstab * fstab,const std::function<bool (const std::set<std::string> &)> & init)890 void MapScratchPartitionIfNeeded(Fstab* fstab,
891                                  const std::function<bool(const std::set<std::string>&)>& init) {
892     if (!OverlayfsSetupAllowed()) {
893         return;
894     }
895     if (GetEntryForMountPoint(fstab, kScratchMountPoint) != nullptr) {
896         return;
897     }
898 
899     if (!GetOverlaysActiveFlag()) {
900         return;
901     }
902     if (ScratchIsOnData()) {
903         if (auto images = IImageManager::Open("remount", 0ms)) {
904             images->MapAllImages(init);
905         }
906     }
907 
908     // Physical or logical partitions will have already been mapped here,
909     // so just ensure /dev/block symlinks exist.
910     auto device = GetBootScratchDevice();
911     if (!device.empty()) {
912         init({android::base::Basename(device)});
913     }
914 }
915 
CleanupOldScratchFiles()916 void CleanupOldScratchFiles() {
917     if (!OverlayfsTeardownAllowed()) {
918         return;
919     }
920     if (!ScratchIsOnData()) {
921         return;
922     }
923     if (auto images = IImageManager::Open("remount", 0ms)) {
924         images->RemoveDisabledImages();
925         if (!GetOverlaysActiveFlag()) {
926             fs_mgr_overlayfs_teardown_scratch(kScratchMountPoint, nullptr);
927         }
928     }
929 }
930 
931 // This returns the scratch device that was detected during early boot (first-
932 // stage init). If the device was created later, for example during setup for
933 // the adb remount command, it can return an empty string since it does not
934 // query ImageManager. (Note that ImageManager in first-stage init will always
935 // use device-mapper, since /data is not available to use loop devices.)
GetBootScratchDevice()936 std::string GetBootScratchDevice() {
937     // Note: fs_mgr_is_dsu_running() always returns false in recovery or fastbootd.
938     if (fs_mgr_is_dsu_running()) {
939         return GetDsuScratchDevice();
940     }
941 
942     auto& dm = DeviceMapper::Instance();
943 
944     // If there is a scratch partition allocated in /data or on super, we
945     // automatically prioritize that over super_other or system_other.
946     // Some devices, for example, have a write-protected eMMC and the
947     // super partition cannot be used even if it exists.
948     std::string device;
949     auto partition_name = android::base::Basename(kScratchMountPoint);
950     if (dm.GetState(partition_name) != DmDeviceState::INVALID &&
951         dm.GetDmDevicePathByName(partition_name, &device)) {
952         return device;
953     }
954 
955     return "";
956 }
957 
TeardownAllOverlayForMountPoint(const std::string & mount_point)958 void TeardownAllOverlayForMountPoint(const std::string& mount_point) {
959     if (!OverlayfsTeardownAllowed()) {
960         return;
961     }
962     if (!InRecovery()) {
963         LERROR << __FUNCTION__ << "(): must be called within recovery.";
964         return;
965     }
966 
967     // Empty string means teardown everything.
968     const std::string teardown_dir = mount_point.empty() ? "" : fs_mgr_mount_point(mount_point);
969     constexpr bool* ignore_change = nullptr;
970 
971     // Teardown legacy overlay mount points that's not backed by a scratch device.
972     for (const auto& overlay_mount_point : OverlayMountPoints()) {
973         if (overlay_mount_point == kScratchMountPoint) {
974             continue;
975         }
976         fs_mgr_overlayfs_teardown_one(overlay_mount_point, teardown_dir, ignore_change);
977     }
978 
979     if (mount_point.empty()) {
980         // Throw away the entire partition.
981         auto partition_name = android::base::Basename(kScratchMountPoint);
982         auto images = IImageManager::Open("remount", 10s);
983         if (images && images->BackingImageExists(partition_name)) {
984             if (images->DisableImage(partition_name)) {
985                 LOG(INFO) << "Disabled scratch partition for: " << kScratchMountPoint;
986             } else {
987                 LOG(ERROR) << "Unable to disable scratch partition for " << kScratchMountPoint;
988             }
989         }
990     }
991 
992     // Note if we just disabled scratch, this mount will fail.
993     if (auto info = EnsureScratchMapped(); info.has_value()) {
994         // Map scratch device, mount kScratchMountPoint and teardown kScratchMountPoint.
995         fs_mgr_overlayfs_umount_scratch();
996         if (MountScratch(info->device)) {
997             bool should_destroy_scratch = false;
998             fs_mgr_overlayfs_teardown_one(kScratchMountPoint, teardown_dir, ignore_change,
999                                           &should_destroy_scratch);
1000             fs_mgr_overlayfs_umount_scratch();
1001             if (should_destroy_scratch) {
1002                 fs_mgr_overlayfs_teardown_scratch(kScratchMountPoint, nullptr);
1003             }
1004         }
1005     }
1006 
1007     // Teardown DSU overlay if present.
1008     std::string scratch_device;
1009     if (MapDsuScratchDevice(&scratch_device)) {
1010         fs_mgr_overlayfs_umount_scratch();
1011         if (MountScratch(scratch_device)) {
1012             fs_mgr_overlayfs_teardown_one(kScratchMountPoint, teardown_dir, ignore_change);
1013             fs_mgr_overlayfs_umount_scratch();
1014         }
1015         DestroyLogicalPartition(android::gsi::kDsuScratch);
1016     }
1017 }
1018 
1019 }  // namespace fs_mgr
1020 }  // namespace android
1021