xref: /aosp_15_r20/system/core/fs_mgr/fs_mgr_overlayfs_control.cpp (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
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 + " -b "s;
391         command += std::to_string(fs_mgr_f2fs_ideal_block_size());
392         command += " -f -d1 -l" + android::base::Basename(kScratchMountPoint);
393     } else if (!access(kMkExt4, X_OK) && fs_mgr_filesystem_available("ext4")) {
394         fs_type = "ext4";
395         command = kMkExt4 + " -F -b 4096 -t ext4 -m 0 -O has_journal -M "s + kScratchMountPoint;
396     } else {
397         LERROR << "No supported mkfs command or filesystem driver available, supported filesystems "
398                   "are: f2fs, ext4";
399         return false;
400     }
401     command += " " + scratch_device + " >/dev/null 2>/dev/null </dev/null";
402     fs_mgr_set_blk_ro(scratch_device, false);
403     auto ret = system(command.c_str());
404     if (ret) {
405         LERROR << "make " << fs_type << " filesystem on " << scratch_device << " return=" << ret;
406         return false;
407     }
408     return true;
409 }
410 
TruncatePartitionsWithSuffix(MetadataBuilder * builder,const std::string & suffix)411 static void TruncatePartitionsWithSuffix(MetadataBuilder* builder, const std::string& suffix) {
412     auto& dm = DeviceMapper::Instance();
413 
414     // Remove <other> partitions
415     for (const auto& group : builder->ListGroups()) {
416         for (const auto& part : builder->ListPartitionsInGroup(group)) {
417             const auto& name = part->name();
418             if (!android::base::EndsWith(name, suffix)) {
419                 continue;
420             }
421             if (dm.GetState(name) != DmDeviceState::INVALID && !DestroyLogicalPartition(name)) {
422                 continue;
423             }
424             builder->ResizePartition(builder->FindPartition(name), 0);
425         }
426     }
427 }
428 
429 // Create or update a scratch partition within super.
CreateDynamicScratch(std::string * scratch_device,bool * partition_exists)430 static bool CreateDynamicScratch(std::string* scratch_device, bool* partition_exists) {
431     const auto partition_name = android::base::Basename(kScratchMountPoint);
432 
433     auto& dm = DeviceMapper::Instance();
434     *partition_exists = dm.GetState(partition_name) != DmDeviceState::INVALID;
435 
436     auto partition_create = !*partition_exists;
437     auto slot_number = fs_mgr_overlayfs_slot_number();
438     const auto super_device = kPhysicalDevice + fs_mgr_get_super_partition_name();
439     auto builder = MetadataBuilder::New(super_device, slot_number);
440     if (!builder) {
441         LERROR << "open " << super_device << " metadata";
442         return false;
443     }
444     auto partition = builder->FindPartition(partition_name);
445     *partition_exists = partition != nullptr;
446     auto changed = false;
447     if (!*partition_exists) {
448         partition = builder->AddPartition(partition_name, LP_PARTITION_ATTR_NONE);
449         if (!partition) {
450             LERROR << "create " << partition_name;
451             return false;
452         }
453         changed = true;
454     }
455     // Take half of free space, minimum 512MB or maximum free - margin.
456     static constexpr auto kMinimumSize = uint64_t(512 * 1024 * 1024);
457     if (partition->size() < kMinimumSize) {
458         auto partition_size =
459                 builder->AllocatableSpace() - builder->UsedSpace() + partition->size();
460         if ((partition_size > kMinimumSize) || !partition->size()) {
461             partition_size = std::max(std::min(kMinimumSize, partition_size), partition_size / 2);
462             if (partition_size > partition->size()) {
463                 if (!builder->ResizePartition(partition, partition_size)) {
464                     // Try to free up space by deallocating partitions in the other slot.
465                     TruncatePartitionsWithSuffix(builder.get(), fs_mgr_get_other_slot_suffix());
466 
467                     partition_size =
468                             builder->AllocatableSpace() - builder->UsedSpace() + partition->size();
469                     partition_size =
470                             std::max(std::min(kMinimumSize, partition_size), partition_size / 2);
471                     if (!builder->ResizePartition(partition, partition_size)) {
472                         LERROR << "resize " << partition_name;
473                         return false;
474                     }
475                 }
476                 if (!partition_create) DestroyLogicalPartition(partition_name);
477                 changed = true;
478                 *partition_exists = false;
479             }
480         }
481     }
482 
483     // land the update back on to the partition
484     if (changed) {
485         auto metadata = builder->Export();
486         if (!metadata || !UpdatePartitionTable(super_device, *metadata.get(), slot_number)) {
487             LERROR << "add partition " << partition_name;
488             return false;
489         }
490     }
491 
492     if (changed || partition_create) {
493         CreateLogicalPartitionParams params = {
494                 .block_device = super_device,
495                 .metadata_slot = slot_number,
496                 .partition_name = partition_name,
497                 .force_writable = true,
498                 .timeout_ms = 10s,
499         };
500         if (!CreateLogicalPartition(params, scratch_device)) {
501             return false;
502         }
503     } else if (scratch_device->empty()) {
504         *scratch_device = GetBootScratchDevice();
505     }
506     return true;
507 }
508 
GetIdealDataScratchSize()509 static inline uint64_t GetIdealDataScratchSize() {
510     BlockDeviceInfo super_info;
511     PartitionOpener opener;
512     if (!opener.GetInfo(fs_mgr_get_super_partition_name(), &super_info)) {
513         LERROR << "could not get block device info for super";
514         return 0;
515     }
516 
517     struct statvfs s;
518     if (statvfs("/data", &s) < 0) {
519         PERROR << "could not statfs /data";
520         return 0;
521     }
522 
523     auto ideal_size = std::min(super_info.size, uint64_t(uint64_t(s.f_frsize) * s.f_bfree * 0.85));
524 
525     // Align up to the filesystem block size.
526     if (auto remainder = ideal_size % s.f_bsize; remainder > 0) {
527         ideal_size += s.f_bsize - remainder;
528     }
529     return ideal_size;
530 }
531 
CreateScratchOnData(std::string * scratch_device,bool * partition_exists)532 static bool CreateScratchOnData(std::string* scratch_device, bool* partition_exists) {
533     *partition_exists = false;
534 
535     auto images = IImageManager::Open("remount", 10s);
536     if (!images) {
537         return false;
538     }
539 
540     auto partition_name = android::base::Basename(kScratchMountPoint);
541     if (images->GetMappedImageDevice(partition_name, scratch_device)) {
542         *partition_exists = true;
543         return true;
544     }
545 
546     // Note: calling RemoveDisabledImages here ensures that we do not race with
547     // clean_scratch_files and accidentally try to map an image that will be
548     // deleted.
549     if (!images->RemoveDisabledImages()) {
550         return false;
551     }
552     if (!images->BackingImageExists(partition_name)) {
553         auto size = android::base::GetUintProperty<uint64_t>(kDataScratchSizeMbProp, 0) * 1_MiB;
554         if (!size) {
555             size = GetIdealDataScratchSize();
556         }
557         if (!size) {
558             size = 2_GiB;
559         }
560 
561         auto flags = IImageManager::CREATE_IMAGE_DEFAULT;
562 
563         if (!images->CreateBackingImage(partition_name, size, flags)) {
564             LERROR << "could not create scratch image of " << size << " bytes";
565             return false;
566         }
567     }
568     if (!images->MapImageDevice(partition_name, 10s, scratch_device)) {
569         LERROR << "could not map scratch image";
570         // If we cannot use this image, then remove it.
571         TeardownDataScratch(images.get(), partition_name, false /* was_mounted */);
572         return false;
573     }
574     return true;
575 }
576 
CanUseSuperPartition(const Fstab & fstab)577 static bool CanUseSuperPartition(const Fstab& fstab) {
578     auto slot_number = fs_mgr_overlayfs_slot_number();
579     const auto super_device = kPhysicalDevice + fs_mgr_get_super_partition_name();
580     if (access(super_device.c_str(), R_OK | W_OK) || !fs_mgr_overlayfs_has_logical(fstab)) {
581         return false;
582     }
583     auto metadata = ReadMetadata(super_device, slot_number);
584     if (!metadata) {
585         return false;
586     }
587     return true;
588 }
589 
fs_mgr_overlayfs_create_scratch(const Fstab & fstab,std::string * scratch_device,bool * partition_exists)590 bool fs_mgr_overlayfs_create_scratch(const Fstab& fstab, std::string* scratch_device,
591                                      bool* partition_exists) {
592     // Use the DSU scratch device managed by gsid if within a DSU system.
593     if (fs_mgr_is_dsu_running()) {
594         *scratch_device = GetDsuScratchDevice();
595         *partition_exists = !scratch_device->empty();
596         return *partition_exists;
597     }
598 
599     // Try ImageManager on /data first.
600     bool can_use_data = false;
601     if (FilesystemHasReliablePinning("/data", &can_use_data) && can_use_data) {
602         if (CreateScratchOnData(scratch_device, partition_exists)) {
603             return true;
604         }
605         LOG(WARNING) << "Failed to allocate scratch on /data, fallback to use free space on super";
606     }
607     // If that fails, see if we can land on super.
608     if (CanUseSuperPartition(fstab)) {
609         return CreateDynamicScratch(scratch_device, partition_exists);
610     }
611     return false;
612 }
613 
614 // Create and mount kScratchMountPoint storage if we have logical partitions
fs_mgr_overlayfs_setup_scratch(const Fstab & fstab)615 bool fs_mgr_overlayfs_setup_scratch(const Fstab& fstab) {
616     if (fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) {
617         return true;
618     }
619 
620     std::string scratch_device;
621     bool partition_exists;
622     if (!fs_mgr_overlayfs_create_scratch(fstab, &scratch_device, &partition_exists)) {
623         LOG(ERROR) << "Failed to create scratch partition";
624         return false;
625     }
626 
627     if (!SetOverlaysActiveFlag(true)) {
628         LOG(ERROR) << "Failed to update dynamic partition data";
629         fs_mgr_overlayfs_teardown_scratch(kScratchMountPoint, nullptr);
630         return false;
631     }
632 
633     // If the partition exists, assume first that it can be mounted.
634     if (partition_exists) {
635         if (MountScratch(scratch_device)) {
636             const auto top = kScratchMountPoint + "/"s + kOverlayTopDir;
637             if (access(top.c_str(), F_OK) == 0 || fs_mgr_filesystem_has_space(kScratchMountPoint)) {
638                 return true;
639             }
640             // declare it useless, no overrides and no free space
641             if (!fs_mgr_overlayfs_umount_scratch()) {
642                 LOG(ERROR) << "Unable to unmount scratch partition";
643                 return false;
644             }
645         }
646     }
647 
648     if (!MakeScratchFilesystem(scratch_device)) {
649         LOG(ERROR) << "Failed to format scratch partition";
650         return false;
651     }
652 
653     return MountScratch(scratch_device);
654 }
655 
OverlayfsTeardownAllowed()656 constexpr bool OverlayfsTeardownAllowed() {
657     // Never allow on non-debuggable build.
658     return kAllowOverlayfs;
659 }
660 
661 }  // namespace
662 
fs_mgr_overlayfs_setup(const Fstab & fstab,const char * mount_point,bool * want_reboot,bool just_disabled_verity)663 bool fs_mgr_overlayfs_setup(const Fstab& fstab, const char* mount_point, bool* want_reboot,
664                             bool just_disabled_verity) {
665     if (!OverlayfsSetupAllowed(/*verbose=*/true)) {
666         return false;
667     }
668 
669     if (!fs_mgr_boot_completed()) {
670         LOG(ERROR) << "Cannot setup overlayfs before persistent properties are ready";
671         return false;
672     }
673 
674     auto candidates = fs_mgr_overlayfs_candidate_list(fstab);
675     for (auto it = candidates.begin(); it != candidates.end();) {
676         if (mount_point &&
677             (fs_mgr_mount_point(it->mount_point) != fs_mgr_mount_point(mount_point))) {
678             it = candidates.erase(it);
679             continue;
680         }
681 
682         auto verity_enabled = !just_disabled_verity && fs_mgr_is_verity_enabled(*it);
683         if (verity_enabled) {
684             it = candidates.erase(it);
685             continue;
686         }
687         ++it;
688     }
689 
690     if (candidates.empty()) {
691         if (mount_point) {
692             LOG(ERROR) << "No overlayfs candidate was found for " << mount_point;
693             return false;
694         }
695         return true;
696     }
697 
698     std::string dir;
699     for (const auto& overlay_mount_point : OverlayMountPoints()) {
700         if (overlay_mount_point == kScratchMountPoint) {
701             if (!fs_mgr_overlayfs_setup_scratch(fstab)) {
702                 continue;
703             }
704         } else {
705             if (!fs_mgr_overlayfs_already_mounted(overlay_mount_point, false /* overlay */)) {
706                 continue;
707             }
708         }
709         dir = overlay_mount_point;
710         break;
711     }
712     if (dir.empty()) {
713         LOG(ERROR) << "Could not allocate backing storage for overlays";
714         return false;
715     }
716 
717     const auto overlay = fs_mgr_overlayfs_setup_dir(dir);
718     if (overlay.empty()) {
719         return false;
720     }
721 
722     bool ok = true;
723     for (const auto& entry : candidates) {
724         auto fstab_mount_point = fs_mgr_mount_point(entry.mount_point);
725         ok &= fs_mgr_overlayfs_setup_one(overlay, fstab_mount_point, want_reboot);
726     }
727     return ok;
728 }
729 
730 struct MapInfo {
731     // If set, partition is owned by ImageManager.
732     std::unique_ptr<IImageManager> images;
733     // If set, and images is null, this is a DAP partition.
734     std::string name;
735     // If set, and images and name are empty, this is a non-dynamic partition.
736     std::string device;
737 
738     MapInfo() = default;
739     MapInfo(MapInfo&&) = default;
~MapInfoMapInfo740     ~MapInfo() {
741         if (images) {
742             images->UnmapImageDevice(name);
743         } else if (!name.empty()) {
744             DestroyLogicalPartition(name);
745         }
746     }
747 };
748 
749 // Note: This function never returns the DSU scratch device in recovery or fastbootd,
750 // because the DSU scratch is created in the first-stage-mount, which is not run in recovery.
EnsureScratchMapped()751 static std::optional<MapInfo> EnsureScratchMapped() {
752     MapInfo info;
753     info.device = GetBootScratchDevice();
754     if (!info.device.empty()) {
755         return {std::move(info)};
756     }
757     if (!InRecovery()) {
758         return {};
759     }
760 
761     auto partition_name = android::base::Basename(kScratchMountPoint);
762 
763     // Check for scratch on /data first, before looking for a modified super
764     // partition. We should only reach this code in recovery, because scratch
765     // would otherwise always be mapped.
766     auto images = IImageManager::Open("remount", 10s);
767     if (images && images->BackingImageExists(partition_name)) {
768         if (images->IsImageDisabled(partition_name)) {
769             return {};
770         }
771         if (!images->MapImageDevice(partition_name, 10s, &info.device)) {
772             return {};
773         }
774         info.name = partition_name;
775         info.images = std::move(images);
776         return {std::move(info)};
777     }
778 
779     // Avoid uart spam by first checking for a scratch partition.
780     const auto super_device = kPhysicalDevice + fs_mgr_get_super_partition_name();
781     auto metadata = ReadCurrentMetadata(super_device);
782     if (!metadata) {
783         return {};
784     }
785 
786     auto partition = FindPartition(*metadata.get(), partition_name);
787     if (!partition) {
788         return {};
789     }
790 
791     CreateLogicalPartitionParams params = {
792             .block_device = super_device,
793             .metadata = metadata.get(),
794             .partition = partition,
795             .force_writable = true,
796             .timeout_ms = 10s,
797     };
798     if (!CreateLogicalPartition(params, &info.device)) {
799         return {};
800     }
801     info.name = partition_name;
802     return {std::move(info)};
803 }
804 
805 // This should only be reachable in recovery, where DSU scratch is not
806 // automatically mapped.
MapDsuScratchDevice(std::string * device)807 static bool MapDsuScratchDevice(std::string* device) {
808     std::string dsu_slot;
809     if (!android::gsi::IsGsiInstalled() || !android::gsi::GetActiveDsu(&dsu_slot) ||
810         dsu_slot.empty()) {
811         // Nothing to do if no DSU installation present.
812         return false;
813     }
814 
815     auto images = IImageManager::Open("dsu/" + dsu_slot, 10s);
816     if (!images || !images->BackingImageExists(android::gsi::kDsuScratch)) {
817         // Nothing to do if DSU scratch device doesn't exist.
818         return false;
819     }
820 
821     images->UnmapImageDevice(android::gsi::kDsuScratch);
822     if (!images->MapImageDevice(android::gsi::kDsuScratch, 10s, device)) {
823         return false;
824     }
825     return true;
826 }
827 
TeardownMountsAndScratch(const char * mount_point,bool * want_reboot)828 static OverlayfsTeardownResult TeardownMountsAndScratch(const char* mount_point,
829                                                         bool* want_reboot) {
830     bool should_destroy_scratch = false;
831     auto rv = OverlayfsTeardownResult::Ok;
832     for (const auto& overlay_mount_point : OverlayMountPoints()) {
833         auto ok = fs_mgr_overlayfs_teardown_one(
834                 overlay_mount_point, mount_point ? fs_mgr_mount_point(mount_point) : "",
835                 want_reboot,
836                 overlay_mount_point == kScratchMountPoint ? &should_destroy_scratch : nullptr);
837         if (!ok) {
838             rv = OverlayfsTeardownResult::Error;
839         }
840     }
841 
842     // Do not attempt to destroy DSU scratch if within a DSU system,
843     // because DSU scratch partition is managed by gsid.
844     if (should_destroy_scratch && !fs_mgr_is_dsu_running()) {
845         auto rv = fs_mgr_overlayfs_teardown_scratch(kScratchMountPoint, want_reboot);
846         if (rv != OverlayfsTeardownResult::Ok) {
847             return rv;
848         }
849     }
850     // And now that we did what we could, lets inform
851     // caller that there may still be more to do.
852     if (!fs_mgr_boot_completed()) {
853         LOG(ERROR) << "Cannot teardown overlayfs before persistent properties are ready";
854         return OverlayfsTeardownResult::Error;
855     }
856     return rv;
857 }
858 
859 // Returns false if teardown not permitted. If something is altered, set *want_reboot.
fs_mgr_overlayfs_teardown(const char * mount_point,bool * want_reboot)860 OverlayfsTeardownResult fs_mgr_overlayfs_teardown(const char* mount_point, bool* want_reboot) {
861     if (!OverlayfsTeardownAllowed()) {
862         // Nothing to teardown.
863         return OverlayfsTeardownResult::Ok;
864     }
865     // If scratch exists, but is not mounted, lets gain access to clean
866     // specific override entries.
867     auto mount_scratch = false;
868     if ((mount_point != nullptr) && !fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) {
869         std::string scratch_device = GetBootScratchDevice();
870         if (!scratch_device.empty()) {
871             mount_scratch = MountScratch(scratch_device);
872         }
873     }
874 
875     auto rv = TeardownMountsAndScratch(mount_point, want_reboot);
876 
877     if (mount_scratch) {
878         if (!fs_mgr_overlayfs_umount_scratch()) {
879             return OverlayfsTeardownResult::Busy;
880         }
881     }
882     return rv;
883 }
884 
885 namespace android {
886 namespace fs_mgr {
887 
MapScratchPartitionIfNeeded(Fstab * fstab,const std::function<bool (const std::set<std::string> &)> & init)888 void MapScratchPartitionIfNeeded(Fstab* fstab,
889                                  const std::function<bool(const std::set<std::string>&)>& init) {
890     if (!OverlayfsSetupAllowed()) {
891         return;
892     }
893     if (GetEntryForMountPoint(fstab, kScratchMountPoint) != nullptr) {
894         return;
895     }
896 
897     if (!GetOverlaysActiveFlag()) {
898         return;
899     }
900     if (ScratchIsOnData()) {
901         if (auto images = IImageManager::Open("remount", 0ms)) {
902             images->MapAllImages(init);
903         }
904     }
905 
906     // Physical or logical partitions will have already been mapped here,
907     // so just ensure /dev/block symlinks exist.
908     auto device = GetBootScratchDevice();
909     if (!device.empty()) {
910         init({android::base::Basename(device)});
911     }
912 }
913 
CleanupOldScratchFiles()914 void CleanupOldScratchFiles() {
915     if (!OverlayfsTeardownAllowed()) {
916         return;
917     }
918     if (!ScratchIsOnData()) {
919         return;
920     }
921     if (auto images = IImageManager::Open("remount", 0ms)) {
922         images->RemoveDisabledImages();
923         if (!GetOverlaysActiveFlag()) {
924             fs_mgr_overlayfs_teardown_scratch(kScratchMountPoint, nullptr);
925         }
926     }
927 }
928 
929 // This returns the scratch device that was detected during early boot (first-
930 // stage init). If the device was created later, for example during setup for
931 // the adb remount command, it can return an empty string since it does not
932 // query ImageManager. (Note that ImageManager in first-stage init will always
933 // use device-mapper, since /data is not available to use loop devices.)
GetBootScratchDevice()934 std::string GetBootScratchDevice() {
935     // Note: fs_mgr_is_dsu_running() always returns false in recovery or fastbootd.
936     if (fs_mgr_is_dsu_running()) {
937         return GetDsuScratchDevice();
938     }
939 
940     auto& dm = DeviceMapper::Instance();
941 
942     // If there is a scratch partition allocated in /data or on super, we
943     // automatically prioritize that over super_other or system_other.
944     // Some devices, for example, have a write-protected eMMC and the
945     // super partition cannot be used even if it exists.
946     std::string device;
947     auto partition_name = android::base::Basename(kScratchMountPoint);
948     if (dm.GetState(partition_name) != DmDeviceState::INVALID &&
949         dm.GetDmDevicePathByName(partition_name, &device)) {
950         return device;
951     }
952 
953     return "";
954 }
955 
TeardownAllOverlayForMountPoint(const std::string & mount_point)956 void TeardownAllOverlayForMountPoint(const std::string& mount_point) {
957     if (!OverlayfsTeardownAllowed()) {
958         return;
959     }
960     if (!InRecovery()) {
961         LERROR << __FUNCTION__ << "(): must be called within recovery.";
962         return;
963     }
964 
965     // Empty string means teardown everything.
966     const std::string teardown_dir = mount_point.empty() ? "" : fs_mgr_mount_point(mount_point);
967     constexpr bool* ignore_change = nullptr;
968 
969     // Teardown legacy overlay mount points that's not backed by a scratch device.
970     for (const auto& overlay_mount_point : OverlayMountPoints()) {
971         if (overlay_mount_point == kScratchMountPoint) {
972             continue;
973         }
974         fs_mgr_overlayfs_teardown_one(overlay_mount_point, teardown_dir, ignore_change);
975     }
976 
977     if (mount_point.empty()) {
978         // Throw away the entire partition.
979         auto partition_name = android::base::Basename(kScratchMountPoint);
980         auto images = IImageManager::Open("remount", 10s);
981         if (images && images->BackingImageExists(partition_name)) {
982             if (images->DisableImage(partition_name)) {
983                 LOG(INFO) << "Disabled scratch partition for: " << kScratchMountPoint;
984             } else {
985                 LOG(ERROR) << "Unable to disable scratch partition for " << kScratchMountPoint;
986             }
987         }
988     }
989 
990     // Note if we just disabled scratch, this mount will fail.
991     if (auto info = EnsureScratchMapped(); info.has_value()) {
992         // Map scratch device, mount kScratchMountPoint and teardown kScratchMountPoint.
993         fs_mgr_overlayfs_umount_scratch();
994         if (MountScratch(info->device)) {
995             bool should_destroy_scratch = false;
996             fs_mgr_overlayfs_teardown_one(kScratchMountPoint, teardown_dir, ignore_change,
997                                           &should_destroy_scratch);
998             fs_mgr_overlayfs_umount_scratch();
999             if (should_destroy_scratch) {
1000                 fs_mgr_overlayfs_teardown_scratch(kScratchMountPoint, nullptr);
1001             }
1002         }
1003     }
1004 
1005     // Teardown DSU overlay if present.
1006     std::string scratch_device;
1007     if (MapDsuScratchDevice(&scratch_device)) {
1008         fs_mgr_overlayfs_umount_scratch();
1009         if (MountScratch(scratch_device)) {
1010             fs_mgr_overlayfs_teardown_one(kScratchMountPoint, teardown_dir, ignore_change);
1011             fs_mgr_overlayfs_umount_scratch();
1012         }
1013         DestroyLogicalPartition(android::gsi::kDsuScratch);
1014     }
1015 }
1016 
1017 }  // namespace fs_mgr
1018 }  // namespace android
1019