blob: 6863894957de569243fa24be00d78014803a24cf [file] [log] [blame]
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001/*
2 * Copyright (C) 2012 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
Mark Salyzynd9e6c202018-06-20 14:08:09 -070017#include "fs_mgr.h"
18
Mattias Nissler097b6bb2016-03-31 16:32:09 +020019#include <ctype.h>
20#include <dirent.h>
21#include <errno.h>
22#include <fcntl.h>
Tom Cherryfafbb642018-11-29 13:24:09 -080023#include <inttypes.h>
Mattias Nissler097b6bb2016-03-31 16:32:09 +020024#include <libgen.h>
Ken Sumrallc1bf8962012-01-06 19:09:42 -080025#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
liminghao9a0fd1d2016-07-22 11:48:14 +080028#include <sys/ioctl.h>
Ken Sumrallc1bf8962012-01-06 19:09:42 -080029#include <sys/mount.h>
30#include <sys/stat.h>
Mattias Nissler097b6bb2016-03-31 16:32:09 +020031#include <sys/swap.h>
Ken Sumrallc1bf8962012-01-06 19:09:42 -080032#include <sys/types.h>
33#include <sys/wait.h>
Ken Sumrallc1bf8962012-01-06 19:09:42 -080034#include <time.h>
Mattias Nissler097b6bb2016-03-31 16:32:09 +020035#include <unistd.h>
Ken Sumrallc1bf8962012-01-06 19:09:42 -080036
Bart Van Asscheec5f6352021-07-29 13:50:43 -070037#include <array>
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +000038#include <chrono>
Mark Salyzynb5065fc2018-06-27 14:57:10 -070039#include <functional>
Bowgo Tsaic1bc2812018-11-26 17:49:23 +080040#include <map>
Bowgo Tsaiaaf70e72017-03-02 00:03:56 +080041#include <memory>
Paul Crowleyc6846962018-01-30 09:56:03 -080042#include <string>
Bart Van Asscheec5f6352021-07-29 13:50:43 -070043#include <string_view>
Jinguang Dong9d344962017-06-13 10:20:34 +080044#include <thread>
Mark Salyzynbe296732018-10-05 09:00:55 -070045#include <utility>
Paul Crowleyc6846962018-01-30 09:56:03 -080046#include <vector>
Bowgo Tsaiaaf70e72017-03-02 00:03:56 +080047
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +000048#include <android-base/chrono_utils.h>
Keun-young Park3fbf94e2017-03-02 14:33:04 -080049#include <android-base/file.h>
Bowgo Tsaiaaf70e72017-03-02 00:03:56 +080050#include <android-base/properties.h>
Keun-young Park3fbf94e2017-03-02 14:33:04 -080051#include <android-base/stringprintf.h>
Paul Crowleyc6846962018-01-30 09:56:03 -080052#include <android-base/strings.h>
bowgotsaicea7ea72017-01-16 21:49:49 +080053#include <android-base/unique_fd.h>
Jeff Sharkey47dc2362018-01-07 19:17:39 -070054#include <cutils/android_filesystem_config.h>
JP Abgrall4bb7bba2014-06-19 22:12:20 -070055#include <cutils/android_reboot.h>
Ken Sumrallc1bf8962012-01-06 19:09:42 -080056#include <cutils/partition_utils.h>
57#include <cutils/properties.h>
Tao Bao6d881d62016-10-05 17:53:30 -070058#include <ext4_utils/ext4.h>
Tao Bao6d881d62016-10-05 17:53:30 -070059#include <ext4_utils/ext4_sb.h>
60#include <ext4_utils/ext4_utils.h>
61#include <ext4_utils/wipe.h>
Bowgo Tsaic1bc2812018-11-26 17:49:23 +080062#include <fs_avb/fs_avb.h>
David Anderson5c475c72019-06-11 17:40:49 -070063#include <fs_mgr/file_wait.h>
Mark Salyzynd9e6c202018-06-20 14:08:09 -070064#include <fs_mgr_overlayfs.h>
Paul Crowley7160fc12019-10-25 17:12:45 -070065#include <fscrypt/fscrypt.h>
David Anderson40b59482018-06-25 17:55:01 -070066#include <libdm/dm.h>
Nikita Ioffebcaeb702020-04-20 17:38:17 +010067#include <libdm/loop_control.h>
David Anderson5cbd2e42018-09-27 10:53:04 -070068#include <liblp/metadata_format.h>
liminghao9a0fd1d2016-07-22 11:48:14 +080069#include <linux/fs.h>
Mattias Nissler097b6bb2016-03-31 16:32:09 +020070#include <linux/loop.h>
Keun-young Park6000a3f2017-04-11 18:59:56 -070071#include <linux/magic.h>
Steven Morelandd73be1b2017-04-13 23:48:57 -070072#include <log/log_properties.h>
Ken Sumrallbf021b42013-03-19 19:38:44 -070073#include <logwrap/logwrap.h>
Geremy Condra3ad3d1c2013-02-22 18:11:41 -080074
Bart Van Assche0223cd82021-08-06 10:21:12 -070075#include "blockdev.h"
Ken Sumrallc1bf8962012-01-06 19:09:42 -080076#include "fs_mgr_priv.h"
77
Ken Sumrallc1bf8962012-01-06 19:09:42 -080078#define E2FSCK_BIN "/system/bin/e2fsck"
liminghao9a0fd1d2016-07-22 11:48:14 +080079#define F2FS_FSCK_BIN "/system/bin/fsck.f2fs"
Ken Sumrall5bc31a22013-07-08 19:11:55 -070080#define MKSWAP_BIN "/system/bin/mkswap"
liminghao9a0fd1d2016-07-22 11:48:14 +080081#define TUNE2FS_BIN "/system/bin/tune2fs"
Jaegeuk Kim78f040c2020-02-11 15:22:46 -080082#define RESIZE2FS_BIN "/system/bin/resize2fs"
Ken Sumrall5bc31a22013-07-08 19:11:55 -070083
Ken Sumrall4eaf9052013-09-18 17:49:21 -070084#define FSCK_LOG_FILE "/dev/fscklogs/log"
85
Ken Sumrall5bc31a22013-07-08 19:11:55 -070086#define ZRAM_CONF_DEV "/sys/block/zram0/disksize"
Peter Enderborg4d217f02016-08-26 15:09:35 +020087#define ZRAM_CONF_MCS "/sys/block/zram0/max_comp_streams"
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080088#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
Ken Sumrallc1bf8962012-01-06 19:09:42 -080089
Leo Liou0b721d32019-01-15 20:43:37 +080090#define SYSFS_EXT4_VERITY "/sys/fs/ext4/features/verity"
Daniel Rosenberg8775ce02019-11-19 20:30:06 -080091#define SYSFS_EXT4_CASEFOLD "/sys/fs/ext4/features/casefold"
Leo Liou0b721d32019-01-15 20:43:37 +080092
Paul Crowley7160fc12019-10-25 17:12:45 -070093// FIXME: this should be in system/extras
94#define EXT4_FEATURE_COMPAT_STABLE_INODES 0x0800
95
Ken Sumrallbf021b42013-03-19 19:38:44 -070096#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
97
Tom Cherrycf80b6d2019-01-07 14:25:31 -080098using android::base::Basename;
Nikita Ioffed572c802019-12-09 21:13:08 +000099using android::base::GetBoolProperty;
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000100using android::base::GetUintProperty;
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800101using android::base::Realpath;
Jaegeuk Kim24d2a292020-02-27 11:28:45 -0800102using android::base::SetProperty;
Tom Cherry0d2621f2018-12-04 13:15:09 -0800103using android::base::StartsWith;
Bart Van Asscheec5f6352021-07-29 13:50:43 -0700104using android::base::StringPrintf;
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +0000105using android::base::Timer;
Tom Cherry0d2621f2018-12-04 13:15:09 -0800106using android::base::unique_fd;
David Anderson35638622018-08-27 14:02:47 -0700107using android::dm::DeviceMapper;
108using android::dm::DmDeviceState;
David Anderson671bd812020-01-24 19:19:27 -0800109using android::dm::DmTargetLinear;
Nikita Ioffebcaeb702020-04-20 17:38:17 +0100110using android::dm::LoopControl;
Tom Cherrya3530e62019-01-30 13:25:35 -0800111
112// Realistically, this file should be part of the android::fs_mgr namespace;
113using namespace android::fs_mgr;
David Anderson40b59482018-06-25 17:55:01 -0700114
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800115using namespace std::literals;
116
Keun-young Park3fbf94e2017-03-02 14:33:04 -0800117// record fs stat
118enum FsStatFlags {
Keun-young Park6000a3f2017-04-11 18:59:56 -0700119 FS_STAT_IS_EXT4 = 0x0001,
Keun-young Park3fbf94e2017-03-02 14:33:04 -0800120 FS_STAT_NEW_IMAGE_VERSION = 0x0002,
Keun-young Park6000a3f2017-04-11 18:59:56 -0700121 FS_STAT_E2FSCK_F_ALWAYS = 0x0004,
122 FS_STAT_UNCLEAN_SHUTDOWN = 0x0008,
123 FS_STAT_QUOTA_ENABLED = 0x0010,
Keun-young Park6000a3f2017-04-11 18:59:56 -0700124 FS_STAT_RO_MOUNT_FAILED = 0x0040,
Keun-young Park3fbf94e2017-03-02 14:33:04 -0800125 FS_STAT_RO_UNMOUNT_FAILED = 0x0080,
126 FS_STAT_FULL_MOUNT_FAILED = 0x0100,
Keun-young Park6000a3f2017-04-11 18:59:56 -0700127 FS_STAT_E2FSCK_FAILED = 0x0200,
128 FS_STAT_E2FSCK_FS_FIXED = 0x0400,
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800129 FS_STAT_INVALID_MAGIC = 0x0800,
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700130 FS_STAT_TOGGLE_QUOTAS_FAILED = 0x10000,
131 FS_STAT_SET_RESERVED_BLOCKS_FAILED = 0x20000,
Eric Biggerse9811f32017-07-05 12:21:15 -0700132 FS_STAT_ENABLE_ENCRYPTION_FAILED = 0x40000,
Leo Liou0b721d32019-01-15 20:43:37 +0800133 FS_STAT_ENABLE_VERITY_FAILED = 0x80000,
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800134 FS_STAT_ENABLE_CASEFOLD_FAILED = 0x100000,
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800135 FS_STAT_ENABLE_METADATA_CSUM_FAILED = 0x200000,
Keun-young Park3fbf94e2017-03-02 14:33:04 -0800136};
137
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800138static void log_fs_stat(const std::string& blk_device, int fs_stat) {
Keun-young Park3fbf94e2017-03-02 14:33:04 -0800139 if ((fs_stat & FS_STAT_IS_EXT4) == 0) return; // only log ext4
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800140 std::string msg =
141 android::base::StringPrintf("\nfs_stat,%s,0x%x\n", blk_device.c_str(), fs_stat);
Keun-young Park3fbf94e2017-03-02 14:33:04 -0800142 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(FSCK_LOG_FILE, O_WRONLY | O_CLOEXEC |
143 O_APPEND | O_CREAT, 0664)));
144 if (fd == -1 || !android::base::WriteStringToFd(msg, fd)) {
145 LWARNING << __FUNCTION__ << "() cannot log " << msg;
146 }
147}
148
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700149static bool is_extfs(const std::string& fs_type) {
150 return fs_type == "ext4" || fs_type == "ext3" || fs_type == "ext2";
151}
152
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800153static bool is_f2fs(const std::string& fs_type) {
154 return fs_type == "f2fs";
155}
156
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800157static std::string realpath(const std::string& blk_device) {
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800158 std::string real_path;
159 if (!Realpath(blk_device, &real_path)) {
160 real_path = blk_device;
161 }
162 return real_path;
163}
164
Keun-young Park40db04d2017-04-13 17:31:08 -0700165static bool should_force_check(int fs_stat) {
Eric Biggerse9811f32017-07-05 12:21:15 -0700166 return fs_stat &
167 (FS_STAT_E2FSCK_F_ALWAYS | FS_STAT_UNCLEAN_SHUTDOWN | FS_STAT_QUOTA_ENABLED |
168 FS_STAT_RO_MOUNT_FAILED | FS_STAT_RO_UNMOUNT_FAILED | FS_STAT_FULL_MOUNT_FAILED |
169 FS_STAT_E2FSCK_FAILED | FS_STAT_TOGGLE_QUOTAS_FAILED |
170 FS_STAT_SET_RESERVED_BLOCKS_FAILED | FS_STAT_ENABLE_ENCRYPTION_FAILED);
Keun-young Park40db04d2017-04-13 17:31:08 -0700171}
172
Jaegeuk Kimbdb981d2021-12-07 11:23:52 -0800173static bool umount_retry(const std::string& mount_point) {
174 int retry_count = 5;
175 bool umounted = false;
176
177 while (retry_count-- > 0) {
178 umounted = umount(mount_point.c_str()) == 0;
179 if (umounted) {
180 LINFO << __FUNCTION__ << "(): unmount(" << mount_point << ") succeeded";
181 break;
182 }
183 PERROR << __FUNCTION__ << "(): umount(" << mount_point << ") failed";
184 if (retry_count) sleep(1);
185 }
186 return umounted;
187}
188
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800189static void check_fs(const std::string& blk_device, const std::string& fs_type,
190 const std::string& target, int* fs_stat) {
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800191 int status;
Ken Sumrall5dc5bfe2012-07-23 19:34:00 -0700192 int ret;
193 long tmpmnt_flags = MS_NOATIME | MS_NOEXEC | MS_NOSUID;
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800194 auto tmpmnt_opts = "errors=remount-ro"s;
195 const char* e2fsck_argv[] = {E2FSCK_BIN, "-y", blk_device.c_str()};
196 const char* e2fsck_forced_argv[] = {E2FSCK_BIN, "-f", "-y", blk_device.c_str()};
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800197
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800198 if (*fs_stat & FS_STAT_INVALID_MAGIC) { // will fail, so do not try
199 return;
200 }
201
Jaegeuk Kim24d2a292020-02-27 11:28:45 -0800202 Timer t;
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800203 /* Check for the types of filesystems we know how to check */
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700204 if (is_extfs(fs_type)) {
Ken Sumrall5dc5bfe2012-07-23 19:34:00 -0700205 /*
206 * First try to mount and unmount the filesystem. We do this because
207 * the kernel is more efficient than e2fsck in running the journal and
208 * processing orphaned inodes, and on at least one device with a
209 * performance issue in the emmc firmware, it can take e2fsck 2.5 minutes
210 * to do what the kernel does in about a second.
211 *
212 * After mounting and unmounting the filesystem, run e2fsck, and if an
213 * error is recorded in the filesystem superblock, e2fsck will do a full
214 * check. Otherwise, it does nothing. If the kernel cannot mount the
215 * filesytsem due to an error, e2fsck is still run to do a full check
216 * fix the filesystem.
217 */
Keun-young Park40db04d2017-04-13 17:31:08 -0700218 if (!(*fs_stat & FS_STAT_FULL_MOUNT_FAILED)) { // already tried if full mount failed
219 errno = 0;
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800220 if (fs_type == "ext4") {
Keun-young Park40db04d2017-04-13 17:31:08 -0700221 // This option is only valid with ext4
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800222 tmpmnt_opts += ",nomblk_io_submit";
Nick Kralevich7294eb62015-02-05 16:02:42 -0800223 }
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800224 ret = mount(blk_device.c_str(), target.c_str(), fs_type.c_str(), tmpmnt_flags,
225 tmpmnt_opts.c_str());
Keun-young Park40db04d2017-04-13 17:31:08 -0700226 PINFO << __FUNCTION__ << "(): mount(" << blk_device << "," << target << "," << fs_type
227 << ")=" << ret;
Jaegeuk Kimbdb981d2021-12-07 11:23:52 -0800228 if (ret) {
Keun-young Park40db04d2017-04-13 17:31:08 -0700229 *fs_stat |= FS_STAT_RO_MOUNT_FAILED;
Jaegeuk Kimbdb981d2021-12-07 11:23:52 -0800230 } else if (!umount_retry(target)) {
231 // boot may fail but continue and leave it to later stage for now.
232 PERROR << __FUNCTION__ << "(): umount(" << target << ") timed out";
233 *fs_stat |= FS_STAT_RO_UNMOUNT_FAILED;
Keun-young Park40db04d2017-04-13 17:31:08 -0700234 }
Ken Sumrall5dc5bfe2012-07-23 19:34:00 -0700235 }
236
David 'Digit' Turner28483d72014-02-17 11:14:44 +0100237 /*
238 * Some system images do not have e2fsck for licensing reasons
239 * (e.g. recent SDK system images). Detect these and skip the check.
240 */
241 if (access(E2FSCK_BIN, X_OK)) {
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800242 LINFO << "Not running " << E2FSCK_BIN << " on " << realpath(blk_device)
bowgotsai47878de2017-01-23 14:04:34 +0800243 << " (executable not in system image)";
David 'Digit' Turner28483d72014-02-17 11:14:44 +0100244 } else {
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800245 LINFO << "Running " << E2FSCK_BIN << " on " << realpath(blk_device);
Keun-young Park40db04d2017-04-13 17:31:08 -0700246 if (should_force_check(*fs_stat)) {
Tom Cherry3a803eb2019-09-25 16:23:50 -0700247 ret = logwrap_fork_execvp(ARRAY_SIZE(e2fsck_forced_argv), e2fsck_forced_argv,
Wei Wang02e89ec2020-02-14 14:22:16 -0800248 &status, false, LOG_KLOG | LOG_FILE, false,
249 FSCK_LOG_FILE);
Keun-young Park40db04d2017-04-13 17:31:08 -0700250 } else {
Tom Cherry3a803eb2019-09-25 16:23:50 -0700251 ret = logwrap_fork_execvp(ARRAY_SIZE(e2fsck_argv), e2fsck_argv, &status, false,
Wei Wang02e89ec2020-02-14 14:22:16 -0800252 LOG_KLOG | LOG_FILE, false, FSCK_LOG_FILE);
Keun-young Park40db04d2017-04-13 17:31:08 -0700253 }
Ken Sumrallbf021b42013-03-19 19:38:44 -0700254
David 'Digit' Turner28483d72014-02-17 11:14:44 +0100255 if (ret < 0) {
256 /* No need to check for error in fork, we can't really handle it now */
bowgotsai47878de2017-01-23 14:04:34 +0800257 LERROR << "Failed trying to run " << E2FSCK_BIN;
Keun-young Park3fbf94e2017-03-02 14:33:04 -0800258 *fs_stat |= FS_STAT_E2FSCK_FAILED;
259 } else if (status != 0) {
260 LINFO << "e2fsck returned status 0x" << std::hex << status;
261 *fs_stat |= FS_STAT_E2FSCK_FS_FIXED;
David 'Digit' Turner28483d72014-02-17 11:14:44 +0100262 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800263 }
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800264 } else if (is_f2fs(fs_type)) {
Jaegeuk Kimc461e162020-01-03 14:09:41 -0800265 const char* f2fs_fsck_argv[] = {F2FS_FSCK_BIN, "-a", "-c", "10000", "--debug-cache",
266 blk_device.c_str()};
267 const char* f2fs_fsck_forced_argv[] = {
268 F2FS_FSCK_BIN, "-f", "-c", "10000", "--debug-cache", blk_device.c_str()};
JP Abgrall12351582014-06-17 17:01:14 -0700269
Sahitya Tummala5928e4f2019-05-23 16:23:58 +0530270 if (should_force_check(*fs_stat)) {
jiahaobfcee282021-04-16 17:07:50 +0800271 LINFO << "Running " << F2FS_FSCK_BIN << " -f -c 10000 --debug-cache "
Jaegeuk Kimc461e162020-01-03 14:09:41 -0800272 << realpath(blk_device);
Tom Cherry3a803eb2019-09-25 16:23:50 -0700273 ret = logwrap_fork_execvp(ARRAY_SIZE(f2fs_fsck_forced_argv), f2fs_fsck_forced_argv,
Jaegeuk Kimd595de52021-12-30 16:48:44 -0800274 &status, false, LOG_KLOG | LOG_FILE, false, nullptr);
Sahitya Tummala5928e4f2019-05-23 16:23:58 +0530275 } else {
jiahaobfcee282021-04-16 17:07:50 +0800276 LINFO << "Running " << F2FS_FSCK_BIN << " -a -c 10000 --debug-cache "
Jaegeuk Kimc461e162020-01-03 14:09:41 -0800277 << realpath(blk_device);
Tom Cherry3a803eb2019-09-25 16:23:50 -0700278 ret = logwrap_fork_execvp(ARRAY_SIZE(f2fs_fsck_argv), f2fs_fsck_argv, &status, false,
Jaegeuk Kimd595de52021-12-30 16:48:44 -0800279 LOG_KLOG | LOG_FILE, false, nullptr);
Sahitya Tummala5928e4f2019-05-23 16:23:58 +0530280 }
JP Abgrall12351582014-06-17 17:01:14 -0700281 if (ret < 0) {
282 /* No need to check for error in fork, we can't really handle it now */
bowgotsai47878de2017-01-23 14:04:34 +0800283 LERROR << "Failed trying to run " << F2FS_FSCK_BIN;
JP Abgrall12351582014-06-17 17:01:14 -0700284 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800285 }
Jaegeuk Kim24d2a292020-02-27 11:28:45 -0800286 android::base::SetProperty("ro.boottime.init.fsck." + Basename(target),
287 std::to_string(t.duration().count()));
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800288 return;
289}
290
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700291static ext4_fsblk_t ext4_blocks_count(const struct ext4_super_block* es) {
liminghao9a0fd1d2016-07-22 11:48:14 +0800292 return ((ext4_fsblk_t)le32_to_cpu(es->s_blocks_count_hi) << 32) |
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700293 le32_to_cpu(es->s_blocks_count_lo);
liminghao9a0fd1d2016-07-22 11:48:14 +0800294}
295
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700296static ext4_fsblk_t ext4_r_blocks_count(const struct ext4_super_block* es) {
liminghao9a0fd1d2016-07-22 11:48:14 +0800297 return ((ext4_fsblk_t)le32_to_cpu(es->s_r_blocks_count_hi) << 32) |
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700298 le32_to_cpu(es->s_r_blocks_count_lo);
liminghao9a0fd1d2016-07-22 11:48:14 +0800299}
300
katao4e8d73f2017-07-05 16:00:54 +0800301static bool is_ext4_superblock_valid(const struct ext4_super_block* es) {
302 if (es->s_magic != EXT4_SUPER_MAGIC) return false;
303 if (es->s_rev_level != EXT4_DYNAMIC_REV && es->s_rev_level != EXT4_GOOD_OLD_REV) return false;
304 if (EXT4_INODES_PER_GROUP(es) == 0) return false;
305 return true;
306}
307
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700308// Read the primary superblock from an ext4 filesystem. On failure return
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800309// false. If it's not an ext4 filesystem, also set FS_STAT_INVALID_MAGIC.
Eric Biggersdc3e8972020-08-04 11:11:13 -0700310static bool read_ext4_superblock(const std::string& blk_device, struct ext4_super_block* sb,
311 int* fs_stat) {
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800312 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
Jeff Sharkey6d896102016-12-14 12:00:51 -0700313
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700314 if (fd < 0) {
315 PERROR << "Failed to open '" << blk_device << "'";
316 return false;
Jeff Sharkey6d896102016-12-14 12:00:51 -0700317 }
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700318
Mark Salyzyn60a76f32019-03-14 15:34:35 -0700319 if (TEMP_FAILURE_RETRY(pread(fd, sb, sizeof(*sb), 1024)) != sizeof(*sb)) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700320 PERROR << "Can't read '" << blk_device << "' superblock";
321 return false;
322 }
323
katao4e8d73f2017-07-05 16:00:54 +0800324 if (!is_ext4_superblock_valid(sb)) {
325 LINFO << "Invalid ext4 superblock on '" << blk_device << "'";
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700326 // not a valid fs, tune2fs, fsck, and mount will all fail.
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800327 *fs_stat |= FS_STAT_INVALID_MAGIC;
Eric Biggersdc3e8972020-08-04 11:11:13 -0700328 return false;
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700329 }
330 *fs_stat |= FS_STAT_IS_EXT4;
331 LINFO << "superblock s_max_mnt_count:" << sb->s_max_mnt_count << "," << blk_device;
332 if (sb->s_max_mnt_count == 0xffff) { // -1 (int16) in ext2, but uint16 in ext4
333 *fs_stat |= FS_STAT_NEW_IMAGE_VERSION;
334 }
335 return true;
Jeff Sharkey6d896102016-12-14 12:00:51 -0700336}
337
Mark Salyzyn60a76f32019-03-14 15:34:35 -0700338// exported silent version of the above that just answer the question is_ext4
339bool fs_mgr_is_ext4(const std::string& blk_device) {
340 android::base::ErrnoRestorer restore;
341 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
342 if (fd < 0) return false;
343 ext4_super_block sb;
344 if (TEMP_FAILURE_RETRY(pread(fd, &sb, sizeof(sb), 1024)) != sizeof(sb)) return false;
345 if (!is_ext4_superblock_valid(&sb)) return false;
346 return true;
347}
348
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700349// Some system images do not have tune2fs for licensing reasons.
350// Detect these and skip running it.
351static bool tune2fs_available(void) {
352 return access(TUNE2FS_BIN, X_OK) == 0;
353}
354
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800355static bool run_command(const char* argv[], int argc) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700356 int ret;
357
Wei Wang02e89ec2020-02-14 14:22:16 -0800358 ret = logwrap_fork_execvp(argc, argv, nullptr, false, LOG_KLOG, false, nullptr);
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700359 return ret == 0;
360}
361
362// Enable/disable quota support on the filesystem if needed.
Tom Cherry23319eb2018-11-30 16:16:05 -0800363static void tune_quota(const std::string& blk_device, const FstabEntry& entry,
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700364 const struct ext4_super_block* sb, int* fs_stat) {
365 bool has_quota = (sb->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_RO_COMPAT_QUOTA)) != 0;
Tom Cherry23319eb2018-11-30 16:16:05 -0800366 bool want_quota = entry.fs_mgr_flags.quota;
Shikha Malhotrabc9b8472021-12-29 16:26:18 +0000367 // Enable projid support by default
368 bool want_projid = true;
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700369 if (has_quota == want_quota) {
370 return;
371 }
372
373 if (!tune2fs_available()) {
374 LERROR << "Unable to " << (want_quota ? "enable" : "disable") << " quotas on " << blk_device
375 << " because " TUNE2FS_BIN " is missing";
376 return;
377 }
378
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800379 const char* argv[] = {TUNE2FS_BIN, nullptr, nullptr, blk_device.c_str()};
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700380
381 if (want_quota) {
382 LINFO << "Enabling quotas on " << blk_device;
383 argv[1] = "-Oquota";
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800384 // Once usr/grp unneeded, make just prjquota to save overhead
385 if (want_projid)
386 argv[2] = "-Qusrquota,grpquota,prjquota";
387 else
388 argv[2] = "-Qusrquota,grpquota";
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700389 *fs_stat |= FS_STAT_QUOTA_ENABLED;
390 } else {
391 LINFO << "Disabling quotas on " << blk_device;
392 argv[1] = "-O^quota";
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800393 argv[2] = "-Q^usrquota,^grpquota,^prjquota";
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700394 }
395
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800396 if (!run_command(argv, ARRAY_SIZE(argv))) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700397 LERROR << "Failed to run " TUNE2FS_BIN " to " << (want_quota ? "enable" : "disable")
398 << " quotas on " << blk_device;
399 *fs_stat |= FS_STAT_TOGGLE_QUOTAS_FAILED;
400 }
401}
402
403// Set the number of reserved filesystem blocks if needed.
Tom Cherry23319eb2018-11-30 16:16:05 -0800404static void tune_reserved_size(const std::string& blk_device, const FstabEntry& entry,
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700405 const struct ext4_super_block* sb, int* fs_stat) {
Martijn Coenen20c4cfa2019-05-10 10:39:54 +0200406 if (entry.reserved_size == 0) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700407 return;
408 }
409
410 // The size to reserve is given in the fstab, but we won't reserve more
411 // than 2% of the filesystem.
412 const uint64_t max_reserved_blocks = ext4_blocks_count(sb) * 0.02;
Tom Cherry23319eb2018-11-30 16:16:05 -0800413 uint64_t reserved_blocks = entry.reserved_size / EXT4_BLOCK_SIZE(sb);
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700414
415 if (reserved_blocks > max_reserved_blocks) {
416 LWARNING << "Reserved blocks " << reserved_blocks << " is too large; "
417 << "capping to " << max_reserved_blocks;
418 reserved_blocks = max_reserved_blocks;
419 }
420
Jeff Sharkey47dc2362018-01-07 19:17:39 -0700421 if ((ext4_r_blocks_count(sb) == reserved_blocks) && (sb->s_def_resgid == AID_RESERVED_DISK)) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700422 return;
423 }
424
425 if (!tune2fs_available()) {
426 LERROR << "Unable to set the number of reserved blocks on " << blk_device
427 << " because " TUNE2FS_BIN " is missing";
428 return;
429 }
430
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700431 LINFO << "Setting reserved block count on " << blk_device << " to " << reserved_blocks;
Jeff Sharkey47dc2362018-01-07 19:17:39 -0700432
433 auto reserved_blocks_str = std::to_string(reserved_blocks);
434 auto reserved_gid_str = std::to_string(AID_RESERVED_DISK);
435 const char* argv[] = {
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800436 TUNE2FS_BIN, "-r", reserved_blocks_str.c_str(), "-g", reserved_gid_str.c_str(),
437 blk_device.c_str()};
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800438 if (!run_command(argv, ARRAY_SIZE(argv))) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700439 LERROR << "Failed to run " TUNE2FS_BIN " to set the number of reserved blocks on "
440 << blk_device;
441 *fs_stat |= FS_STAT_SET_RESERVED_BLOCKS_FAILED;
442 }
443}
444
Eric Biggerse9811f32017-07-05 12:21:15 -0700445// Enable file-based encryption if needed.
Tom Cherry23319eb2018-11-30 16:16:05 -0800446static void tune_encrypt(const std::string& blk_device, const FstabEntry& entry,
Eric Biggerse9811f32017-07-05 12:21:15 -0700447 const struct ext4_super_block* sb, int* fs_stat) {
Paul Crowley7160fc12019-10-25 17:12:45 -0700448 if (!entry.fs_mgr_flags.file_encryption) {
449 return; // Nothing needs done.
450 }
451 std::vector<std::string> features_needed;
452 if ((sb->s_feature_incompat & cpu_to_le32(EXT4_FEATURE_INCOMPAT_ENCRYPT)) == 0) {
453 features_needed.emplace_back("encrypt");
454 }
455 android::fscrypt::EncryptionOptions options;
456 if (!android::fscrypt::ParseOptions(entry.encryption_options, &options)) {
457 LERROR << "Unable to parse encryption options on " << blk_device << ": "
458 << entry.encryption_options;
Eric Biggerse9811f32017-07-05 12:21:15 -0700459 return;
460 }
Paul Crowleyc2f37682020-05-20 16:36:15 -0700461 if ((options.flags &
462 (FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 | FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32)) != 0) {
Paul Crowley7160fc12019-10-25 17:12:45 -0700463 // We can only use this policy on ext4 if the "stable_inodes" feature
464 // is set on the filesystem, otherwise shrinking will break encrypted files.
465 if ((sb->s_feature_compat & cpu_to_le32(EXT4_FEATURE_COMPAT_STABLE_INODES)) == 0) {
466 features_needed.emplace_back("stable_inodes");
467 }
468 }
469 if (features_needed.size() == 0) {
470 return;
471 }
Eric Biggerse9811f32017-07-05 12:21:15 -0700472 if (!tune2fs_available()) {
473 LERROR << "Unable to enable ext4 encryption on " << blk_device
474 << " because " TUNE2FS_BIN " is missing";
475 return;
476 }
477
Paul Crowley7160fc12019-10-25 17:12:45 -0700478 auto flags = android::base::Join(features_needed, ',');
479 auto flag_arg = "-O"s + flags;
480 const char* argv[] = {TUNE2FS_BIN, flag_arg.c_str(), blk_device.c_str()};
Eric Biggerse9811f32017-07-05 12:21:15 -0700481
Paul Crowley7160fc12019-10-25 17:12:45 -0700482 LINFO << "Enabling ext4 flags " << flags << " on " << blk_device;
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800483 if (!run_command(argv, ARRAY_SIZE(argv))) {
Eric Biggerse9811f32017-07-05 12:21:15 -0700484 LERROR << "Failed to run " TUNE2FS_BIN " to enable "
Paul Crowley7160fc12019-10-25 17:12:45 -0700485 << "ext4 flags " << flags << " on " << blk_device;
Eric Biggerse9811f32017-07-05 12:21:15 -0700486 *fs_stat |= FS_STAT_ENABLE_ENCRYPTION_FAILED;
487 }
488}
489
Leo Liou0b721d32019-01-15 20:43:37 +0800490// Enable fs-verity if needed.
491static void tune_verity(const std::string& blk_device, const FstabEntry& entry,
492 const struct ext4_super_block* sb, int* fs_stat) {
493 bool has_verity = (sb->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_RO_COMPAT_VERITY)) != 0;
494 bool want_verity = entry.fs_mgr_flags.fs_verity;
495
496 if (has_verity || !want_verity) {
497 return;
498 }
499
500 std::string verity_support;
501 if (!android::base::ReadFileToString(SYSFS_EXT4_VERITY, &verity_support)) {
502 LERROR << "Failed to open " << SYSFS_EXT4_VERITY;
503 return;
504 }
505
506 if (!(android::base::Trim(verity_support) == "supported")) {
507 LERROR << "Current ext4 verity not supported by kernel";
508 return;
509 }
510
511 if (!tune2fs_available()) {
512 LERROR << "Unable to enable ext4 verity on " << blk_device
513 << " because " TUNE2FS_BIN " is missing";
514 return;
515 }
516
517 LINFO << "Enabling ext4 verity on " << blk_device;
518
519 const char* argv[] = {TUNE2FS_BIN, "-O", "verity", blk_device.c_str()};
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800520 if (!run_command(argv, ARRAY_SIZE(argv))) {
Leo Liou0b721d32019-01-15 20:43:37 +0800521 LERROR << "Failed to run " TUNE2FS_BIN " to enable "
522 << "ext4 verity on " << blk_device;
523 *fs_stat |= FS_STAT_ENABLE_VERITY_FAILED;
524 }
525}
526
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800527// Enable casefold if needed.
Jaegeuk Kim5ba5b902020-08-14 12:34:36 -0700528static void tune_casefold(const std::string& blk_device, const FstabEntry& entry,
529 const struct ext4_super_block* sb, int* fs_stat) {
Eric Biggers91bcfd82020-02-25 11:11:35 -0800530 bool has_casefold = (sb->s_feature_incompat & cpu_to_le32(EXT4_FEATURE_INCOMPAT_CASEFOLD)) != 0;
Martijn Coenenea751d92020-04-15 11:45:05 +0200531 bool wants_casefold =
532 android::base::GetBoolProperty("external_storage.casefold.enabled", false);
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800533
Yongqin Liuc007c432020-10-23 13:29:19 +0800534 if (entry.mount_point != "/data" || !wants_casefold || has_casefold) return;
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800535
536 std::string casefold_support;
537 if (!android::base::ReadFileToString(SYSFS_EXT4_CASEFOLD, &casefold_support)) {
538 LERROR << "Failed to open " << SYSFS_EXT4_CASEFOLD;
539 return;
540 }
541
542 if (!(android::base::Trim(casefold_support) == "supported")) {
543 LERROR << "Current ext4 casefolding not supported by kernel";
544 return;
545 }
546
547 if (!tune2fs_available()) {
548 LERROR << "Unable to enable ext4 casefold on " << blk_device
549 << " because " TUNE2FS_BIN " is missing";
550 return;
551 }
552
553 LINFO << "Enabling ext4 casefold on " << blk_device;
554
555 const char* argv[] = {TUNE2FS_BIN, "-O", "casefold", "-E", "encoding=utf8", blk_device.c_str()};
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800556 if (!run_command(argv, ARRAY_SIZE(argv))) {
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800557 LERROR << "Failed to run " TUNE2FS_BIN " to enable "
558 << "ext4 casefold on " << blk_device;
559 *fs_stat |= FS_STAT_ENABLE_CASEFOLD_FAILED;
560 }
561}
562
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800563static bool resize2fs_available(void) {
564 return access(RESIZE2FS_BIN, X_OK) == 0;
565}
566
567// Enable metadata_csum
568static void tune_metadata_csum(const std::string& blk_device, const FstabEntry& entry,
569 const struct ext4_super_block* sb, int* fs_stat) {
570 bool has_meta_csum =
571 (sb->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) != 0;
572 bool want_meta_csum = entry.fs_mgr_flags.ext_meta_csum;
573
574 if (has_meta_csum || !want_meta_csum) return;
575
576 if (!tune2fs_available()) {
577 LERROR << "Unable to enable metadata_csum on " << blk_device
578 << " because " TUNE2FS_BIN " is missing";
579 return;
580 }
581 if (!resize2fs_available()) {
582 LERROR << "Unable to enable metadata_csum on " << blk_device
583 << " because " RESIZE2FS_BIN " is missing";
584 return;
585 }
586
587 LINFO << "Enabling ext4 metadata_csum on " << blk_device;
588
Tom Cherry2d451662020-07-27 11:20:29 -0700589 // Must give `-T now` to prevent last_fsck_time from growing too large,
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800590 // otherwise, tune2fs won't enable metadata_csum.
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800591 const char* tune2fs_args[] = {TUNE2FS_BIN, "-O", "metadata_csum,64bit,extent",
Jaegeuk Kim52838162020-02-24 19:58:22 -0800592 "-T", "now", blk_device.c_str()};
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800593 const char* resize2fs_args[] = {RESIZE2FS_BIN, "-b", blk_device.c_str()};
594
595 if (!run_command(tune2fs_args, ARRAY_SIZE(tune2fs_args))) {
596 LERROR << "Failed to run " TUNE2FS_BIN " to enable "
597 << "ext4 metadata_csum on " << blk_device;
598 *fs_stat |= FS_STAT_ENABLE_METADATA_CSUM_FAILED;
599 } else if (!run_command(resize2fs_args, ARRAY_SIZE(resize2fs_args))) {
600 LERROR << "Failed to run " RESIZE2FS_BIN " to enable "
601 << "ext4 metadata_csum on " << blk_device;
602 *fs_stat |= FS_STAT_ENABLE_METADATA_CSUM_FAILED;
603 }
604}
605
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800606// Read the primary superblock from an f2fs filesystem. On failure return
607// false. If it's not an f2fs filesystem, also set FS_STAT_INVALID_MAGIC.
608#define F2FS_BLKSIZE 4096
609#define F2FS_SUPER_OFFSET 1024
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800610static bool read_f2fs_superblock(const std::string& blk_device, int* fs_stat) {
611 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800612 __le32 sb1, sb2;
613
614 if (fd < 0) {
615 PERROR << "Failed to open '" << blk_device << "'";
616 return false;
617 }
618
Mark Salyzyn60a76f32019-03-14 15:34:35 -0700619 if (TEMP_FAILURE_RETRY(pread(fd, &sb1, sizeof(sb1), F2FS_SUPER_OFFSET)) != sizeof(sb1)) {
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800620 PERROR << "Can't read '" << blk_device << "' superblock1";
621 return false;
622 }
Mark Salyzyn60a76f32019-03-14 15:34:35 -0700623 if (TEMP_FAILURE_RETRY(pread(fd, &sb2, sizeof(sb2), F2FS_BLKSIZE + F2FS_SUPER_OFFSET)) !=
624 sizeof(sb2)) {
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800625 PERROR << "Can't read '" << blk_device << "' superblock2";
626 return false;
627 }
628
629 if (sb1 != cpu_to_le32(F2FS_SUPER_MAGIC) && sb2 != cpu_to_le32(F2FS_SUPER_MAGIC)) {
630 LINFO << "Invalid f2fs superblock on '" << blk_device << "'";
631 *fs_stat |= FS_STAT_INVALID_MAGIC;
632 return false;
633 }
634 return true;
635}
636
Mark Salyzyn60a76f32019-03-14 15:34:35 -0700637// exported silent version of the above that just answer the question is_f2fs
638bool fs_mgr_is_f2fs(const std::string& blk_device) {
639 android::base::ErrnoRestorer restore;
640 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
641 if (fd < 0) return false;
642 __le32 sb;
643 if (TEMP_FAILURE_RETRY(pread(fd, &sb, sizeof(sb), F2FS_SUPER_OFFSET)) != sizeof(sb)) {
644 return false;
645 }
646 if (sb == cpu_to_le32(F2FS_SUPER_MAGIC)) return true;
647 if (TEMP_FAILURE_RETRY(pread(fd, &sb, sizeof(sb), F2FS_BLKSIZE + F2FS_SUPER_OFFSET)) !=
648 sizeof(sb)) {
649 return false;
650 }
651 return sb == cpu_to_le32(F2FS_SUPER_MAGIC);
652}
653
Jaegeuk Kim05ca9152021-04-02 21:28:51 -0700654static void SetReadAheadSize(const std::string& entry_block_device, off64_t size_kb) {
655 std::string block_device;
656 if (!Realpath(entry_block_device, &block_device)) {
657 PERROR << "Failed to realpath " << entry_block_device;
658 return;
659 }
660
661 static constexpr std::string_view kDevBlockPrefix("/dev/block/");
662 if (!android::base::StartsWith(block_device, kDevBlockPrefix)) {
663 LWARNING << block_device << " is not a block device";
664 return;
665 }
666
667 DeviceMapper& dm = DeviceMapper::Instance();
668 while (true) {
669 std::string block_name = block_device;
670 if (android::base::StartsWith(block_device, kDevBlockPrefix)) {
671 block_name = block_device.substr(kDevBlockPrefix.length());
672 }
673 std::string sys_partition =
674 android::base::StringPrintf("/sys/class/block/%s/partition", block_name.c_str());
675 struct stat info;
676 if (lstat(sys_partition.c_str(), &info) == 0) {
677 // it has a partition like "sda12".
678 block_name += "/..";
679 }
680 std::string sys_ra = android::base::StringPrintf("/sys/class/block/%s/queue/read_ahead_kb",
681 block_name.c_str());
682 std::string size = android::base::StringPrintf("%llu", (long long)size_kb);
683 android::base::WriteStringToFile(size, sys_ra.c_str());
684 LINFO << "Set readahead_kb: " << size << " on " << sys_ra;
685
686 auto parent = dm.GetParentBlockDeviceByPath(block_device);
687 if (!parent) {
688 return;
689 }
690 block_device = *parent;
691 }
692}
693
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700694//
695// Prepare the filesystem on the given block device to be mounted.
696//
697// If the "check" option was given in the fstab record, or it seems that the
698// filesystem was uncleanly shut down, we'll run fsck on the filesystem.
699//
700// If needed, we'll also enable (or disable) filesystem features as specified by
701// the fstab record.
702//
Tom Cherrya7f1a9f2020-11-19 11:39:39 -0800703static int prepare_fs_for_mount(const std::string& blk_device, const FstabEntry& entry,
704 const std::string& alt_mount_point = "") {
705 auto& mount_point = alt_mount_point.empty() ? entry.mount_point : alt_mount_point;
706 // We need this because sometimes we have legacy symlinks that are
707 // lingering around and need cleaning up.
708 struct stat info;
709 if (lstat(mount_point.c_str(), &info) == 0 && (info.st_mode & S_IFMT) == S_IFLNK) {
710 unlink(mount_point.c_str());
711 }
712 mkdir(mount_point.c_str(), 0755);
713
Jaegeuk Kim05ca9152021-04-02 21:28:51 -0700714 // Don't need to return error, since it's a salt
715 if (entry.readahead_size_kb != -1) {
716 SetReadAheadSize(blk_device, entry.readahead_size_kb);
717 }
718
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700719 int fs_stat = 0;
720
Tom Cherry23319eb2018-11-30 16:16:05 -0800721 if (is_extfs(entry.fs_type)) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700722 struct ext4_super_block sb;
723
Eric Biggersdc3e8972020-08-04 11:11:13 -0700724 if (read_ext4_superblock(blk_device, &sb, &fs_stat)) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700725 if ((sb.s_feature_incompat & EXT4_FEATURE_INCOMPAT_RECOVER) != 0 ||
726 (sb.s_state & EXT4_VALID_FS) == 0) {
727 LINFO << "Filesystem on " << blk_device << " was not cleanly shutdown; "
728 << "state flags: 0x" << std::hex << sb.s_state << ", "
729 << "incompat feature flags: 0x" << std::hex << sb.s_feature_incompat;
730 fs_stat |= FS_STAT_UNCLEAN_SHUTDOWN;
731 }
732
733 // Note: quotas should be enabled before running fsck.
Tom Cherry23319eb2018-11-30 16:16:05 -0800734 tune_quota(blk_device, entry, &sb, &fs_stat);
liminghao9a0fd1d2016-07-22 11:48:14 +0800735 } else {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700736 return fs_stat;
liminghao9a0fd1d2016-07-22 11:48:14 +0800737 }
Tom Cherry23319eb2018-11-30 16:16:05 -0800738 } else if (is_f2fs(entry.fs_type)) {
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800739 if (!read_f2fs_superblock(blk_device, &fs_stat)) {
740 return fs_stat;
741 }
liminghao9a0fd1d2016-07-22 11:48:14 +0800742 }
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700743
Tom Cherry23319eb2018-11-30 16:16:05 -0800744 if (entry.fs_mgr_flags.check ||
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700745 (fs_stat & (FS_STAT_UNCLEAN_SHUTDOWN | FS_STAT_QUOTA_ENABLED))) {
Tom Cherrya7f1a9f2020-11-19 11:39:39 -0800746 check_fs(blk_device, entry.fs_type, mount_point, &fs_stat);
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700747 }
748
Tom Cherry23319eb2018-11-30 16:16:05 -0800749 if (is_extfs(entry.fs_type) &&
Tom Cherry685c2c72019-02-04 13:33:32 -0800750 (entry.reserved_size != 0 || entry.fs_mgr_flags.file_encryption ||
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800751 entry.fs_mgr_flags.fs_verity || entry.fs_mgr_flags.ext_meta_csum)) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700752 struct ext4_super_block sb;
753
Eric Biggersdc3e8972020-08-04 11:11:13 -0700754 if (read_ext4_superblock(blk_device, &sb, &fs_stat)) {
Tom Cherry23319eb2018-11-30 16:16:05 -0800755 tune_reserved_size(blk_device, entry, &sb, &fs_stat);
756 tune_encrypt(blk_device, entry, &sb, &fs_stat);
Leo Liou0b721d32019-01-15 20:43:37 +0800757 tune_verity(blk_device, entry, &sb, &fs_stat);
Jaegeuk Kim5ba5b902020-08-14 12:34:36 -0700758 tune_casefold(blk_device, entry, &sb, &fs_stat);
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800759 tune_metadata_csum(blk_device, entry, &sb, &fs_stat);
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700760 }
761 }
762
763 return fs_stat;
liminghao9a0fd1d2016-07-22 11:48:14 +0800764}
765
Tom Cherry0d2621f2018-12-04 13:15:09 -0800766// Mark the given block device as read-only, using the BLKROSET ioctl.
Yifan Hongccdba572019-01-08 13:33:52 -0800767bool fs_mgr_set_blk_ro(const std::string& blockdev, bool readonly) {
Tom Cherry0d2621f2018-12-04 13:15:09 -0800768 unique_fd fd(TEMP_FAILURE_RETRY(open(blockdev.c_str(), O_RDONLY | O_CLOEXEC)));
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700769 if (fd < 0) {
Tom Cherry0d2621f2018-12-04 13:15:09 -0800770 return false;
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700771 }
772
Yifan Hongccdba572019-01-08 13:33:52 -0800773 int ON = readonly;
Tom Cherry0d2621f2018-12-04 13:15:09 -0800774 return ioctl(fd, BLKROSET, &ON) == 0;
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700775}
776
Bowgo Tsaid1fe3bd2017-07-05 15:37:15 +0800777// Orange state means the device is unlocked, see the following link for details.
778// https://source.android.com/security/verifiedboot/verified-boot#device_state
779bool fs_mgr_is_device_unlocked() {
780 std::string verified_boot_state;
781 if (fs_mgr_get_boot_config("verifiedbootstate", &verified_boot_state)) {
782 return verified_boot_state == "orange";
783 }
784 return false;
785}
786
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800787// __mount(): wrapper around the mount() system call which also
788// sets the underlying block device to read-only if the mount is read-only.
789// See "man 2 mount" for return values.
Tom Cherry23319eb2018-11-30 16:16:05 -0800790static int __mount(const std::string& source, const std::string& target, const FstabEntry& entry) {
Mark Salyzyn69a5bd42017-06-28 13:36:52 -0700791 errno = 0;
Tom Cherry23319eb2018-11-30 16:16:05 -0800792 unsigned long mountflags = entry.flags;
Daniel Rosenberg5620c6c2019-01-16 16:28:21 -0800793 int ret = 0;
794 int save_errno = 0;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800795 int gc_allowance = 0;
796 std::string opts;
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700797 std::string checkpoint_opts;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800798 bool try_f2fs_gc_allowance = is_f2fs(entry.fs_type) && entry.fs_checkpoint_opts.length() > 0;
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700799 bool try_f2fs_fallback = false;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800800 Timer t;
801
Daniel Rosenberg5620c6c2019-01-16 16:28:21 -0800802 do {
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700803 if (save_errno == EINVAL && (try_f2fs_gc_allowance || try_f2fs_fallback)) {
804 PINFO << "Kernel does not support " << checkpoint_opts << ", trying without.";
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800805 try_f2fs_gc_allowance = false;
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700806 // Attempt without gc allowance before dropping.
807 try_f2fs_fallback = !try_f2fs_fallback;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800808 }
809 if (try_f2fs_gc_allowance) {
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700810 checkpoint_opts = entry.fs_checkpoint_opts + ":" + std::to_string(gc_allowance) + "%";
811 } else if (try_f2fs_fallback) {
812 checkpoint_opts = entry.fs_checkpoint_opts;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800813 } else {
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700814 checkpoint_opts = "";
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800815 }
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700816 opts = entry.fs_options + checkpoint_opts;
Daniel Rosenberg5620c6c2019-01-16 16:28:21 -0800817 if (save_errno == EAGAIN) {
818 PINFO << "Retrying mount (source=" << source << ",target=" << target
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800819 << ",type=" << entry.fs_type << ", gc_allowance=" << gc_allowance << "%)=" << ret
820 << "(" << save_errno << ")";
Daniel Rosenberg5620c6c2019-01-16 16:28:21 -0800821 }
822 ret = mount(source.c_str(), target.c_str(), entry.fs_type.c_str(), mountflags,
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800823 opts.c_str());
Daniel Rosenberg5620c6c2019-01-16 16:28:21 -0800824 save_errno = errno;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800825 if (try_f2fs_gc_allowance) gc_allowance += 10;
826 } while ((ret && save_errno == EAGAIN && gc_allowance <= 100) ||
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700827 (ret && save_errno == EINVAL && (try_f2fs_gc_allowance || try_f2fs_fallback)));
Mark Salyzyn8243f662018-09-26 14:27:04 -0700828 const char* target_missing = "";
829 const char* source_missing = "";
830 if (save_errno == ENOENT) {
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800831 if (access(target.c_str(), F_OK)) {
Mark Salyzyn8243f662018-09-26 14:27:04 -0700832 target_missing = "(missing)";
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800833 } else if (access(source.c_str(), F_OK)) {
Mark Salyzyn8243f662018-09-26 14:27:04 -0700834 source_missing = "(missing)";
835 }
836 errno = save_errno;
837 }
838 PINFO << __FUNCTION__ << "(source=" << source << source_missing << ",target=" << target
Tom Cherry23319eb2018-11-30 16:16:05 -0800839 << target_missing << ",type=" << entry.fs_type << ")=" << ret;
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700840 if ((ret == 0) && (mountflags & MS_RDONLY) != 0) {
Sami Tolvanen214f33b2014-12-18 16:15:30 +0000841 fs_mgr_set_blk_ro(source);
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700842 }
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800843 android::base::SetProperty("ro.boottime.init.mount." + Basename(target),
844 std::to_string(t.duration().count()));
JP Abgrall5c01dac2014-06-18 14:54:37 -0700845 errno = save_errno;
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700846 return ret;
847}
848
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800849static bool fs_match(const std::string& in1, const std::string& in2) {
850 if (in1.empty() || in2.empty()) {
851 return false;
852 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800853
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800854 auto in1_end = in1.size() - 1;
855 while (in1_end > 0 && in1[in1_end] == '/') {
856 in1_end--;
857 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800858
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800859 auto in2_end = in2.size() - 1;
860 while (in2_end > 0 && in2[in2_end] == '/') {
861 in2_end--;
862 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800863
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800864 if (in1_end != in2_end) {
865 return false;
866 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800867
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800868 for (size_t i = 0; i <= in1_end; ++i) {
869 if (in1[i] != in2[i]) {
870 return false;
871 }
872 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800873
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800874 return true;
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800875}
876
Tom Cherry23319eb2018-11-30 16:16:05 -0800877// Tries to mount any of the consecutive fstab entries that match
878// the mountpoint of the one given by fstab[start_idx].
879//
880// end_idx: On return, will be the last entry that was looked at.
881// attempted_idx: On return, will indicate which fstab entry
882// succeeded. In case of failure, it will be the start_idx.
883// Sets errno to match the 1st mount failure on failure.
884static bool mount_with_alternatives(const Fstab& fstab, int start_idx, int* end_idx,
885 int* attempted_idx) {
Yi Konge93040c2018-12-14 15:40:08 -0800886 unsigned long i;
JP Abgrallf22b7452014-07-02 13:16:04 -0700887 int mount_errno = 0;
Tom Cherry23319eb2018-11-30 16:16:05 -0800888 bool mounted = false;
JP Abgrallf22b7452014-07-02 13:16:04 -0700889
Tom Cherry23319eb2018-11-30 16:16:05 -0800890 // Hunt down an fstab entry for the same mount point that might succeed.
JP Abgrallf22b7452014-07-02 13:16:04 -0700891 for (i = start_idx;
Tom Cherry23319eb2018-11-30 16:16:05 -0800892 // We required that fstab entries for the same mountpoint be consecutive.
893 i < fstab.size() && fstab[start_idx].mount_point == fstab[i].mount_point; i++) {
894 // Don't try to mount/encrypt the same mount point again.
895 // Deal with alternate entries for the same point which are required to be all following
896 // each other.
897 if (mounted) {
898 LERROR << __FUNCTION__ << "(): skipping fstab dup mountpoint=" << fstab[i].mount_point
899 << " rec[" << i << "].fs_type=" << fstab[i].fs_type << " already mounted as "
900 << fstab[*attempted_idx].fs_type;
901 continue;
902 }
JP Abgrallf22b7452014-07-02 13:16:04 -0700903
Tom Cherry23319eb2018-11-30 16:16:05 -0800904 int fs_stat = prepare_fs_for_mount(fstab[i].blk_device, fstab[i]);
905 if (fs_stat & FS_STAT_INVALID_MAGIC) {
906 LERROR << __FUNCTION__
907 << "(): skipping mount due to invalid magic, mountpoint=" << fstab[i].mount_point
908 << " blk_dev=" << realpath(fstab[i].blk_device) << " rec[" << i
909 << "].fs_type=" << fstab[i].fs_type;
Eric Biggers63fb1952021-11-08 16:38:53 -0800910 mount_errno = EINVAL; // continue bootup for metadata encryption
Tom Cherry23319eb2018-11-30 16:16:05 -0800911 continue;
912 }
liminghao9a0fd1d2016-07-22 11:48:14 +0800913
Tom Cherry23319eb2018-11-30 16:16:05 -0800914 int retry_count = 2;
915 while (retry_count-- > 0) {
916 if (!__mount(fstab[i].blk_device, fstab[i].mount_point, fstab[i])) {
917 *attempted_idx = i;
918 mounted = true;
919 if (i != start_idx) {
920 LERROR << __FUNCTION__ << "(): Mounted " << fstab[i].blk_device << " on "
921 << fstab[i].mount_point << " with fs_type=" << fstab[i].fs_type
922 << " instead of " << fstab[start_idx].fs_type;
NIEJuhu5c31ffe2017-03-09 12:19:08 +0800923 }
Tom Cherry23319eb2018-11-30 16:16:05 -0800924 fs_stat &= ~FS_STAT_FULL_MOUNT_FAILED;
925 mount_errno = 0;
926 break;
927 } else {
928 if (retry_count <= 0) break; // run check_fs only once
929 fs_stat |= FS_STAT_FULL_MOUNT_FAILED;
930 // back up the first errno for crypto decisions.
931 if (mount_errno == 0) {
932 mount_errno = errno;
933 }
934 // retry after fsck
935 check_fs(fstab[i].blk_device, fstab[i].fs_type, fstab[i].mount_point, &fs_stat);
JP Abgrallf22b7452014-07-02 13:16:04 -0700936 }
Tom Cherry23319eb2018-11-30 16:16:05 -0800937 }
938 log_fs_stat(fstab[i].blk_device, fs_stat);
JP Abgrallf22b7452014-07-02 13:16:04 -0700939 }
940
941 /* Adjust i for the case where it was still withing the recs[] */
Tom Cherry23319eb2018-11-30 16:16:05 -0800942 if (i < fstab.size()) --i;
JP Abgrallf22b7452014-07-02 13:16:04 -0700943
944 *end_idx = i;
945 if (!mounted) {
946 *attempted_idx = start_idx;
947 errno = mount_errno;
Tom Cherry23319eb2018-11-30 16:16:05 -0800948 return false;
JP Abgrallf22b7452014-07-02 13:16:04 -0700949 }
Tom Cherry23319eb2018-11-30 16:16:05 -0800950 return true;
JP Abgrall4bb7bba2014-06-19 22:12:20 -0700951}
952
Tom Cherry23319eb2018-11-30 16:16:05 -0800953static bool TranslateExtLabels(FstabEntry* entry) {
954 if (!StartsWith(entry->blk_device, "LABEL=")) {
Tom Cherry0d2621f2018-12-04 13:15:09 -0800955 return true;
Christoffer Dall82982342014-12-17 21:26:54 +0100956 }
957
Tom Cherry23319eb2018-11-30 16:16:05 -0800958 std::string label = entry->blk_device.substr(6);
Tom Cherry0d2621f2018-12-04 13:15:09 -0800959 if (label.size() > 16) {
960 LERROR << "FS label is longer than allowed by filesystem";
961 return false;
962 }
Christoffer Dall82982342014-12-17 21:26:54 +0100963
Tom Cherry0d2621f2018-12-04 13:15:09 -0800964 auto blockdir = std::unique_ptr<DIR, decltype(&closedir)>{opendir("/dev/block"), closedir};
Christoffer Dall82982342014-12-17 21:26:54 +0100965 if (!blockdir) {
bowgotsai47878de2017-01-23 14:04:34 +0800966 LERROR << "couldn't open /dev/block";
Tom Cherry0d2621f2018-12-04 13:15:09 -0800967 return false;
Christoffer Dall82982342014-12-17 21:26:54 +0100968 }
969
Tom Cherry0d2621f2018-12-04 13:15:09 -0800970 struct dirent* ent;
971 while ((ent = readdir(blockdir.get()))) {
Christoffer Dall82982342014-12-17 21:26:54 +0100972 if (ent->d_type != DT_BLK)
973 continue;
974
Tom Cherry0d2621f2018-12-04 13:15:09 -0800975 unique_fd fd(TEMP_FAILURE_RETRY(
976 openat(dirfd(blockdir.get()), ent->d_name, O_RDONLY | O_CLOEXEC)));
Christoffer Dall82982342014-12-17 21:26:54 +0100977 if (fd < 0) {
bowgotsai47878de2017-01-23 14:04:34 +0800978 LERROR << "Cannot open block device /dev/block/" << ent->d_name;
Tom Cherry0d2621f2018-12-04 13:15:09 -0800979 return false;
Christoffer Dall82982342014-12-17 21:26:54 +0100980 }
981
Tom Cherry0d2621f2018-12-04 13:15:09 -0800982 ext4_super_block super_block;
Christoffer Dall82982342014-12-17 21:26:54 +0100983 if (TEMP_FAILURE_RETRY(lseek(fd, 1024, SEEK_SET)) < 0 ||
Tom Cherry0d2621f2018-12-04 13:15:09 -0800984 TEMP_FAILURE_RETRY(read(fd, &super_block, sizeof(super_block))) !=
985 sizeof(super_block)) {
986 // Probably a loopback device or something else without a readable superblock.
Christoffer Dall82982342014-12-17 21:26:54 +0100987 continue;
988 }
989
Tom Cherry0d2621f2018-12-04 13:15:09 -0800990 if (super_block.s_magic != EXT4_SUPER_MAGIC) {
bowgotsai47878de2017-01-23 14:04:34 +0800991 LINFO << "/dev/block/" << ent->d_name << " not ext{234}";
Christoffer Dall82982342014-12-17 21:26:54 +0100992 continue;
993 }
994
Tom Cherry0d2621f2018-12-04 13:15:09 -0800995 if (label == super_block.s_volume_name) {
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800996 std::string new_blk_device = "/dev/block/"s + ent->d_name;
Christoffer Dall82982342014-12-17 21:26:54 +0100997
Tom Cherry23319eb2018-11-30 16:16:05 -0800998 LINFO << "resolved label " << entry->blk_device << " to " << new_blk_device;
Christoffer Dall82982342014-12-17 21:26:54 +0100999
Tom Cherry23319eb2018-11-30 16:16:05 -08001000 entry->blk_device = new_blk_device;
Tom Cherry0d2621f2018-12-04 13:15:09 -08001001 return true;
Christoffer Dall82982342014-12-17 21:26:54 +01001002 }
1003 }
1004
Tom Cherry0d2621f2018-12-04 13:15:09 -08001005 return false;
Christoffer Dall82982342014-12-17 21:26:54 +01001006}
1007
Tom Cherry23319eb2018-11-30 16:16:05 -08001008static bool should_use_metadata_encryption(const FstabEntry& entry) {
Eric Biggers63fb1952021-11-08 16:38:53 -08001009 return !entry.metadata_key_dir.empty() && entry.fs_mgr_flags.file_encryption;
Paul Lawrence9dbe97b2017-04-21 12:41:48 -07001010}
1011
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001012// Check to see if a mountable volume has encryption requirements
Tom Cherry23319eb2018-11-30 16:16:05 -08001013static int handle_encryptable(const FstabEntry& entry) {
Eric Biggers63fb1952021-11-08 16:38:53 -08001014 if (should_use_metadata_encryption(entry)) {
Jaegeuk Kimbdb981d2021-12-07 11:23:52 -08001015 if (umount_retry(entry.mount_point)) {
Paul Lawrence9dbe97b2017-04-21 12:41:48 -07001016 return FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION;
Paul Lawrence9dbe97b2017-04-21 12:41:48 -07001017 }
Jaegeuk Kimbdb981d2021-12-07 11:23:52 -08001018 PERROR << "Could not umount " << entry.mount_point << " - fail since can't encrypt";
1019 return FS_MGR_MNTALL_FAIL;
Eric Biggers63fb1952021-11-08 16:38:53 -08001020 } else if (entry.fs_mgr_flags.file_encryption) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001021 LINFO << entry.mount_point << " is file encrypted";
Paul Lawrence69080182016-02-02 10:31:30 -08001022 return FS_MGR_MNTALL_DEV_FILE_ENCRYPTED;
Paul Lawrence1098aac2016-03-04 15:52:33 -08001023 } else {
1024 return FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE;
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001025 }
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001026}
1027
Paul Crowley9acab5a2020-08-14 11:05:05 -07001028static void set_type_property(int status) {
1029 switch (status) {
Paul Crowley9acab5a2020-08-14 11:05:05 -07001030 case FS_MGR_MNTALL_DEV_FILE_ENCRYPTED:
1031 case FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED:
1032 case FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION:
1033 SetProperty("ro.crypto.type", "file");
1034 break;
1035 }
1036}
1037
Tom Cherry3a803eb2019-09-25 16:23:50 -07001038static bool call_vdc(const std::vector<std::string>& args, int* ret) {
Paul Crowleyc6846962018-01-30 09:56:03 -08001039 std::vector<char const*> argv;
1040 argv.emplace_back("/system/bin/vdc");
1041 for (auto& arg : args) {
1042 argv.emplace_back(arg.c_str());
1043 }
1044 LOG(INFO) << "Calling: " << android::base::Join(argv, ' ');
Tom Cherry3a803eb2019-09-25 16:23:50 -07001045 int err = logwrap_fork_execvp(argv.size(), argv.data(), ret, false, LOG_ALOG, false, nullptr);
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001046 if (err != 0) {
1047 LOG(ERROR) << "vdc call failed with error code: " << err;
1048 return false;
1049 }
1050 LOG(DEBUG) << "vdc finished successfully";
Tom Cherry3a803eb2019-09-25 16:23:50 -07001051 if (ret != nullptr) {
1052 *ret = WEXITSTATUS(*ret);
1053 }
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001054 return true;
1055}
1056
Tom Cherry23319eb2018-11-30 16:16:05 -08001057bool fs_mgr_update_logical_partition(FstabEntry* entry) {
David Anderson62e5b202018-05-01 17:09:17 -07001058 // Logical partitions are specified with a named partition rather than a
1059 // block device, so if the block device is a path, then it has already
1060 // been updated.
Tom Cherry23319eb2018-11-30 16:16:05 -08001061 if (entry->blk_device[0] == '/') {
David Anderson62e5b202018-05-01 17:09:17 -07001062 return true;
1063 }
1064
David Andersonb5acb1a2018-06-26 17:07:55 -07001065 DeviceMapper& dm = DeviceMapper::Instance();
David Anderson62e5b202018-05-01 17:09:17 -07001066 std::string device_name;
Tom Cherry23319eb2018-11-30 16:16:05 -08001067 if (!dm.GetDmDevicePathByName(entry->blk_device, &device_name)) {
David Anderson62e5b202018-05-01 17:09:17 -07001068 return false;
1069 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001070
1071 entry->blk_device = device_name;
1072 return true;
1073}
1074
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001075static bool SupportsCheckpoint(FstabEntry* entry) {
1076 return entry->fs_mgr_flags.checkpoint_blk || entry->fs_mgr_flags.checkpoint_fs;
1077}
1078
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001079class CheckpointManager {
1080 public:
Paul Lawrence20553642020-06-12 07:32:23 -07001081 CheckpointManager(int needs_checkpoint = -1, bool metadata_encrypted = false)
1082 : needs_checkpoint_(needs_checkpoint), metadata_encrypted_(metadata_encrypted) {}
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001083
Nikita Ioffe12a36072019-10-23 20:11:32 +01001084 bool NeedsCheckpoint() {
1085 if (needs_checkpoint_ != UNKNOWN) {
1086 return needs_checkpoint_ == YES;
1087 }
1088 if (!call_vdc({"checkpoint", "needsCheckpoint"}, &needs_checkpoint_)) {
1089 LERROR << "Failed to find if checkpointing is needed. Assuming no.";
1090 needs_checkpoint_ = NO;
1091 }
1092 return needs_checkpoint_ == YES;
1093 }
1094
Paul Lawrence323959e2019-06-25 14:36:52 -07001095 bool Update(FstabEntry* entry, const std::string& block_device = std::string()) {
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001096 if (!SupportsCheckpoint(entry)) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001097 return true;
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001098 }
Paul Lawrence786d0b22018-09-21 10:49:38 -07001099
Paul Lawrence20553642020-06-12 07:32:23 -07001100 if (entry->fs_mgr_flags.checkpoint_blk && !metadata_encrypted_) {
Tom Cherry3a803eb2019-09-25 16:23:50 -07001101 call_vdc({"checkpoint", "restoreCheckpoint", entry->blk_device}, nullptr);
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001102 }
1103
Nikita Ioffe12a36072019-10-23 20:11:32 +01001104 if (!NeedsCheckpoint()) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001105 return true;
1106 }
1107
Paul Lawrence323959e2019-06-25 14:36:52 -07001108 if (!UpdateCheckpointPartition(entry, block_device)) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001109 LERROR << "Could not set up checkpoint partition, skipping!";
Paul Lawrence786d0b22018-09-21 10:49:38 -07001110 return false;
1111 }
1112
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001113 return true;
1114 }
1115
Tom Cherry23319eb2018-11-30 16:16:05 -08001116 bool Revert(FstabEntry* entry) {
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001117 if (!SupportsCheckpoint(entry)) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001118 return true;
Paul Lawrence786d0b22018-09-21 10:49:38 -07001119 }
1120
Tom Cherry23319eb2018-11-30 16:16:05 -08001121 if (device_map_.find(entry->blk_device) == device_map_.end()) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001122 return true;
Paul Lawrence786d0b22018-09-21 10:49:38 -07001123 }
1124
Tom Cherry23319eb2018-11-30 16:16:05 -08001125 std::string bow_device = entry->blk_device;
1126 entry->blk_device = device_map_[bow_device];
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001127 device_map_.erase(bow_device);
1128
Paul Lawrence786d0b22018-09-21 10:49:38 -07001129 DeviceMapper& dm = DeviceMapper::Instance();
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001130 if (!dm.DeleteDevice("bow")) {
1131 PERROR << "Failed to remove bow device";
Paul Lawrence786d0b22018-09-21 10:49:38 -07001132 }
1133
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001134 return true;
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001135 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001136
1137 private:
Paul Lawrence323959e2019-06-25 14:36:52 -07001138 bool UpdateCheckpointPartition(FstabEntry* entry, const std::string& block_device) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001139 if (entry->fs_mgr_flags.checkpoint_fs) {
1140 if (is_f2fs(entry->fs_type)) {
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -08001141 entry->fs_checkpoint_opts = ",checkpoint=disable";
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001142 } else {
Tom Cherry23319eb2018-11-30 16:16:05 -08001143 LERROR << entry->fs_type << " does not implement checkpoints.";
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001144 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001145 } else if (entry->fs_mgr_flags.checkpoint_blk) {
Paul Lawrence323959e2019-06-25 14:36:52 -07001146 auto actual_block_device = block_device.empty() ? entry->blk_device : block_device;
1147 if (fs_mgr_find_bow_device(actual_block_device).empty()) {
1148 unique_fd fd(
1149 TEMP_FAILURE_RETRY(open(entry->blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
1150 if (fd < 0) {
1151 PERROR << "Cannot open device " << entry->blk_device;
1152 return false;
1153 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001154
Paul Lawrence323959e2019-06-25 14:36:52 -07001155 uint64_t size = get_block_device_size(fd) / 512;
1156 if (!size) {
1157 PERROR << "Cannot get device size";
1158 return false;
1159 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001160
Paul Lawrence323959e2019-06-25 14:36:52 -07001161 android::dm::DmTable table;
Paul Lawrence2f0c6cb2020-06-01 12:58:04 -07001162 auto bowTarget =
1163 std::make_unique<android::dm::DmTargetBow>(0, size, entry->blk_device);
1164
1165 // dm-bow uses the first block as a log record, and relocates the real first block
1166 // elsewhere. For metadata encrypted devices, dm-bow sits below dm-default-key, and
1167 // for post Android Q devices dm-default-key uses a block size of 4096 always.
1168 // So if dm-bow's block size, which by default is the block size of the underlying
1169 // hardware, is less than dm-default-key's, blocks will get broken up and I/O will
1170 // fail as it won't be data_unit_size aligned.
1171 // However, since it is possible there is an already shipping non
1172 // metadata-encrypted device with smaller blocks, we must not change this for
1173 // devices shipped with Q or earlier unless they explicitly selected dm-default-key
1174 // v2
Paul Lawrence2f0c6cb2020-06-01 12:58:04 -07001175 unsigned int options_format_version = android::base::GetUintProperty<unsigned int>(
1176 "ro.crypto.dm_default_key.options_format.version",
Eric Biggers75ebdd92020-08-10 11:14:51 -07001177 (android::fscrypt::GetFirstApiLevel() <= __ANDROID_API_Q__ ? 1 : 2));
Paul Lawrence2f0c6cb2020-06-01 12:58:04 -07001178 if (options_format_version > 1) {
1179 bowTarget->SetBlockSize(4096);
1180 }
1181
1182 if (!table.AddTarget(std::move(bowTarget))) {
Paul Lawrence323959e2019-06-25 14:36:52 -07001183 LERROR << "Failed to add bow target";
1184 return false;
1185 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001186
Paul Lawrence323959e2019-06-25 14:36:52 -07001187 DeviceMapper& dm = DeviceMapper::Instance();
1188 if (!dm.CreateDevice("bow", table)) {
1189 PERROR << "Failed to create bow device";
1190 return false;
1191 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001192
Paul Lawrence323959e2019-06-25 14:36:52 -07001193 std::string name;
1194 if (!dm.GetDmDevicePathByName("bow", &name)) {
1195 PERROR << "Failed to get bow device name";
1196 return false;
1197 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001198
Paul Lawrence323959e2019-06-25 14:36:52 -07001199 device_map_[name] = entry->blk_device;
1200 entry->blk_device = name;
1201 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001202 }
1203 return true;
1204 }
1205
1206 enum { UNKNOWN = -1, NO = 0, YES = 1 };
1207 int needs_checkpoint_;
Paul Lawrence20553642020-06-12 07:32:23 -07001208 bool metadata_encrypted_;
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001209 std::map<std::string, std::string> device_map_;
1210};
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001211
Paul Lawrence323959e2019-06-25 14:36:52 -07001212std::string fs_mgr_find_bow_device(const std::string& block_device) {
1213 if (block_device.substr(0, 5) != "/dev/") {
1214 LOG(ERROR) << "Expected block device, got " << block_device;
1215 return std::string();
1216 }
1217
1218 std::string sys_dir = std::string("/sys/") + block_device.substr(5);
1219
1220 for (;;) {
1221 std::string name;
1222 if (!android::base::ReadFileToString(sys_dir + "/dm/name", &name)) {
1223 PLOG(ERROR) << block_device << " is not dm device";
1224 return std::string();
1225 }
1226
1227 if (name == "bow\n") return sys_dir;
1228
1229 std::string slaves = sys_dir + "/slaves";
1230 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(slaves.c_str()), closedir);
1231 if (!directory) {
1232 PLOG(ERROR) << "Can't open slave directory " << slaves;
1233 return std::string();
1234 }
1235
1236 int count = 0;
1237 for (dirent* entry = readdir(directory.get()); entry; entry = readdir(directory.get())) {
1238 if (entry->d_type != DT_LNK) continue;
1239
1240 if (count == 1) {
1241 LOG(ERROR) << "Too many slaves in " << slaves;
1242 return std::string();
1243 }
1244
1245 ++count;
1246 sys_dir = std::string("/sys/block/") + entry->d_name;
1247 }
1248
1249 if (count != 1) {
1250 LOG(ERROR) << "No slave in " << slaves;
1251 return std::string();
1252 }
1253 }
1254}
1255
David Anderson671bd812020-01-24 19:19:27 -08001256static constexpr const char* kUserdataWrapperName = "userdata-wrapper";
1257
1258static void WrapUserdata(FstabEntry* entry, dev_t dev, const std::string& block_device) {
1259 DeviceMapper& dm = DeviceMapper::Instance();
1260 if (dm.GetState(kUserdataWrapperName) != DmDeviceState::INVALID) {
1261 // This will report failure for us. If we do fail to get the path,
1262 // we leave the device unwrapped.
1263 dm.GetDmDevicePathByName(kUserdataWrapperName, &entry->blk_device);
1264 return;
1265 }
1266
1267 unique_fd fd(open(block_device.c_str(), O_RDONLY | O_CLOEXEC));
1268 if (fd < 0) {
1269 PLOG(ERROR) << "open failed: " << entry->blk_device;
1270 return;
1271 }
1272
1273 auto dev_str = android::base::StringPrintf("%u:%u", major(dev), minor(dev));
1274 uint64_t sectors = get_block_device_size(fd) / 512;
1275
1276 android::dm::DmTable table;
1277 table.Emplace<DmTargetLinear>(0, sectors, dev_str, 0);
1278
1279 std::string dm_path;
1280 if (!dm.CreateDevice(kUserdataWrapperName, table, &dm_path, 20s)) {
1281 LOG(ERROR) << "Failed to create userdata wrapper device";
1282 return;
1283 }
1284 entry->blk_device = dm_path;
1285}
1286
1287// When using Virtual A/B, partitions can be backed by /data and mapped with
1288// device-mapper in first-stage init. This can happen when merging an OTA or
1289// when using adb remount to house "scratch". In this case, /data cannot be
1290// mounted directly off the userdata block device, and e2fsck will refuse to
1291// scan it, because the kernel reports the block device as in-use.
1292//
1293// As a workaround, when mounting /data, we create a trivial dm-linear wrapper
1294// if the underlying block device already has dependencies. Note that we make
1295// an exception for metadata-encrypted devices, since dm-default-key is already
1296// a wrapper.
1297static void WrapUserdataIfNeeded(FstabEntry* entry, const std::string& actual_block_device = {}) {
1298 const auto& block_device =
1299 actual_block_device.empty() ? entry->blk_device : actual_block_device;
Paul Crowley7823e322020-01-30 16:03:45 -08001300 if (entry->mount_point != "/data" || !entry->metadata_key_dir.empty() ||
David Anderson671bd812020-01-24 19:19:27 -08001301 android::base::StartsWith(block_device, "/dev/block/dm-")) {
1302 return;
1303 }
1304
1305 struct stat st;
1306 if (stat(block_device.c_str(), &st) < 0) {
1307 PLOG(ERROR) << "stat failed: " << block_device;
1308 return;
1309 }
1310
1311 std::string path = android::base::StringPrintf("/sys/dev/block/%u:%u/holders",
1312 major(st.st_rdev), minor(st.st_rdev));
1313 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
1314 if (!dir) {
1315 PLOG(ERROR) << "opendir failed: " << path;
1316 return;
1317 }
1318
1319 struct dirent* d;
1320 bool has_holders = false;
1321 while ((d = readdir(dir.get())) != nullptr) {
1322 if (strcmp(d->d_name, ".") != 0 && strcmp(d->d_name, "..") != 0) {
1323 has_holders = true;
1324 break;
1325 }
1326 }
1327
1328 if (has_holders) {
1329 WrapUserdata(entry, st.st_rdev, block_device);
1330 }
1331}
1332
David Anderson42c32bf2019-01-14 16:51:52 -08001333static bool IsMountPointMounted(const std::string& mount_point) {
1334 // Check if this is already mounted.
1335 Fstab fstab;
1336 if (!ReadFstabFromFile("/proc/mounts", &fstab)) {
1337 return false;
1338 }
Tom Cherry2e545f82019-01-29 08:49:57 -08001339 return GetEntryForMountPoint(&fstab, mount_point) != nullptr;
David Anderson42c32bf2019-01-14 16:51:52 -08001340}
1341
Tom Cherry23319eb2018-11-30 16:16:05 -08001342// When multiple fstab records share the same mount_point, it will try to mount each
1343// one in turn, and ignore any duplicates after a first successful mount.
1344// Returns -1 on error, and FS_MGR_MNTALL_* otherwise.
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001345MountAllResult fs_mgr_mount_all(Fstab* fstab, int mount_mode) {
Paul Lawrence1098aac2016-03-04 15:52:33 -08001346 int encryptable = FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE;
Mohamad Ayyash38afe5f2014-03-10 15:40:29 -07001347 int error_count = 0;
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001348 CheckpointManager checkpoint_manager;
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001349 AvbUniquePtr avb_handle(nullptr);
Jaegeuk Kima7635712020-12-15 08:46:44 -08001350 bool wiped = false;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001351
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001352 bool userdata_mounted = false;
Tom Cherry23319eb2018-11-30 16:16:05 -08001353 if (fstab->empty()) {
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001354 return {FS_MGR_MNTALL_FAIL, userdata_mounted};
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001355 }
1356
Woody Chow7fb93c12020-01-21 10:50:34 +09001357 // Keep i int to prevent unsigned integer overflow from (i = top_idx - 1),
1358 // where top_idx is 0. It will give SIGABRT
1359 for (int i = 0; i < static_cast<int>(fstab->size()); i++) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001360 auto& current_entry = (*fstab)[i];
1361
David Anderson42c32bf2019-01-14 16:51:52 -08001362 // If a filesystem should have been mounted in the first stage, we
1363 // ignore it here. With one exception, if the filesystem is
1364 // formattable, then it can only be formatted in the second stage,
1365 // so we allow it to mount here.
1366 if (current_entry.fs_mgr_flags.first_stage_mount &&
1367 (!current_entry.fs_mgr_flags.formattable ||
1368 IsMountPointMounted(current_entry.mount_point))) {
1369 continue;
1370 }
1371
Tom Cherry23319eb2018-11-30 16:16:05 -08001372 // Don't mount entries that are managed by vold or not for the mount mode.
1373 if (current_entry.fs_mgr_flags.vold_managed || current_entry.fs_mgr_flags.recovery_only ||
Tom Cherry23319eb2018-11-30 16:16:05 -08001374 ((mount_mode == MOUNT_MODE_LATE) && !current_entry.fs_mgr_flags.late_mount) ||
1375 ((mount_mode == MOUNT_MODE_EARLY) && current_entry.fs_mgr_flags.late_mount)) {
Ken Sumrallab6b8522013-02-13 12:58:40 -08001376 continue;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001377 }
1378
Tom Cherry23319eb2018-11-30 16:16:05 -08001379 // Skip swap and raw partition entries such as boot, recovery, etc.
1380 if (current_entry.fs_type == "swap" || current_entry.fs_type == "emmc" ||
1381 current_entry.fs_type == "mtd") {
Ken Sumrallab6b8522013-02-13 12:58:40 -08001382 continue;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001383 }
1384
Tom Cherry23319eb2018-11-30 16:16:05 -08001385 // Skip mounting the root partition, as it will already have been mounted.
1386 if (current_entry.mount_point == "/" || current_entry.mount_point == "/system") {
1387 if ((current_entry.flags & MS_RDONLY) != 0) {
1388 fs_mgr_set_blk_ro(current_entry.blk_device);
Daniel Rosenberg31a4faf2015-06-29 17:33:05 -07001389 }
1390 continue;
1391 }
1392
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001393 // Terrible hack to make it possible to remount /data.
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001394 // TODO: refactor fs_mgr_mount_all and get rid of this.
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001395 if (mount_mode == MOUNT_MODE_ONLY_USERDATA && current_entry.mount_point != "/data") {
1396 continue;
1397 }
1398
Tom Cherry23319eb2018-11-30 16:16:05 -08001399 // Translate LABEL= file system labels into block devices.
1400 if (is_extfs(current_entry.fs_type)) {
1401 if (!TranslateExtLabels(&current_entry)) {
bowgotsai47878de2017-01-23 14:04:34 +08001402 LERROR << "Could not translate label to block device";
Christoffer Dall82982342014-12-17 21:26:54 +01001403 continue;
1404 }
1405 }
1406
Tom Cherry23319eb2018-11-30 16:16:05 -08001407 if (current_entry.fs_mgr_flags.logical) {
1408 if (!fs_mgr_update_logical_partition(&current_entry)) {
David Anderson62e5b202018-05-01 17:09:17 -07001409 LERROR << "Could not set up logical partition, skipping!";
1410 continue;
1411 }
1412 }
1413
David Anderson671bd812020-01-24 19:19:27 -08001414 WrapUserdataIfNeeded(&current_entry);
1415
Tom Cherry23319eb2018-11-30 16:16:05 -08001416 if (!checkpoint_manager.Update(&current_entry)) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001417 continue;
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001418 }
1419
David Anderson5c475c72019-06-11 17:40:49 -07001420 if (current_entry.fs_mgr_flags.wait && !WaitForFile(current_entry.blk_device, 20s)) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001421 LERROR << "Skipping '" << current_entry.blk_device << "' during mount_all";
Jinguang Dong9d344962017-06-13 10:20:34 +08001422 continue;
Ken Sumrallab6b8522013-02-13 12:58:40 -08001423 }
1424
Tom Cherry23319eb2018-11-30 16:16:05 -08001425 if (current_entry.fs_mgr_flags.avb) {
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001426 if (!avb_handle) {
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001427 avb_handle = AvbHandle::Open();
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001428 if (!avb_handle) {
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001429 LERROR << "Failed to open AvbHandle";
Paul Crowley9acab5a2020-08-14 11:05:05 -07001430 set_type_property(encryptable);
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001431 return {FS_MGR_MNTALL_FAIL, userdata_mounted};
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001432 }
1433 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001434 if (avb_handle->SetUpAvbHashtree(&current_entry, true /* wait_for_verity_dev */) ==
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001435 AvbHashtreeResult::kFail) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001436 LERROR << "Failed to set up AVB on partition: " << current_entry.mount_point
1437 << ", skipping!";
1438 // Skips mounting the device.
bowgotsaib51722b2017-01-11 22:21:38 +08001439 continue;
1440 }
Bowgo Tsaif3e28e12019-02-20 21:53:47 +08001441 } else if (!current_entry.avb_keys.empty()) {
Bowgo Tsaidefe1cb2019-01-25 12:07:09 +08001442 if (AvbHandle::SetUpStandaloneAvbHashtree(&current_entry) == AvbHashtreeResult::kFail) {
1443 LERROR << "Failed to set up AVB on standalone partition: "
1444 << current_entry.mount_point << ", skipping!";
1445 // Skips mounting the device.
1446 continue;
1447 }
Geremy Condra3ad3d1c2013-02-22 18:11:41 -08001448 }
bowgotsaib51722b2017-01-11 22:21:38 +08001449
JP Abgrallf22b7452014-07-02 13:16:04 -07001450 int last_idx_inspected;
Chris Fries79f33842013-09-05 13:19:21 -05001451 int top_idx = i;
Tom Cherry23319eb2018-11-30 16:16:05 -08001452 int attempted_idx = -1;
Chris Fries79f33842013-09-05 13:19:21 -05001453
Tom Cherry23319eb2018-11-30 16:16:05 -08001454 bool mret = mount_with_alternatives(*fstab, i, &last_idx_inspected, &attempted_idx);
1455 auto& attempted_entry = (*fstab)[attempted_idx];
JP Abgrallf22b7452014-07-02 13:16:04 -07001456 i = last_idx_inspected;
Tom Cherry23319eb2018-11-30 16:16:05 -08001457 int mount_errno = errno;
JP Abgrallf786fe52014-06-18 07:28:14 +00001458
Tom Cherry23319eb2018-11-30 16:16:05 -08001459 // Handle success and deal with encryptability.
1460 if (mret) {
1461 int status = handle_encryptable(attempted_entry);
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001462
1463 if (status == FS_MGR_MNTALL_FAIL) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001464 // Fatal error - no point continuing.
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001465 return {status, userdata_mounted};
Paul Lawrence166fa3d2014-02-03 13:27:49 -08001466 }
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001467
Paul Lawrence1098aac2016-03-04 15:52:33 -08001468 if (status != FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
1469 if (encryptable != FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001470 // Log and continue
bowgotsai47878de2017-01-23 14:04:34 +08001471 LERROR << "Only one encryptable/encrypted partition supported";
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001472 }
1473 encryptable = status;
Paul Crowleyc6846962018-01-30 09:56:03 -08001474 if (status == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
Paul Lawrence323959e2019-06-25 14:36:52 -07001475 if (!call_vdc({"cryptfs", "encryptFstab", attempted_entry.blk_device,
Jaegeuk Kima7635712020-12-15 08:46:44 -08001476 attempted_entry.mount_point, wiped ? "true" : "false",
1477 attempted_entry.fs_type},
Tom Cherry3a803eb2019-09-25 16:23:50 -07001478 nullptr)) {
Paul Crowleyc6846962018-01-30 09:56:03 -08001479 LERROR << "Encryption failed";
Paul Crowley9acab5a2020-08-14 11:05:05 -07001480 set_type_property(encryptable);
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001481 return {FS_MGR_MNTALL_FAIL, userdata_mounted};
Paul Crowleyc6846962018-01-30 09:56:03 -08001482 }
1483 }
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001484 }
1485
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001486 if (current_entry.mount_point == "/data") {
1487 userdata_mounted = true;
1488 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001489 // Success! Go get the next one.
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001490 continue;
1491 }
1492
Tom Cherry23319eb2018-11-30 16:16:05 -08001493 // Mounting failed, understand why and retry.
Jaegeuk Kima7635712020-12-15 08:46:44 -08001494 wiped = partition_wiped(current_entry.blk_device.c_str());
Tom Cherry23319eb2018-11-30 16:16:05 -08001495 if (mount_errno != EBUSY && mount_errno != EACCES &&
1496 current_entry.fs_mgr_flags.formattable && wiped) {
1497 // current_entry and attempted_entry point at the same partition, but sometimes
1498 // at two different lines in the fstab. Use current_entry for formatting
1499 // as that is the preferred one.
1500 LERROR << __FUNCTION__ << "(): " << realpath(current_entry.blk_device)
1501 << " is wiped and " << current_entry.mount_point << " " << current_entry.fs_type
1502 << " is formattable. Format it.";
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001503
Tom Cherry23319eb2018-11-30 16:16:05 -08001504 checkpoint_manager.Revert(&current_entry);
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001505
Jaegeuk Kima7635712020-12-15 08:46:44 -08001506 // EncryptInplace will be used when vdc gives an error or needs to format partitions
1507 // other than /data
1508 if (should_use_metadata_encryption(current_entry) &&
1509 current_entry.mount_point == "/data") {
1510
1511 // vdc->Format requires "ro.crypto.type" to set an encryption flag
1512 encryptable = FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED;
1513 set_type_property(encryptable);
1514
1515 if (!call_vdc({"cryptfs", "encryptFstab", current_entry.blk_device,
1516 current_entry.mount_point, "true" /* shouldFormat */,
1517 current_entry.fs_type},
1518 nullptr)) {
1519 LERROR << "Encryption failed";
1520 } else {
1521 userdata_mounted = true;
1522 continue;
1523 }
1524 }
1525
Eric Biggers4d0c5ef2021-11-08 16:38:54 -08001526 if (fs_mgr_do_format(current_entry) == 0) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001527 // Let's replay the mount actions.
Chris Fries79f33842013-09-05 13:19:21 -05001528 i = top_idx - 1;
1529 continue;
Matthew Bouyack9c59cbc2016-05-02 15:55:30 -07001530 } else {
bowgotsai47878de2017-01-23 14:04:34 +08001531 LERROR << __FUNCTION__ << "(): Format failed. "
1532 << "Suggest recovery...";
Matthew Bouyack9c59cbc2016-05-02 15:55:30 -07001533 encryptable = FS_MGR_MNTALL_DEV_NEEDS_RECOVERY;
1534 continue;
Chris Fries79f33842013-09-05 13:19:21 -05001535 }
1536 }
Paul Lawrence9dbe97b2017-04-21 12:41:48 -07001537
Tom Cherry23319eb2018-11-30 16:16:05 -08001538 // mount(2) returned an error, handle the encryptable/formattable case.
Eric Biggers63fb1952021-11-08 16:38:53 -08001539 if (mount_errno != EBUSY && mount_errno != EACCES &&
1540 should_use_metadata_encryption(attempted_entry)) {
Paul Lawrence323959e2019-06-25 14:36:52 -07001541 if (!call_vdc({"cryptfs", "mountFstab", attempted_entry.blk_device,
Tom Cherry3a803eb2019-09-25 16:23:50 -07001542 attempted_entry.mount_point},
1543 nullptr)) {
Paul Crowleyc6846962018-01-30 09:56:03 -08001544 ++error_count;
Qilin Tan12d95df2020-11-02 11:25:09 +08001545 } else if (current_entry.mount_point == "/data") {
1546 userdata_mounted = true;
Paul Crowleyc6846962018-01-30 09:56:03 -08001547 }
Paul Lawrence9dbe97b2017-04-21 12:41:48 -07001548 encryptable = FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED;
Paul Crowleyc6846962018-01-30 09:56:03 -08001549 continue;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001550 } else {
Bowgo Tsai59af33c2017-05-24 18:51:36 +08001551 // fs_options might be null so we cannot use PERROR << directly.
1552 // Use StringPrintf to output "(null)" instead.
Tom Cherry23319eb2018-11-30 16:16:05 -08001553 if (attempted_entry.fs_mgr_flags.no_fail) {
Bowgo Tsai59af33c2017-05-24 18:51:36 +08001554 PERROR << android::base::StringPrintf(
Tom Cherry23319eb2018-11-30 16:16:05 -08001555 "Ignoring failure to mount an un-encryptable or wiped "
1556 "partition on %s at %s options: %s",
1557 attempted_entry.blk_device.c_str(), attempted_entry.mount_point.c_str(),
1558 attempted_entry.fs_options.c_str());
Daniel Rosenbergd38e3c52016-04-07 20:10:25 -07001559 } else {
Bowgo Tsai59af33c2017-05-24 18:51:36 +08001560 PERROR << android::base::StringPrintf(
Tom Cherry23319eb2018-11-30 16:16:05 -08001561 "Failed to mount an un-encryptable or wiped partition "
1562 "on %s at %s options: %s",
1563 attempted_entry.blk_device.c_str(), attempted_entry.mount_point.c_str(),
1564 attempted_entry.fs_options.c_str());
Daniel Rosenbergd38e3c52016-04-07 20:10:25 -07001565 ++error_count;
1566 }
Mohamad Ayyash38afe5f2014-03-10 15:40:29 -07001567 continue;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001568 }
1569 }
1570
Paul Crowley9acab5a2020-08-14 11:05:05 -07001571 set_type_property(encryptable);
1572
Mark Salyzynd9e6c202018-06-20 14:08:09 -07001573#if ALLOW_ADBD_DISABLE_VERITY == 1 // "userdebug" build
Mark Salyzynf35db9b2018-09-20 15:23:00 -07001574 fs_mgr_overlayfs_mount_all(fstab);
Mark Salyzynd9e6c202018-06-20 14:08:09 -07001575#endif
1576
Mohamad Ayyash38afe5f2014-03-10 15:40:29 -07001577 if (error_count) {
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001578 return {FS_MGR_MNTALL_FAIL, userdata_mounted};
Mohamad Ayyash38afe5f2014-03-10 15:40:29 -07001579 } else {
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001580 return {encryptable, userdata_mounted};
Mohamad Ayyash38afe5f2014-03-10 15:40:29 -07001581 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001582}
1583
Yifan Hong402633d2019-04-09 10:11:34 -07001584int fs_mgr_umount_all(android::fs_mgr::Fstab* fstab) {
1585 AvbUniquePtr avb_handle(nullptr);
1586 int ret = FsMgrUmountStatus::SUCCESS;
1587 for (auto& current_entry : *fstab) {
1588 if (!IsMountPointMounted(current_entry.mount_point)) {
1589 continue;
1590 }
1591
1592 if (umount(current_entry.mount_point.c_str()) == -1) {
1593 PERROR << "Failed to umount " << current_entry.mount_point;
1594 ret |= FsMgrUmountStatus::ERROR_UMOUNT;
1595 continue;
1596 }
1597
1598 if (current_entry.fs_mgr_flags.logical) {
1599 if (!fs_mgr_update_logical_partition(&current_entry)) {
1600 LERROR << "Could not get logical partition blk_device, skipping!";
1601 ret |= FsMgrUmountStatus::ERROR_DEVICE_MAPPER;
1602 continue;
1603 }
1604 }
1605
1606 if (current_entry.fs_mgr_flags.avb || !current_entry.avb_keys.empty()) {
1607 if (!AvbHandle::TearDownAvbHashtree(&current_entry, true /* wait */)) {
1608 LERROR << "Failed to tear down AVB on mount point: " << current_entry.mount_point;
1609 ret |= FsMgrUmountStatus::ERROR_VERITY;
1610 continue;
1611 }
Yifan Hong402633d2019-04-09 10:11:34 -07001612 }
1613 }
1614 return ret;
1615}
1616
Nikita Ioffe7b41a152020-03-25 00:06:51 +00001617static std::chrono::milliseconds GetMillisProperty(const std::string& name,
1618 std::chrono::milliseconds default_value) {
1619 auto value = GetUintProperty(name, static_cast<uint64_t>(default_value.count()));
1620 return std::chrono::milliseconds(std::move(value));
1621}
1622
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001623static bool fs_mgr_unmount_all_data_mounts(const std::string& data_block_device) {
1624 LINFO << __FUNCTION__ << "(): about to umount everything on top of " << data_block_device;
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001625 Timer t;
Nikita Ioffe7b41a152020-03-25 00:06:51 +00001626 auto timeout = GetMillisProperty("init.userspace_reboot.userdata_remount.timeoutmillis", 5s);
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001627 while (true) {
1628 bool umount_done = true;
1629 Fstab proc_mounts;
1630 if (!ReadFstabFromFile("/proc/mounts", &proc_mounts)) {
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001631 LERROR << __FUNCTION__ << "(): Can't read /proc/mounts";
Greg Kaiserd8fdf602019-12-20 19:39:16 -08001632 return false;
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001633 }
1634 // Now proceed with other bind mounts on top of /data.
1635 for (const auto& entry : proc_mounts) {
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001636 std::string block_device;
1637 if (StartsWith(entry.blk_device, "/dev/block") &&
1638 !Realpath(entry.blk_device, &block_device)) {
1639 PWARNING << __FUNCTION__ << "(): failed to realpath " << entry.blk_device;
1640 block_device = entry.blk_device;
1641 }
1642 if (data_block_device == block_device) {
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001643 if (umount2(entry.mount_point.c_str(), 0) != 0) {
Nikita Ioffeb03e0cf2020-01-13 16:05:07 +00001644 PERROR << __FUNCTION__ << "(): Failed to umount " << entry.mount_point;
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001645 umount_done = false;
1646 }
1647 }
1648 }
1649 if (umount_done) {
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001650 LINFO << __FUNCTION__ << "(): Unmounting /data took " << t;
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001651 return true;
1652 }
1653 if (t.duration() > timeout) {
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001654 LERROR << __FUNCTION__ << "(): Timed out unmounting all mounts on "
1655 << data_block_device;
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001656 Fstab remaining_mounts;
1657 if (!ReadFstabFromFile("/proc/mounts", &remaining_mounts)) {
1658 LERROR << __FUNCTION__ << "(): Can't read /proc/mounts";
1659 } else {
1660 LERROR << __FUNCTION__ << "(): Following mounts remaining";
1661 for (const auto& e : remaining_mounts) {
1662 LERROR << __FUNCTION__ << "(): mount point: " << e.mount_point
1663 << " block device: " << e.blk_device;
1664 }
1665 }
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001666 return false;
1667 }
1668 std::this_thread::sleep_for(50ms);
1669 }
1670}
1671
Nikita Ioffe17824f02020-03-06 17:36:05 +00001672static bool UnwindDmDeviceStack(const std::string& block_device,
1673 std::vector<std::string>* dm_stack) {
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001674 if (!StartsWith(block_device, "/dev/block/")) {
1675 LWARNING << block_device << " is not a block device";
Nikita Ioffe17824f02020-03-06 17:36:05 +00001676 return false;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001677 }
Nikita Ioffe17824f02020-03-06 17:36:05 +00001678 std::string current = block_device;
1679 DeviceMapper& dm = DeviceMapper::Instance();
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001680 while (true) {
Nikita Ioffe17824f02020-03-06 17:36:05 +00001681 dm_stack->push_back(current);
1682 if (!dm.IsDmBlockDevice(current)) {
1683 break;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001684 }
Nikita Ioffe17824f02020-03-06 17:36:05 +00001685 auto parent = dm.GetParentBlockDeviceByPath(current);
1686 if (!parent) {
1687 return false;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001688 }
Nikita Ioffe17824f02020-03-06 17:36:05 +00001689 current = *parent;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001690 }
Nikita Ioffe17824f02020-03-06 17:36:05 +00001691 return true;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001692}
1693
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001694FstabEntry* fs_mgr_get_mounted_entry_for_userdata(Fstab* fstab,
1695 const std::string& data_block_device) {
Nikita Ioffe17824f02020-03-06 17:36:05 +00001696 std::vector<std::string> dm_stack;
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001697 if (!UnwindDmDeviceStack(data_block_device, &dm_stack)) {
1698 LERROR << "Failed to unwind dm-device stack for " << data_block_device;
Nikita Ioffe17824f02020-03-06 17:36:05 +00001699 return nullptr;
1700 }
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001701 for (auto& entry : *fstab) {
1702 if (entry.mount_point != "/data") {
1703 continue;
1704 }
1705 std::string block_device;
Nikita Ioffe17824f02020-03-06 17:36:05 +00001706 if (entry.fs_mgr_flags.logical) {
1707 if (!fs_mgr_update_logical_partition(&entry)) {
1708 LERROR << "Failed to update logic partition " << entry.blk_device;
1709 continue;
1710 }
1711 block_device = entry.blk_device;
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001712 } else if (!Realpath(entry.blk_device, &block_device)) {
1713 PWARNING << "Failed to realpath " << entry.blk_device;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001714 block_device = entry.blk_device;
1715 }
Nikita Ioffe17824f02020-03-06 17:36:05 +00001716 if (std::find(dm_stack.begin(), dm_stack.end(), block_device) != dm_stack.end()) {
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001717 return &entry;
1718 }
1719 }
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001720 LERROR << "Didn't find entry that was used to mount /data onto " << data_block_device;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001721 return nullptr;
1722}
1723
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001724// TODO(b/143970043): return different error codes based on which step failed.
Nikita Ioffe12a36072019-10-23 20:11:32 +01001725int fs_mgr_remount_userdata_into_checkpointing(Fstab* fstab) {
Nikita Ioffe0dda4232019-12-16 23:22:55 +00001726 Fstab proc_mounts;
1727 if (!ReadFstabFromFile("/proc/mounts", &proc_mounts)) {
1728 LERROR << "Can't read /proc/mounts";
1729 return -1;
1730 }
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001731 auto mounted_entry = GetEntryForMountPoint(&proc_mounts, "/data");
1732 if (mounted_entry == nullptr) {
Nikita Ioffed572c802019-12-09 21:13:08 +00001733 LERROR << "/data is not mounted";
1734 return -1;
1735 }
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001736 std::string block_device;
1737 if (!Realpath(mounted_entry->blk_device, &block_device)) {
1738 PERROR << "Failed to realpath " << mounted_entry->blk_device;
1739 return -1;
1740 }
1741 auto fstab_entry = fs_mgr_get_mounted_entry_for_userdata(fstab, block_device);
Nikita Ioffed572c802019-12-09 21:13:08 +00001742 if (fstab_entry == nullptr) {
Nikita Ioffe12a36072019-10-23 20:11:32 +01001743 LERROR << "Can't find /data in fstab";
1744 return -1;
1745 }
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001746 bool force_umount = GetBoolProperty("sys.init.userdata_remount.force_umount", false);
1747 if (force_umount) {
1748 LINFO << "Will force an umount of userdata even if it's not required";
1749 }
1750 if (!force_umount && !SupportsCheckpoint(fstab_entry)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +01001751 LINFO << "Userdata doesn't support checkpointing. Nothing to do";
1752 return 0;
1753 }
1754 CheckpointManager checkpoint_manager;
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001755 if (!force_umount && !checkpoint_manager.NeedsCheckpoint()) {
Nikita Ioffe12a36072019-10-23 20:11:32 +01001756 LINFO << "Checkpointing not needed. Don't remount";
1757 return 0;
1758 }
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001759 if (!force_umount && fstab_entry->fs_mgr_flags.checkpoint_fs) {
Nikita Ioffe12a36072019-10-23 20:11:32 +01001760 // Userdata is f2fs, simply remount it.
Nikita Ioffed572c802019-12-09 21:13:08 +00001761 if (!checkpoint_manager.Update(fstab_entry)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +01001762 LERROR << "Failed to remount userdata in checkpointing mode";
1763 return -1;
1764 }
Nikita Ioffed572c802019-12-09 21:13:08 +00001765 if (mount(block_device.c_str(), fstab_entry->mount_point.c_str(), "none",
1766 MS_REMOUNT | fstab_entry->flags, fstab_entry->fs_options.c_str()) != 0) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001767 PERROR << "Failed to remount userdata in checkpointing mode";
Nikita Ioffe12a36072019-10-23 20:11:32 +01001768 return -1;
1769 }
1770 } else {
Nikita Ioffed572c802019-12-09 21:13:08 +00001771 LINFO << "Unmounting /data before remounting into checkpointing mode";
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001772 if (!fs_mgr_unmount_all_data_mounts(block_device)) {
1773 LERROR << "Failed to umount /data";
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001774 return -1;
1775 }
1776 DeviceMapper& dm = DeviceMapper::Instance();
Nikita Ioffed572c802019-12-09 21:13:08 +00001777 while (dm.IsDmBlockDevice(block_device)) {
1778 auto next_device = dm.GetParentBlockDeviceByPath(block_device);
1779 auto name = dm.GetDmDeviceNameByPath(block_device);
1780 if (!name) {
1781 LERROR << "Failed to get dm-name for " << block_device;
1782 return -1;
1783 }
1784 LINFO << "Deleting " << block_device << " named " << *name;
1785 if (!dm.DeleteDevice(*name, 3s)) {
1786 return -1;
1787 }
1788 if (!next_device) {
1789 LERROR << "Failed to find parent device for " << block_device;
1790 }
1791 block_device = *next_device;
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001792 }
Nikita Ioffed572c802019-12-09 21:13:08 +00001793 LINFO << "Remounting /data";
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001794 // TODO(b/143970043): remove this hack after fs_mgr_mount_all is refactored.
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001795 auto result = fs_mgr_mount_all(fstab, MOUNT_MODE_ONLY_USERDATA);
1796 return result.code == FS_MGR_MNTALL_FAIL ? -1 : 0;
Nikita Ioffe12a36072019-10-23 20:11:32 +01001797 }
1798 return 0;
1799}
1800
Tom Cherry23319eb2018-11-30 16:16:05 -08001801// wrapper to __mount() and expects a fully prepared fstab_rec,
1802// unlike fs_mgr_do_mount which does more things with avb / verity etc.
Tom Cherrya7f1a9f2020-11-19 11:39:39 -08001803int fs_mgr_do_mount_one(const FstabEntry& entry, const std::string& alt_mount_point) {
Will Shiu589b7df2020-01-03 16:05:00 +08001804 // First check the filesystem if requested.
1805 if (entry.fs_mgr_flags.wait && !WaitForFile(entry.blk_device, 20s)) {
1806 LERROR << "Skipping mounting '" << entry.blk_device << "'";
1807 }
1808
Tom Cherrya7f1a9f2020-11-19 11:39:39 -08001809 auto& mount_point = alt_mount_point.empty() ? entry.mount_point : alt_mount_point;
Tom Cherry81ae0752018-07-30 16:23:49 -07001810
Tom Cherrya7f1a9f2020-11-19 11:39:39 -08001811 // Run fsck if needed
Jaegeuk Kim95477262021-12-29 14:44:22 -08001812 int ret = prepare_fs_for_mount(entry.blk_device, entry, mount_point);
1813 // Wiped case doesn't require to try __mount below.
1814 if (ret & FS_STAT_INVALID_MAGIC) {
1815 return FS_MGR_DOMNT_FAILED;
1816 }
Tom Cherrya7f1a9f2020-11-19 11:39:39 -08001817
Jaegeuk Kim95477262021-12-29 14:44:22 -08001818 ret = __mount(entry.blk_device, mount_point, entry);
Sandeep Patil56f9ada2017-02-14 14:00:14 -08001819 if (ret) {
1820 ret = (errno == EBUSY) ? FS_MGR_DOMNT_BUSY : FS_MGR_DOMNT_FAILED;
1821 }
1822
1823 return ret;
1824}
1825
Tom Cherry23319eb2018-11-30 16:16:05 -08001826// If tmp_mount_point is non-null, mount the filesystem there. This is for the
1827// tmp mount we do to check the user password
1828// If multiple fstab entries are to be mounted on "n_name", it will try to mount each one
1829// in turn, and stop on 1st success, or no more match.
1830static int fs_mgr_do_mount_helper(Fstab* fstab, const std::string& n_name,
1831 const std::string& n_blk_device, const char* tmp_mount_point,
Paul Lawrence20553642020-06-12 07:32:23 -07001832 int needs_checkpoint, bool metadata_encrypted) {
JP Abgrall5c01dac2014-06-18 14:54:37 -07001833 int mount_errors = 0;
1834 int first_mount_errno = 0;
Tom Cherry23319eb2018-11-30 16:16:05 -08001835 std::string mount_point;
Paul Lawrence20553642020-06-12 07:32:23 -07001836 CheckpointManager checkpoint_manager(needs_checkpoint, metadata_encrypted);
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001837 AvbUniquePtr avb_handle(nullptr);
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001838
Ken Sumrallab6b8522013-02-13 12:58:40 -08001839 if (!fstab) {
Bowgo Tsai359bed32017-04-27 15:44:39 +08001840 return FS_MGR_DOMNT_FAILED;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001841 }
1842
Tom Cherry23319eb2018-11-30 16:16:05 -08001843 for (auto& fstab_entry : *fstab) {
1844 if (!fs_match(fstab_entry.mount_point, n_name)) {
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001845 continue;
1846 }
1847
Tom Cherry23319eb2018-11-30 16:16:05 -08001848 // We found our match.
1849 // If this swap or a raw partition, report an error.
1850 if (fstab_entry.fs_type == "swap" || fstab_entry.fs_type == "emmc" ||
1851 fstab_entry.fs_type == "mtd") {
1852 LERROR << "Cannot mount filesystem of type " << fstab_entry.fs_type << " on "
1853 << n_blk_device;
Bowgo Tsai359bed32017-04-27 15:44:39 +08001854 return FS_MGR_DOMNT_FAILED;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001855 }
1856
Tom Cherry23319eb2018-11-30 16:16:05 -08001857 if (fstab_entry.fs_mgr_flags.logical) {
1858 if (!fs_mgr_update_logical_partition(&fstab_entry)) {
David Anderson62e5b202018-05-01 17:09:17 -07001859 LERROR << "Could not set up logical partition, skipping!";
1860 continue;
1861 }
1862 }
1863
David Anderson671bd812020-01-24 19:19:27 -08001864 WrapUserdataIfNeeded(&fstab_entry, n_blk_device);
1865
Paul Lawrence323959e2019-06-25 14:36:52 -07001866 if (!checkpoint_manager.Update(&fstab_entry, n_blk_device)) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001867 LERROR << "Could not set up checkpoint partition, skipping!";
1868 continue;
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001869 }
1870
Tom Cherry23319eb2018-11-30 16:16:05 -08001871 // First check the filesystem if requested.
David Anderson5c475c72019-06-11 17:40:49 -07001872 if (fstab_entry.fs_mgr_flags.wait && !WaitForFile(n_blk_device, 20s)) {
Jinguang Dong9d344962017-06-13 10:20:34 +08001873 LERROR << "Skipping mounting '" << n_blk_device << "'";
1874 continue;
Ken Sumrallab6b8522013-02-13 12:58:40 -08001875 }
1876
Tom Cherrya7f1a9f2020-11-19 11:39:39 -08001877 // Now mount it where requested */
1878 if (tmp_mount_point) {
1879 mount_point = tmp_mount_point;
1880 } else {
1881 mount_point = fstab_entry.mount_point;
1882 }
1883
1884 int fs_stat = prepare_fs_for_mount(n_blk_device, fstab_entry, mount_point);
liminghao9a0fd1d2016-07-22 11:48:14 +08001885
Tom Cherry23319eb2018-11-30 16:16:05 -08001886 if (fstab_entry.fs_mgr_flags.avb) {
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001887 if (!avb_handle) {
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001888 avb_handle = AvbHandle::Open();
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001889 if (!avb_handle) {
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001890 LERROR << "Failed to open AvbHandle";
Bowgo Tsai359bed32017-04-27 15:44:39 +08001891 return FS_MGR_DOMNT_FAILED;
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001892 }
1893 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001894 if (avb_handle->SetUpAvbHashtree(&fstab_entry, true /* wait_for_verity_dev */) ==
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001895 AvbHashtreeResult::kFail) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001896 LERROR << "Failed to set up AVB on partition: " << fstab_entry.mount_point
1897 << ", skipping!";
1898 // Skips mounting the device.
bowgotsaib51722b2017-01-11 22:21:38 +08001899 continue;
1900 }
Bowgo Tsaif3e28e12019-02-20 21:53:47 +08001901 } else if (!fstab_entry.avb_keys.empty()) {
Bowgo Tsaidefe1cb2019-01-25 12:07:09 +08001902 if (AvbHandle::SetUpStandaloneAvbHashtree(&fstab_entry) == AvbHashtreeResult::kFail) {
1903 LERROR << "Failed to set up AVB on standalone partition: "
1904 << fstab_entry.mount_point << ", skipping!";
1905 // Skips mounting the device.
1906 continue;
1907 }
Geremy Condra3ad3d1c2013-02-22 18:11:41 -08001908 }
1909
Keun-young Park40db04d2017-04-13 17:31:08 -07001910 int retry_count = 2;
1911 while (retry_count-- > 0) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001912 if (!__mount(n_blk_device, mount_point, fstab_entry)) {
Keun-young Park40db04d2017-04-13 17:31:08 -07001913 fs_stat &= ~FS_STAT_FULL_MOUNT_FAILED;
Bowgo Tsai359bed32017-04-27 15:44:39 +08001914 return FS_MGR_DOMNT_SUCCESS;
Keun-young Park40db04d2017-04-13 17:31:08 -07001915 } else {
1916 if (retry_count <= 0) break; // run check_fs only once
1917 if (!first_mount_errno) first_mount_errno = errno;
1918 mount_errors++;
1919 fs_stat |= FS_STAT_FULL_MOUNT_FAILED;
1920 // try again after fsck
Tom Cherrya7f1a9f2020-11-19 11:39:39 -08001921 check_fs(n_blk_device, fstab_entry.fs_type, mount_point, &fs_stat);
Keun-young Park40db04d2017-04-13 17:31:08 -07001922 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001923 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001924 log_fs_stat(fstab_entry.blk_device, fs_stat);
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001925 }
Bowgo Tsai359bed32017-04-27 15:44:39 +08001926
1927 // Reach here means the mount attempt fails.
JP Abgrall5c01dac2014-06-18 14:54:37 -07001928 if (mount_errors) {
Bowgo Tsai359bed32017-04-27 15:44:39 +08001929 PERROR << "Cannot mount filesystem on " << n_blk_device << " at " << mount_point;
1930 if (first_mount_errno == EBUSY) return FS_MGR_DOMNT_BUSY;
JP Abgrall5c01dac2014-06-18 14:54:37 -07001931 } else {
Tom Cherry23319eb2018-11-30 16:16:05 -08001932 // We didn't find a match, say so and return an error.
Bowgo Tsai359bed32017-04-27 15:44:39 +08001933 LERROR << "Cannot find mount point " << n_name << " in fstab";
JP Abgrall5c01dac2014-06-18 14:54:37 -07001934 }
Bowgo Tsai359bed32017-04-27 15:44:39 +08001935 return FS_MGR_DOMNT_FAILED;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001936}
1937
Tom Cherry2e545f82019-01-29 08:49:57 -08001938int fs_mgr_do_mount(Fstab* fstab, const char* n_name, char* n_blk_device, char* tmp_mount_point) {
Paul Lawrence20553642020-06-12 07:32:23 -07001939 return fs_mgr_do_mount_helper(fstab, n_name, n_blk_device, tmp_mount_point, -1, false);
Tom Cherry2e545f82019-01-29 08:49:57 -08001940}
1941
1942int fs_mgr_do_mount(Fstab* fstab, const char* n_name, char* n_blk_device, char* tmp_mount_point,
Paul Lawrence20553642020-06-12 07:32:23 -07001943 bool needs_checkpoint, bool metadata_encrypted) {
1944 return fs_mgr_do_mount_helper(fstab, n_name, n_blk_device, tmp_mount_point, needs_checkpoint,
1945 metadata_encrypted);
Tom Cherry2e545f82019-01-29 08:49:57 -08001946}
1947
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001948/*
1949 * mount a tmpfs filesystem at the given point.
1950 * return 0 on success, non-zero on failure.
1951 */
Wei Wang4d71bc52017-02-24 17:41:38 -08001952int fs_mgr_do_tmpfs_mount(const char *n_name)
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001953{
1954 int ret;
1955
Luis Hector Chavezf29b39d2017-07-10 15:25:55 -07001956 ret = mount("tmpfs", n_name, "tmpfs", MS_NOATIME | MS_NOSUID | MS_NODEV | MS_NOEXEC,
1957 CRYPTO_TMPFS_OPTIONS);
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001958 if (ret < 0) {
bowgotsai47878de2017-01-23 14:04:34 +08001959 LERROR << "Cannot mount tmpfs filesystem at " << n_name;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001960 return -1;
1961 }
1962
1963 /* Success */
1964 return 0;
1965}
1966
Bart Van Asscheec5f6352021-07-29 13:50:43 -07001967static bool ConfigureIoScheduler(const std::string& device_path) {
1968 if (!StartsWith(device_path, "/dev/")) {
1969 LERROR << __func__ << ": invalid argument " << device_path;
1970 return false;
1971 }
1972
1973 const std::string iosched_path =
1974 StringPrintf("/sys/block/%s/queue/scheduler", Basename(device_path).c_str());
1975 unique_fd iosched_fd(open(iosched_path.c_str(), O_RDWR | O_CLOEXEC));
1976 if (iosched_fd.get() == -1) {
1977 PERROR << __func__ << ": failed to open " << iosched_path;
1978 return false;
1979 }
1980
1981 // Kernels before v4.1 only support 'noop'. Kernels [v4.1, v5.0) support
1982 // 'noop' and 'none'. Kernels v5.0 and later only support 'none'.
1983 static constexpr const std::array<std::string_view, 2> kNoScheduler = {"none", "noop"};
1984
1985 for (const std::string_view& scheduler : kNoScheduler) {
1986 int ret = write(iosched_fd.get(), scheduler.data(), scheduler.size());
1987 if (ret > 0) {
1988 return true;
1989 }
1990 }
1991
1992 PERROR << __func__ << ": failed to write to " << iosched_path;
1993 return false;
1994}
1995
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08001996static bool InstallZramDevice(const std::string& device) {
1997 if (!android::base::WriteStringToFile(device, ZRAM_BACK_DEV)) {
1998 PERROR << "Cannot write " << device << " in: " << ZRAM_BACK_DEV;
1999 return false;
2000 }
2001 LINFO << "Success to set " << device << " to " << ZRAM_BACK_DEV;
2002 return true;
2003}
2004
Minchan Kim12e96152019-10-15 14:41:18 -07002005static bool PrepareZramBackingDevice(off64_t size) {
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002006
Minchan Kim12e96152019-10-15 14:41:18 -07002007 constexpr const char* file_path = "/data/per_boot/zram_swap";
2008 if (size == 0) return true;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002009
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002010 // Prepare target path
Minchan Kim12e96152019-10-15 14:41:18 -07002011 unique_fd target_fd(TEMP_FAILURE_RETRY(open(file_path, O_RDWR | O_CREAT | O_CLOEXEC, 0600)));
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002012 if (target_fd.get() == -1) {
Minchan Kim12e96152019-10-15 14:41:18 -07002013 PERROR << "Cannot open target path: " << file_path;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002014 return false;
2015 }
2016 if (fallocate(target_fd.get(), 0, 0, size) < 0) {
Minchan Kim12e96152019-10-15 14:41:18 -07002017 PERROR << "Cannot truncate target path: " << file_path;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002018 return false;
2019 }
2020
Nikita Ioffebcaeb702020-04-20 17:38:17 +01002021 // Allocate loop device and attach it to file_path.
2022 LoopControl loop_control;
Bart Van Assche06b95de2021-07-29 13:53:53 -07002023 std::string loop_device;
2024 if (!loop_control.Attach(target_fd.get(), 5s, &loop_device)) {
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002025 return false;
2026 }
2027
Bart Van Asscheec5f6352021-07-29 13:50:43 -07002028 ConfigureIoScheduler(loop_device);
2029
Jiyong Parkd185d4a2021-12-11 10:45:20 +09002030 if (auto ret = ConfigureQueueDepth(loop_device, "/"); !ret.ok()) {
2031 LOG(DEBUG) << "Failed to config queue depth: " << ret.error().message();
2032 }
Bart Van Assche0223cd82021-08-06 10:21:12 -07002033
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002034 // set block size & direct IO
Bart Van Assche06b95de2021-07-29 13:53:53 -07002035 unique_fd loop_fd(TEMP_FAILURE_RETRY(open(loop_device.c_str(), O_RDWR | O_CLOEXEC)));
2036 if (loop_fd.get() == -1) {
2037 PERROR << "Cannot open " << loop_device;
Nikita Ioffebcaeb702020-04-20 17:38:17 +01002038 return false;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002039 }
Liangcai Fand884ba52021-09-06 17:56:18 +08002040 if (!LoopControl::SetAutoClearStatus(loop_fd.get())) {
2041 PERROR << "Failed set LO_FLAGS_AUTOCLEAR for " << loop_device;
2042 }
Bart Van Assche06b95de2021-07-29 13:53:53 -07002043 if (!LoopControl::EnableDirectIo(loop_fd.get())) {
Nikita Ioffebcaeb702020-04-20 17:38:17 +01002044 return false;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002045 }
2046
Bart Van Assche06b95de2021-07-29 13:53:53 -07002047 return InstallZramDevice(loop_device);
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002048}
2049
Tom Cherry30554572018-11-30 15:21:04 -08002050bool fs_mgr_swapon_all(const Fstab& fstab) {
2051 bool ret = true;
2052 for (const auto& entry : fstab) {
2053 // Skip non-swap entries.
2054 if (entry.fs_type != "swap") {
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002055 continue;
2056 }
2057
Tom Cherry30554572018-11-30 15:21:04 -08002058 if (entry.zram_size > 0) {
JeongHyeon Leec159edc2021-06-24 11:21:08 +09002059 if (!PrepareZramBackingDevice(entry.zram_backingdev_size)) {
Minchan Kim12e96152019-10-15 14:41:18 -07002060 LERROR << "Failure of zram backing device file for '" << entry.blk_device << "'";
2061 }
Tom Cherry30554572018-11-30 15:21:04 -08002062 // A zram_size was specified, so we need to configure the
2063 // device. There is no point in having multiple zram devices
2064 // on a system (all the memory comes from the same pool) so
2065 // we can assume the device number is 0.
2066 if (entry.max_comp_streams >= 0) {
Tom Cherryf274e782018-10-03 13:13:41 -07002067 auto zram_mcs_fp = std::unique_ptr<FILE, decltype(&fclose)>{
2068 fopen(ZRAM_CONF_MCS, "re"), fclose};
Tom Cherry30554572018-11-30 15:21:04 -08002069 if (zram_mcs_fp == nullptr) {
Tom Cherryf274e782018-10-03 13:13:41 -07002070 LERROR << "Unable to open zram conf comp device " << ZRAM_CONF_MCS;
Tom Cherry30554572018-11-30 15:21:04 -08002071 ret = false;
Tom Cherryf274e782018-10-03 13:13:41 -07002072 continue;
2073 }
Tom Cherry30554572018-11-30 15:21:04 -08002074 fprintf(zram_mcs_fp.get(), "%d\n", entry.max_comp_streams);
Peter Enderborg4d217f02016-08-26 15:09:35 +02002075 }
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002076
Tom Cherryf274e782018-10-03 13:13:41 -07002077 auto zram_fp =
2078 std::unique_ptr<FILE, decltype(&fclose)>{fopen(ZRAM_CONF_DEV, "re+"), fclose};
Tom Cherry30554572018-11-30 15:21:04 -08002079 if (zram_fp == nullptr) {
bowgotsai47878de2017-01-23 14:04:34 +08002080 LERROR << "Unable to open zram conf device " << ZRAM_CONF_DEV;
Tom Cherry30554572018-11-30 15:21:04 -08002081 ret = false;
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002082 continue;
2083 }
Tom Cherry30554572018-11-30 15:21:04 -08002084 fprintf(zram_fp.get(), "%" PRId64 "\n", entry.zram_size);
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002085 }
2086
David Anderson5c475c72019-06-11 17:40:49 -07002087 if (entry.fs_mgr_flags.wait && !WaitForFile(entry.blk_device, 20s)) {
Tom Cherry30554572018-11-30 15:21:04 -08002088 LERROR << "Skipping mkswap for '" << entry.blk_device << "'";
2089 ret = false;
Jinguang Dong9d344962017-06-13 10:20:34 +08002090 continue;
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002091 }
2092
Tom Cherry30554572018-11-30 15:21:04 -08002093 // Initialize the swap area.
2094 const char* mkswap_argv[2] = {
2095 MKSWAP_BIN,
2096 entry.blk_device.c_str(),
2097 };
Tom Cherry3a803eb2019-09-25 16:23:50 -07002098 int err = logwrap_fork_execvp(ARRAY_SIZE(mkswap_argv), mkswap_argv, nullptr, false,
2099 LOG_KLOG, false, nullptr);
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002100 if (err) {
Tom Cherry30554572018-11-30 15:21:04 -08002101 LERROR << "mkswap failed for " << entry.blk_device;
2102 ret = false;
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002103 continue;
2104 }
2105
2106 /* If -1, then no priority was specified in fstab, so don't set
2107 * SWAP_FLAG_PREFER or encode the priority */
Tom Cherry30554572018-11-30 15:21:04 -08002108 int flags = 0;
2109 if (entry.swap_prio >= 0) {
2110 flags = (entry.swap_prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK;
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002111 flags |= SWAP_FLAG_PREFER;
2112 } else {
2113 flags = 0;
2114 }
Tom Cherry30554572018-11-30 15:21:04 -08002115 err = swapon(entry.blk_device.c_str(), flags);
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002116 if (err) {
Tom Cherry30554572018-11-30 15:21:04 -08002117 LERROR << "swapon failed for " << entry.blk_device;
2118 ret = false;
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002119 }
2120 }
2121
2122 return ret;
2123}
2124
Tom Cherrycf80b6d2019-01-07 14:25:31 -08002125bool fs_mgr_is_verity_enabled(const FstabEntry& entry) {
David Anderson6cdd9bd2021-10-29 16:13:22 -07002126 if (!entry.fs_mgr_flags.avb) {
Bowgo Tsaiaaf70e72017-03-02 00:03:56 +08002127 return false;
2128 }
2129
David Anderson40b59482018-06-25 17:55:01 -07002130 DeviceMapper& dm = DeviceMapper::Instance();
2131
David Anderson7082f682019-03-18 19:17:11 -07002132 std::string mount_point = GetVerityDeviceName(entry);
Tom Cherrycf80b6d2019-01-07 14:25:31 -08002133 if (dm.GetState(mount_point) == DmDeviceState::INVALID) {
2134 return false;
2135 }
2136
Tom Cherrycf80b6d2019-01-07 14:25:31 -08002137 std::vector<DeviceMapper::TargetInfo> table;
2138 if (!dm.GetTableStatus(mount_point, &table) || table.empty() || table[0].data.empty()) {
David Anderson6cdd9bd2021-10-29 16:13:22 -07002139 return false;
Tom Cherrycf80b6d2019-01-07 14:25:31 -08002140 }
2141
David Anderson6cdd9bd2021-10-29 16:13:22 -07002142 auto status = table[0].data.c_str();
Tom Cherrycf80b6d2019-01-07 14:25:31 -08002143 if (*status == 'C' || *status == 'V') {
2144 return true;
2145 }
2146
2147 return false;
Bowgo Tsaiaaf70e72017-03-02 00:03:56 +08002148}
David Anderson5cbd2e42018-09-27 10:53:04 -07002149
Tianjie10bec652021-08-30 16:10:09 -07002150std::optional<HashtreeInfo> fs_mgr_get_hashtree_info(const android::fs_mgr::FstabEntry& entry) {
David Anderson6cdd9bd2021-10-29 16:13:22 -07002151 if (!entry.fs_mgr_flags.avb) {
Tianjie10bec652021-08-30 16:10:09 -07002152 return {};
Tianjie327237d2021-01-20 19:02:34 -08002153 }
2154 DeviceMapper& dm = DeviceMapper::Instance();
2155 std::string device = GetVerityDeviceName(entry);
2156
2157 std::vector<DeviceMapper::TargetInfo> table;
2158 if (dm.GetState(device) == DmDeviceState::INVALID || !dm.GetTableInfo(device, &table)) {
Tianjie10bec652021-08-30 16:10:09 -07002159 return {};
Tianjie327237d2021-01-20 19:02:34 -08002160 }
2161 for (const auto& target : table) {
2162 if (strcmp(target.spec.target_type, "verity") != 0) {
2163 continue;
2164 }
2165
2166 // The format is stable for dm-verity version 0 & 1. And the data is expected to have
2167 // the fixed format:
2168 // <version> <dev> <hash_dev> <data_block_size> <hash_block_size> <num_data_blocks>
2169 // <hash_start_block> <algorithm> <digest> <salt>
2170 // Details in https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/verity.html
2171
2172 std::vector<std::string> tokens = android::base::Split(target.data, " \t\r\n");
2173 if (tokens[0] != "0" && tokens[0] != "1") {
2174 LOG(WARNING) << "Unrecognized device mapper version in " << target.data;
Tianjie10bec652021-08-30 16:10:09 -07002175 return {};
Tianjie327237d2021-01-20 19:02:34 -08002176 }
2177
Tianjie10bec652021-08-30 16:10:09 -07002178 // Hashtree algorithm & root digest are the 8th & 9th token in the output.
2179 return HashtreeInfo{.algorithm = android::base::Trim(tokens[7]),
2180 .root_digest = android::base::Trim(tokens[8])};
Tianjie327237d2021-01-20 19:02:34 -08002181 }
2182
Tianjie10bec652021-08-30 16:10:09 -07002183 return {};
Tianjie327237d2021-01-20 19:02:34 -08002184}
2185
David Andersonee725f62019-03-13 19:10:48 -07002186bool fs_mgr_verity_is_check_at_most_once(const android::fs_mgr::FstabEntry& entry) {
David Anderson6cdd9bd2021-10-29 16:13:22 -07002187 if (!entry.fs_mgr_flags.avb) {
David Andersonee725f62019-03-13 19:10:48 -07002188 return false;
2189 }
2190
2191 DeviceMapper& dm = DeviceMapper::Instance();
David Anderson7082f682019-03-18 19:17:11 -07002192 std::string device = GetVerityDeviceName(entry);
David Andersonee725f62019-03-13 19:10:48 -07002193
2194 std::vector<DeviceMapper::TargetInfo> table;
2195 if (dm.GetState(device) == DmDeviceState::INVALID || !dm.GetTableInfo(device, &table)) {
2196 return false;
2197 }
2198 for (const auto& target : table) {
2199 if (strcmp(target.spec.target_type, "verity") == 0 &&
2200 target.data.find("check_at_most_once") != std::string::npos) {
2201 return true;
2202 }
2203 }
2204 return false;
2205}
2206
David Anderson0bfa1c82018-10-30 15:06:46 -07002207std::string fs_mgr_get_super_partition_name(int slot) {
2208 // Devices upgrading to dynamic partitions are allowed to specify a super
David Anderson0b0ee7a2019-04-18 14:14:33 -07002209 // partition name. This includes cuttlefish, which is a non-A/B device.
David Anderson0bfa1c82018-10-30 15:06:46 -07002210 std::string super_partition;
David Andersondac04762022-02-28 21:38:38 -08002211 if (fs_mgr_get_boot_config("force_super_partition", &super_partition)) {
2212 return super_partition;
2213 }
2214 if (fs_mgr_get_boot_config("super_partition", &super_partition)) {
David Anderson0b0ee7a2019-04-18 14:14:33 -07002215 if (fs_mgr_get_slot_suffix().empty()) {
2216 return super_partition;
2217 }
David Anderson0bfa1c82018-10-30 15:06:46 -07002218 std::string suffix;
2219 if (slot == 0) {
2220 suffix = "_a";
2221 } else if (slot == 1) {
2222 suffix = "_b";
2223 } else if (slot == -1) {
2224 suffix = fs_mgr_get_slot_suffix();
2225 }
David Anderson0bfa1c82018-10-30 15:06:46 -07002226 return super_partition + suffix;
2227 }
David Anderson5cbd2e42018-09-27 10:53:04 -07002228 return LP_METADATA_DEFAULT_PARTITION_NAME;
2229}
Yi-Yo Chiang23816e82021-05-19 17:19:58 +08002230
Yi-Yo Chiang3431d522021-05-27 22:29:32 +08002231bool fs_mgr_create_canonical_mount_point(const std::string& mount_point) {
2232 auto saved_errno = errno;
2233 auto ok = true;
2234 auto created_mount_point = !mkdir(mount_point.c_str(), 0755);
2235 std::string real_mount_point;
2236 if (!Realpath(mount_point, &real_mount_point)) {
2237 ok = false;
2238 PERROR << "failed to realpath(" << mount_point << ")";
2239 } else if (mount_point != real_mount_point) {
2240 ok = false;
2241 LERROR << "mount point is not canonical: realpath(" << mount_point << ") -> "
2242 << real_mount_point;
2243 }
2244 if (!ok && created_mount_point) {
2245 rmdir(mount_point.c_str());
2246 }
2247 errno = saved_errno;
2248 return ok;
2249}
2250
Yi-Yo Chiang23816e82021-05-19 17:19:58 +08002251bool fs_mgr_mount_overlayfs_fstab_entry(const FstabEntry& entry) {
2252 auto overlayfs_valid_result = fs_mgr_overlayfs_valid();
2253 if (overlayfs_valid_result == OverlayfsValidResult::kNotSupported) {
2254 LERROR << __FUNCTION__ << "(): kernel does not support overlayfs";
2255 return false;
2256 }
2257
2258#if ALLOW_ADBD_DISABLE_VERITY == 0
2259 // Allowlist the mount point if user build.
2260 static const std::vector<const std::string> kAllowedPaths = {
Ramji Jiyani023d8972022-02-08 02:04:24 +00002261 "/odm", "/odm_dlkm", "/oem", "/product",
2262 "/system_dlkm", "/system_ext", "/vendor", "/vendor_dlkm",
Yi-Yo Chiang23816e82021-05-19 17:19:58 +08002263 };
2264 static const std::vector<const std::string> kAllowedPrefixes = {
2265 "/mnt/product/",
2266 "/mnt/vendor/",
2267 };
2268 if (std::none_of(kAllowedPaths.begin(), kAllowedPaths.end(),
2269 [&entry](const auto& path) -> bool {
2270 return entry.mount_point == path ||
2271 StartsWith(entry.mount_point, path + "/");
2272 }) &&
2273 std::none_of(kAllowedPrefixes.begin(), kAllowedPrefixes.end(),
2274 [&entry](const auto& prefix) -> bool {
2275 return entry.mount_point != prefix &&
2276 StartsWith(entry.mount_point, prefix);
2277 })) {
2278 LERROR << __FUNCTION__
2279 << "(): mount point is forbidden on user build: " << entry.mount_point;
2280 return false;
2281 }
2282#endif // ALLOW_ADBD_DISABLE_VERITY == 0
2283
Yi-Yo Chiang3431d522021-05-27 22:29:32 +08002284 if (!fs_mgr_create_canonical_mount_point(entry.mount_point)) {
Yi-Yo Chiang23816e82021-05-19 17:19:58 +08002285 return false;
2286 }
2287
Yi-Yo Chiange7783a92021-08-03 01:02:31 +08002288 auto lowerdir = entry.lowerdir;
2289 if (entry.fs_mgr_flags.overlayfs_remove_missing_lowerdir) {
2290 bool removed_any = false;
2291 std::vector<std::string> lowerdirs;
2292 for (const auto& dir : android::base::Split(entry.lowerdir, ":")) {
2293 if (access(dir.c_str(), F_OK)) {
2294 PWARNING << __FUNCTION__ << "(): remove missing lowerdir '" << dir << "'";
2295 removed_any = true;
2296 } else {
2297 lowerdirs.push_back(dir);
2298 }
2299 }
2300 if (removed_any) {
2301 lowerdir = android::base::Join(lowerdirs, ":");
2302 }
2303 }
2304
2305 auto options = "lowerdir=" + lowerdir;
Yi-Yo Chiang23816e82021-05-19 17:19:58 +08002306 if (overlayfs_valid_result == OverlayfsValidResult::kOverrideCredsRequired) {
2307 options += ",override_creds=off";
2308 }
2309
2310 // Use "overlay-" + entry.blk_device as the mount() source, so that adb-remout-test don't
2311 // confuse this with adb remount overlay, whose device name is "overlay".
2312 // Overlayfs is a pseudo filesystem, so the source device is a symbolic value and isn't used to
2313 // back the filesystem. However the device name would be shown in /proc/mounts.
2314 auto source = "overlay-" + entry.blk_device;
2315 auto report = "__mount(source=" + source + ",target=" + entry.mount_point + ",type=overlay," +
2316 options + ")=";
2317 auto ret = mount(source.c_str(), entry.mount_point.c_str(), "overlay", MS_RDONLY | MS_NOATIME,
2318 options.c_str());
2319 if (ret) {
2320 PERROR << report << ret;
2321 return false;
2322 }
2323 LINFO << report << ret;
2324 return true;
2325}
David Anderson6cdd9bd2021-10-29 16:13:22 -07002326
2327bool fs_mgr_load_verity_state(int* mode) {
2328 // unless otherwise specified, use EIO mode.
2329 *mode = VERITY_MODE_EIO;
2330
2331 // The bootloader communicates verity mode via the kernel commandline
2332 std::string verity_mode;
2333 if (!fs_mgr_get_boot_config("veritymode", &verity_mode)) {
2334 return false;
2335 }
2336
2337 if (verity_mode == "enforcing") {
2338 *mode = VERITY_MODE_DEFAULT;
2339 } else if (verity_mode == "logging") {
2340 *mode = VERITY_MODE_LOGGING;
2341 }
2342
2343 return true;
2344}