blob: 2298ac763919e6a514f42d669cd9f6c22603fc4f [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
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800173static void check_fs(const std::string& blk_device, const std::string& fs_type,
174 const std::string& target, int* fs_stat) {
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800175 int status;
Ken Sumrall5dc5bfe2012-07-23 19:34:00 -0700176 int ret;
177 long tmpmnt_flags = MS_NOATIME | MS_NOEXEC | MS_NOSUID;
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800178 auto tmpmnt_opts = "errors=remount-ro"s;
179 const char* e2fsck_argv[] = {E2FSCK_BIN, "-y", blk_device.c_str()};
180 const char* e2fsck_forced_argv[] = {E2FSCK_BIN, "-f", "-y", blk_device.c_str()};
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800181
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800182 if (*fs_stat & FS_STAT_INVALID_MAGIC) { // will fail, so do not try
183 return;
184 }
185
Jaegeuk Kim24d2a292020-02-27 11:28:45 -0800186 Timer t;
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800187 /* Check for the types of filesystems we know how to check */
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700188 if (is_extfs(fs_type)) {
Ken Sumrall5dc5bfe2012-07-23 19:34:00 -0700189 /*
190 * First try to mount and unmount the filesystem. We do this because
191 * the kernel is more efficient than e2fsck in running the journal and
192 * processing orphaned inodes, and on at least one device with a
193 * performance issue in the emmc firmware, it can take e2fsck 2.5 minutes
194 * to do what the kernel does in about a second.
195 *
196 * After mounting and unmounting the filesystem, run e2fsck, and if an
197 * error is recorded in the filesystem superblock, e2fsck will do a full
198 * check. Otherwise, it does nothing. If the kernel cannot mount the
199 * filesytsem due to an error, e2fsck is still run to do a full check
200 * fix the filesystem.
201 */
Keun-young Park40db04d2017-04-13 17:31:08 -0700202 if (!(*fs_stat & FS_STAT_FULL_MOUNT_FAILED)) { // already tried if full mount failed
203 errno = 0;
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800204 if (fs_type == "ext4") {
Keun-young Park40db04d2017-04-13 17:31:08 -0700205 // This option is only valid with ext4
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800206 tmpmnt_opts += ",nomblk_io_submit";
Nick Kralevich7294eb62015-02-05 16:02:42 -0800207 }
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800208 ret = mount(blk_device.c_str(), target.c_str(), fs_type.c_str(), tmpmnt_flags,
209 tmpmnt_opts.c_str());
Keun-young Park40db04d2017-04-13 17:31:08 -0700210 PINFO << __FUNCTION__ << "(): mount(" << blk_device << "," << target << "," << fs_type
211 << ")=" << ret;
212 if (!ret) {
213 bool umounted = false;
214 int retry_count = 5;
215 while (retry_count-- > 0) {
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800216 umounted = umount(target.c_str()) == 0;
Keun-young Park40db04d2017-04-13 17:31:08 -0700217 if (umounted) {
218 LINFO << __FUNCTION__ << "(): unmount(" << target << ") succeeded";
219 break;
220 }
221 PERROR << __FUNCTION__ << "(): umount(" << target << ") failed";
222 if (retry_count) sleep(1);
223 }
224 if (!umounted) {
225 // boot may fail but continue and leave it to later stage for now.
226 PERROR << __FUNCTION__ << "(): umount(" << target << ") timed out";
227 *fs_stat |= FS_STAT_RO_UNMOUNT_FAILED;
228 }
229 } else {
230 *fs_stat |= FS_STAT_RO_MOUNT_FAILED;
231 }
Ken Sumrall5dc5bfe2012-07-23 19:34:00 -0700232 }
233
David 'Digit' Turner28483d72014-02-17 11:14:44 +0100234 /*
235 * Some system images do not have e2fsck for licensing reasons
236 * (e.g. recent SDK system images). Detect these and skip the check.
237 */
238 if (access(E2FSCK_BIN, X_OK)) {
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800239 LINFO << "Not running " << E2FSCK_BIN << " on " << realpath(blk_device)
bowgotsai47878de2017-01-23 14:04:34 +0800240 << " (executable not in system image)";
David 'Digit' Turner28483d72014-02-17 11:14:44 +0100241 } else {
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800242 LINFO << "Running " << E2FSCK_BIN << " on " << realpath(blk_device);
Keun-young Park40db04d2017-04-13 17:31:08 -0700243 if (should_force_check(*fs_stat)) {
Tom Cherry3a803eb2019-09-25 16:23:50 -0700244 ret = logwrap_fork_execvp(ARRAY_SIZE(e2fsck_forced_argv), e2fsck_forced_argv,
Wei Wang02e89ec2020-02-14 14:22:16 -0800245 &status, false, LOG_KLOG | LOG_FILE, false,
246 FSCK_LOG_FILE);
Keun-young Park40db04d2017-04-13 17:31:08 -0700247 } else {
Tom Cherry3a803eb2019-09-25 16:23:50 -0700248 ret = logwrap_fork_execvp(ARRAY_SIZE(e2fsck_argv), e2fsck_argv, &status, false,
Wei Wang02e89ec2020-02-14 14:22:16 -0800249 LOG_KLOG | LOG_FILE, false, FSCK_LOG_FILE);
Keun-young Park40db04d2017-04-13 17:31:08 -0700250 }
Ken Sumrallbf021b42013-03-19 19:38:44 -0700251
David 'Digit' Turner28483d72014-02-17 11:14:44 +0100252 if (ret < 0) {
253 /* No need to check for error in fork, we can't really handle it now */
bowgotsai47878de2017-01-23 14:04:34 +0800254 LERROR << "Failed trying to run " << E2FSCK_BIN;
Keun-young Park3fbf94e2017-03-02 14:33:04 -0800255 *fs_stat |= FS_STAT_E2FSCK_FAILED;
256 } else if (status != 0) {
257 LINFO << "e2fsck returned status 0x" << std::hex << status;
258 *fs_stat |= FS_STAT_E2FSCK_FS_FIXED;
David 'Digit' Turner28483d72014-02-17 11:14:44 +0100259 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800260 }
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800261 } else if (is_f2fs(fs_type)) {
Jaegeuk Kimc461e162020-01-03 14:09:41 -0800262 const char* f2fs_fsck_argv[] = {F2FS_FSCK_BIN, "-a", "-c", "10000", "--debug-cache",
263 blk_device.c_str()};
264 const char* f2fs_fsck_forced_argv[] = {
265 F2FS_FSCK_BIN, "-f", "-c", "10000", "--debug-cache", blk_device.c_str()};
JP Abgrall12351582014-06-17 17:01:14 -0700266
Sahitya Tummala5928e4f2019-05-23 16:23:58 +0530267 if (should_force_check(*fs_stat)) {
jiahaobfcee282021-04-16 17:07:50 +0800268 LINFO << "Running " << F2FS_FSCK_BIN << " -f -c 10000 --debug-cache "
Jaegeuk Kimc461e162020-01-03 14:09:41 -0800269 << realpath(blk_device);
Tom Cherry3a803eb2019-09-25 16:23:50 -0700270 ret = logwrap_fork_execvp(ARRAY_SIZE(f2fs_fsck_forced_argv), f2fs_fsck_forced_argv,
Wei Wang02e89ec2020-02-14 14:22:16 -0800271 &status, false, LOG_KLOG | LOG_FILE, false, FSCK_LOG_FILE);
Sahitya Tummala5928e4f2019-05-23 16:23:58 +0530272 } else {
jiahaobfcee282021-04-16 17:07:50 +0800273 LINFO << "Running " << F2FS_FSCK_BIN << " -a -c 10000 --debug-cache "
Jaegeuk Kimc461e162020-01-03 14:09:41 -0800274 << realpath(blk_device);
Tom Cherry3a803eb2019-09-25 16:23:50 -0700275 ret = logwrap_fork_execvp(ARRAY_SIZE(f2fs_fsck_argv), f2fs_fsck_argv, &status, false,
Wei Wang02e89ec2020-02-14 14:22:16 -0800276 LOG_KLOG | LOG_FILE, false, FSCK_LOG_FILE);
Sahitya Tummala5928e4f2019-05-23 16:23:58 +0530277 }
JP Abgrall12351582014-06-17 17:01:14 -0700278 if (ret < 0) {
279 /* No need to check for error in fork, we can't really handle it now */
bowgotsai47878de2017-01-23 14:04:34 +0800280 LERROR << "Failed trying to run " << F2FS_FSCK_BIN;
JP Abgrall12351582014-06-17 17:01:14 -0700281 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800282 }
Jaegeuk Kim24d2a292020-02-27 11:28:45 -0800283 android::base::SetProperty("ro.boottime.init.fsck." + Basename(target),
284 std::to_string(t.duration().count()));
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800285 return;
286}
287
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700288static ext4_fsblk_t ext4_blocks_count(const struct ext4_super_block* es) {
liminghao9a0fd1d2016-07-22 11:48:14 +0800289 return ((ext4_fsblk_t)le32_to_cpu(es->s_blocks_count_hi) << 32) |
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700290 le32_to_cpu(es->s_blocks_count_lo);
liminghao9a0fd1d2016-07-22 11:48:14 +0800291}
292
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700293static ext4_fsblk_t ext4_r_blocks_count(const struct ext4_super_block* es) {
liminghao9a0fd1d2016-07-22 11:48:14 +0800294 return ((ext4_fsblk_t)le32_to_cpu(es->s_r_blocks_count_hi) << 32) |
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700295 le32_to_cpu(es->s_r_blocks_count_lo);
liminghao9a0fd1d2016-07-22 11:48:14 +0800296}
297
katao4e8d73f2017-07-05 16:00:54 +0800298static bool is_ext4_superblock_valid(const struct ext4_super_block* es) {
299 if (es->s_magic != EXT4_SUPER_MAGIC) return false;
300 if (es->s_rev_level != EXT4_DYNAMIC_REV && es->s_rev_level != EXT4_GOOD_OLD_REV) return false;
301 if (EXT4_INODES_PER_GROUP(es) == 0) return false;
302 return true;
303}
304
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700305// Read the primary superblock from an ext4 filesystem. On failure return
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800306// false. If it's not an ext4 filesystem, also set FS_STAT_INVALID_MAGIC.
Eric Biggersdc3e8972020-08-04 11:11:13 -0700307static bool read_ext4_superblock(const std::string& blk_device, struct ext4_super_block* sb,
308 int* fs_stat) {
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800309 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
Jeff Sharkey6d896102016-12-14 12:00:51 -0700310
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700311 if (fd < 0) {
312 PERROR << "Failed to open '" << blk_device << "'";
313 return false;
Jeff Sharkey6d896102016-12-14 12:00:51 -0700314 }
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700315
Mark Salyzyn60a76f32019-03-14 15:34:35 -0700316 if (TEMP_FAILURE_RETRY(pread(fd, sb, sizeof(*sb), 1024)) != sizeof(*sb)) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700317 PERROR << "Can't read '" << blk_device << "' superblock";
318 return false;
319 }
320
katao4e8d73f2017-07-05 16:00:54 +0800321 if (!is_ext4_superblock_valid(sb)) {
322 LINFO << "Invalid ext4 superblock on '" << blk_device << "'";
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700323 // not a valid fs, tune2fs, fsck, and mount will all fail.
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800324 *fs_stat |= FS_STAT_INVALID_MAGIC;
Eric Biggersdc3e8972020-08-04 11:11:13 -0700325 return false;
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700326 }
327 *fs_stat |= FS_STAT_IS_EXT4;
328 LINFO << "superblock s_max_mnt_count:" << sb->s_max_mnt_count << "," << blk_device;
329 if (sb->s_max_mnt_count == 0xffff) { // -1 (int16) in ext2, but uint16 in ext4
330 *fs_stat |= FS_STAT_NEW_IMAGE_VERSION;
331 }
332 return true;
Jeff Sharkey6d896102016-12-14 12:00:51 -0700333}
334
Mark Salyzyn60a76f32019-03-14 15:34:35 -0700335// exported silent version of the above that just answer the question is_ext4
336bool fs_mgr_is_ext4(const std::string& blk_device) {
337 android::base::ErrnoRestorer restore;
338 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
339 if (fd < 0) return false;
340 ext4_super_block sb;
341 if (TEMP_FAILURE_RETRY(pread(fd, &sb, sizeof(sb), 1024)) != sizeof(sb)) return false;
342 if (!is_ext4_superblock_valid(&sb)) return false;
343 return true;
344}
345
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700346// Some system images do not have tune2fs for licensing reasons.
347// Detect these and skip running it.
348static bool tune2fs_available(void) {
349 return access(TUNE2FS_BIN, X_OK) == 0;
350}
351
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800352static bool run_command(const char* argv[], int argc) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700353 int ret;
354
Wei Wang02e89ec2020-02-14 14:22:16 -0800355 ret = logwrap_fork_execvp(argc, argv, nullptr, false, LOG_KLOG, false, nullptr);
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700356 return ret == 0;
357}
358
359// Enable/disable quota support on the filesystem if needed.
Tom Cherry23319eb2018-11-30 16:16:05 -0800360static void tune_quota(const std::string& blk_device, const FstabEntry& entry,
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700361 const struct ext4_super_block* sb, int* fs_stat) {
362 bool has_quota = (sb->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_RO_COMPAT_QUOTA)) != 0;
Tom Cherry23319eb2018-11-30 16:16:05 -0800363 bool want_quota = entry.fs_mgr_flags.quota;
Martijn Coenenea751d92020-04-15 11:45:05 +0200364 bool want_projid = android::base::GetBoolProperty("external_storage.projid.enabled", false);
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700365
366 if (has_quota == want_quota) {
367 return;
368 }
369
370 if (!tune2fs_available()) {
371 LERROR << "Unable to " << (want_quota ? "enable" : "disable") << " quotas on " << blk_device
372 << " because " TUNE2FS_BIN " is missing";
373 return;
374 }
375
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800376 const char* argv[] = {TUNE2FS_BIN, nullptr, nullptr, blk_device.c_str()};
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700377
378 if (want_quota) {
379 LINFO << "Enabling quotas on " << blk_device;
380 argv[1] = "-Oquota";
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800381 // Once usr/grp unneeded, make just prjquota to save overhead
382 if (want_projid)
383 argv[2] = "-Qusrquota,grpquota,prjquota";
384 else
385 argv[2] = "-Qusrquota,grpquota";
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700386 *fs_stat |= FS_STAT_QUOTA_ENABLED;
387 } else {
388 LINFO << "Disabling quotas on " << blk_device;
389 argv[1] = "-O^quota";
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800390 argv[2] = "-Q^usrquota,^grpquota,^prjquota";
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700391 }
392
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800393 if (!run_command(argv, ARRAY_SIZE(argv))) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700394 LERROR << "Failed to run " TUNE2FS_BIN " to " << (want_quota ? "enable" : "disable")
395 << " quotas on " << blk_device;
396 *fs_stat |= FS_STAT_TOGGLE_QUOTAS_FAILED;
397 }
398}
399
400// Set the number of reserved filesystem blocks if needed.
Tom Cherry23319eb2018-11-30 16:16:05 -0800401static void tune_reserved_size(const std::string& blk_device, const FstabEntry& entry,
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700402 const struct ext4_super_block* sb, int* fs_stat) {
Martijn Coenen20c4cfa2019-05-10 10:39:54 +0200403 if (entry.reserved_size == 0) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700404 return;
405 }
406
407 // The size to reserve is given in the fstab, but we won't reserve more
408 // than 2% of the filesystem.
409 const uint64_t max_reserved_blocks = ext4_blocks_count(sb) * 0.02;
Tom Cherry23319eb2018-11-30 16:16:05 -0800410 uint64_t reserved_blocks = entry.reserved_size / EXT4_BLOCK_SIZE(sb);
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700411
412 if (reserved_blocks > max_reserved_blocks) {
413 LWARNING << "Reserved blocks " << reserved_blocks << " is too large; "
414 << "capping to " << max_reserved_blocks;
415 reserved_blocks = max_reserved_blocks;
416 }
417
Jeff Sharkey47dc2362018-01-07 19:17:39 -0700418 if ((ext4_r_blocks_count(sb) == reserved_blocks) && (sb->s_def_resgid == AID_RESERVED_DISK)) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700419 return;
420 }
421
422 if (!tune2fs_available()) {
423 LERROR << "Unable to set the number of reserved blocks on " << blk_device
424 << " because " TUNE2FS_BIN " is missing";
425 return;
426 }
427
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700428 LINFO << "Setting reserved block count on " << blk_device << " to " << reserved_blocks;
Jeff Sharkey47dc2362018-01-07 19:17:39 -0700429
430 auto reserved_blocks_str = std::to_string(reserved_blocks);
431 auto reserved_gid_str = std::to_string(AID_RESERVED_DISK);
432 const char* argv[] = {
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800433 TUNE2FS_BIN, "-r", reserved_blocks_str.c_str(), "-g", reserved_gid_str.c_str(),
434 blk_device.c_str()};
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800435 if (!run_command(argv, ARRAY_SIZE(argv))) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700436 LERROR << "Failed to run " TUNE2FS_BIN " to set the number of reserved blocks on "
437 << blk_device;
438 *fs_stat |= FS_STAT_SET_RESERVED_BLOCKS_FAILED;
439 }
440}
441
Eric Biggerse9811f32017-07-05 12:21:15 -0700442// Enable file-based encryption if needed.
Tom Cherry23319eb2018-11-30 16:16:05 -0800443static void tune_encrypt(const std::string& blk_device, const FstabEntry& entry,
Eric Biggerse9811f32017-07-05 12:21:15 -0700444 const struct ext4_super_block* sb, int* fs_stat) {
Paul Crowley7160fc12019-10-25 17:12:45 -0700445 if (!entry.fs_mgr_flags.file_encryption) {
446 return; // Nothing needs done.
447 }
448 std::vector<std::string> features_needed;
449 if ((sb->s_feature_incompat & cpu_to_le32(EXT4_FEATURE_INCOMPAT_ENCRYPT)) == 0) {
450 features_needed.emplace_back("encrypt");
451 }
452 android::fscrypt::EncryptionOptions options;
453 if (!android::fscrypt::ParseOptions(entry.encryption_options, &options)) {
454 LERROR << "Unable to parse encryption options on " << blk_device << ": "
455 << entry.encryption_options;
Eric Biggerse9811f32017-07-05 12:21:15 -0700456 return;
457 }
Paul Crowleyc2f37682020-05-20 16:36:15 -0700458 if ((options.flags &
459 (FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 | FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32)) != 0) {
Paul Crowley7160fc12019-10-25 17:12:45 -0700460 // We can only use this policy on ext4 if the "stable_inodes" feature
461 // is set on the filesystem, otherwise shrinking will break encrypted files.
462 if ((sb->s_feature_compat & cpu_to_le32(EXT4_FEATURE_COMPAT_STABLE_INODES)) == 0) {
463 features_needed.emplace_back("stable_inodes");
464 }
465 }
466 if (features_needed.size() == 0) {
467 return;
468 }
Eric Biggerse9811f32017-07-05 12:21:15 -0700469 if (!tune2fs_available()) {
470 LERROR << "Unable to enable ext4 encryption on " << blk_device
471 << " because " TUNE2FS_BIN " is missing";
472 return;
473 }
474
Paul Crowley7160fc12019-10-25 17:12:45 -0700475 auto flags = android::base::Join(features_needed, ',');
476 auto flag_arg = "-O"s + flags;
477 const char* argv[] = {TUNE2FS_BIN, flag_arg.c_str(), blk_device.c_str()};
Eric Biggerse9811f32017-07-05 12:21:15 -0700478
Paul Crowley7160fc12019-10-25 17:12:45 -0700479 LINFO << "Enabling ext4 flags " << flags << " on " << blk_device;
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800480 if (!run_command(argv, ARRAY_SIZE(argv))) {
Eric Biggerse9811f32017-07-05 12:21:15 -0700481 LERROR << "Failed to run " TUNE2FS_BIN " to enable "
Paul Crowley7160fc12019-10-25 17:12:45 -0700482 << "ext4 flags " << flags << " on " << blk_device;
Eric Biggerse9811f32017-07-05 12:21:15 -0700483 *fs_stat |= FS_STAT_ENABLE_ENCRYPTION_FAILED;
484 }
485}
486
Leo Liou0b721d32019-01-15 20:43:37 +0800487// Enable fs-verity if needed.
488static void tune_verity(const std::string& blk_device, const FstabEntry& entry,
489 const struct ext4_super_block* sb, int* fs_stat) {
490 bool has_verity = (sb->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_RO_COMPAT_VERITY)) != 0;
491 bool want_verity = entry.fs_mgr_flags.fs_verity;
492
493 if (has_verity || !want_verity) {
494 return;
495 }
496
497 std::string verity_support;
498 if (!android::base::ReadFileToString(SYSFS_EXT4_VERITY, &verity_support)) {
499 LERROR << "Failed to open " << SYSFS_EXT4_VERITY;
500 return;
501 }
502
503 if (!(android::base::Trim(verity_support) == "supported")) {
504 LERROR << "Current ext4 verity not supported by kernel";
505 return;
506 }
507
508 if (!tune2fs_available()) {
509 LERROR << "Unable to enable ext4 verity on " << blk_device
510 << " because " TUNE2FS_BIN " is missing";
511 return;
512 }
513
514 LINFO << "Enabling ext4 verity on " << blk_device;
515
516 const char* argv[] = {TUNE2FS_BIN, "-O", "verity", blk_device.c_str()};
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800517 if (!run_command(argv, ARRAY_SIZE(argv))) {
Leo Liou0b721d32019-01-15 20:43:37 +0800518 LERROR << "Failed to run " TUNE2FS_BIN " to enable "
519 << "ext4 verity on " << blk_device;
520 *fs_stat |= FS_STAT_ENABLE_VERITY_FAILED;
521 }
522}
523
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800524// Enable casefold if needed.
Jaegeuk Kim5ba5b902020-08-14 12:34:36 -0700525static void tune_casefold(const std::string& blk_device, const FstabEntry& entry,
526 const struct ext4_super_block* sb, int* fs_stat) {
Eric Biggers91bcfd82020-02-25 11:11:35 -0800527 bool has_casefold = (sb->s_feature_incompat & cpu_to_le32(EXT4_FEATURE_INCOMPAT_CASEFOLD)) != 0;
Martijn Coenenea751d92020-04-15 11:45:05 +0200528 bool wants_casefold =
529 android::base::GetBoolProperty("external_storage.casefold.enabled", false);
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800530
Yongqin Liuc007c432020-10-23 13:29:19 +0800531 if (entry.mount_point != "/data" || !wants_casefold || has_casefold) return;
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800532
533 std::string casefold_support;
534 if (!android::base::ReadFileToString(SYSFS_EXT4_CASEFOLD, &casefold_support)) {
535 LERROR << "Failed to open " << SYSFS_EXT4_CASEFOLD;
536 return;
537 }
538
539 if (!(android::base::Trim(casefold_support) == "supported")) {
540 LERROR << "Current ext4 casefolding not supported by kernel";
541 return;
542 }
543
544 if (!tune2fs_available()) {
545 LERROR << "Unable to enable ext4 casefold on " << blk_device
546 << " because " TUNE2FS_BIN " is missing";
547 return;
548 }
549
550 LINFO << "Enabling ext4 casefold on " << blk_device;
551
552 const char* argv[] = {TUNE2FS_BIN, "-O", "casefold", "-E", "encoding=utf8", blk_device.c_str()};
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800553 if (!run_command(argv, ARRAY_SIZE(argv))) {
Daniel Rosenberg8775ce02019-11-19 20:30:06 -0800554 LERROR << "Failed to run " TUNE2FS_BIN " to enable "
555 << "ext4 casefold on " << blk_device;
556 *fs_stat |= FS_STAT_ENABLE_CASEFOLD_FAILED;
557 }
558}
559
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800560static bool resize2fs_available(void) {
561 return access(RESIZE2FS_BIN, X_OK) == 0;
562}
563
564// Enable metadata_csum
565static void tune_metadata_csum(const std::string& blk_device, const FstabEntry& entry,
566 const struct ext4_super_block* sb, int* fs_stat) {
567 bool has_meta_csum =
568 (sb->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) != 0;
569 bool want_meta_csum = entry.fs_mgr_flags.ext_meta_csum;
570
571 if (has_meta_csum || !want_meta_csum) return;
572
573 if (!tune2fs_available()) {
574 LERROR << "Unable to enable metadata_csum on " << blk_device
575 << " because " TUNE2FS_BIN " is missing";
576 return;
577 }
578 if (!resize2fs_available()) {
579 LERROR << "Unable to enable metadata_csum on " << blk_device
580 << " because " RESIZE2FS_BIN " is missing";
581 return;
582 }
583
584 LINFO << "Enabling ext4 metadata_csum on " << blk_device;
585
Tom Cherry2d451662020-07-27 11:20:29 -0700586 // Must give `-T now` to prevent last_fsck_time from growing too large,
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800587 // otherwise, tune2fs won't enable metadata_csum.
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800588 const char* tune2fs_args[] = {TUNE2FS_BIN, "-O", "metadata_csum,64bit,extent",
Jaegeuk Kim52838162020-02-24 19:58:22 -0800589 "-T", "now", blk_device.c_str()};
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800590 const char* resize2fs_args[] = {RESIZE2FS_BIN, "-b", blk_device.c_str()};
591
592 if (!run_command(tune2fs_args, ARRAY_SIZE(tune2fs_args))) {
593 LERROR << "Failed to run " TUNE2FS_BIN " to enable "
594 << "ext4 metadata_csum on " << blk_device;
595 *fs_stat |= FS_STAT_ENABLE_METADATA_CSUM_FAILED;
596 } else if (!run_command(resize2fs_args, ARRAY_SIZE(resize2fs_args))) {
597 LERROR << "Failed to run " RESIZE2FS_BIN " to enable "
598 << "ext4 metadata_csum on " << blk_device;
599 *fs_stat |= FS_STAT_ENABLE_METADATA_CSUM_FAILED;
600 }
601}
602
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800603// Read the primary superblock from an f2fs filesystem. On failure return
604// false. If it's not an f2fs filesystem, also set FS_STAT_INVALID_MAGIC.
605#define F2FS_BLKSIZE 4096
606#define F2FS_SUPER_OFFSET 1024
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800607static bool read_f2fs_superblock(const std::string& blk_device, int* fs_stat) {
608 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800609 __le32 sb1, sb2;
610
611 if (fd < 0) {
612 PERROR << "Failed to open '" << blk_device << "'";
613 return false;
614 }
615
Mark Salyzyn60a76f32019-03-14 15:34:35 -0700616 if (TEMP_FAILURE_RETRY(pread(fd, &sb1, sizeof(sb1), F2FS_SUPER_OFFSET)) != sizeof(sb1)) {
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800617 PERROR << "Can't read '" << blk_device << "' superblock1";
618 return false;
619 }
Mark Salyzyn60a76f32019-03-14 15:34:35 -0700620 if (TEMP_FAILURE_RETRY(pread(fd, &sb2, sizeof(sb2), F2FS_BLKSIZE + F2FS_SUPER_OFFSET)) !=
621 sizeof(sb2)) {
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800622 PERROR << "Can't read '" << blk_device << "' superblock2";
623 return false;
624 }
625
626 if (sb1 != cpu_to_le32(F2FS_SUPER_MAGIC) && sb2 != cpu_to_le32(F2FS_SUPER_MAGIC)) {
627 LINFO << "Invalid f2fs superblock on '" << blk_device << "'";
628 *fs_stat |= FS_STAT_INVALID_MAGIC;
629 return false;
630 }
631 return true;
632}
633
Mark Salyzyn60a76f32019-03-14 15:34:35 -0700634// exported silent version of the above that just answer the question is_f2fs
635bool fs_mgr_is_f2fs(const std::string& blk_device) {
636 android::base::ErrnoRestorer restore;
637 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
638 if (fd < 0) return false;
639 __le32 sb;
640 if (TEMP_FAILURE_RETRY(pread(fd, &sb, sizeof(sb), F2FS_SUPER_OFFSET)) != sizeof(sb)) {
641 return false;
642 }
643 if (sb == cpu_to_le32(F2FS_SUPER_MAGIC)) return true;
644 if (TEMP_FAILURE_RETRY(pread(fd, &sb, sizeof(sb), F2FS_BLKSIZE + F2FS_SUPER_OFFSET)) !=
645 sizeof(sb)) {
646 return false;
647 }
648 return sb == cpu_to_le32(F2FS_SUPER_MAGIC);
649}
650
Jaegeuk Kim05ca9152021-04-02 21:28:51 -0700651static void SetReadAheadSize(const std::string& entry_block_device, off64_t size_kb) {
652 std::string block_device;
653 if (!Realpath(entry_block_device, &block_device)) {
654 PERROR << "Failed to realpath " << entry_block_device;
655 return;
656 }
657
658 static constexpr std::string_view kDevBlockPrefix("/dev/block/");
659 if (!android::base::StartsWith(block_device, kDevBlockPrefix)) {
660 LWARNING << block_device << " is not a block device";
661 return;
662 }
663
664 DeviceMapper& dm = DeviceMapper::Instance();
665 while (true) {
666 std::string block_name = block_device;
667 if (android::base::StartsWith(block_device, kDevBlockPrefix)) {
668 block_name = block_device.substr(kDevBlockPrefix.length());
669 }
670 std::string sys_partition =
671 android::base::StringPrintf("/sys/class/block/%s/partition", block_name.c_str());
672 struct stat info;
673 if (lstat(sys_partition.c_str(), &info) == 0) {
674 // it has a partition like "sda12".
675 block_name += "/..";
676 }
677 std::string sys_ra = android::base::StringPrintf("/sys/class/block/%s/queue/read_ahead_kb",
678 block_name.c_str());
679 std::string size = android::base::StringPrintf("%llu", (long long)size_kb);
680 android::base::WriteStringToFile(size, sys_ra.c_str());
681 LINFO << "Set readahead_kb: " << size << " on " << sys_ra;
682
683 auto parent = dm.GetParentBlockDeviceByPath(block_device);
684 if (!parent) {
685 return;
686 }
687 block_device = *parent;
688 }
689}
690
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700691//
692// Prepare the filesystem on the given block device to be mounted.
693//
694// If the "check" option was given in the fstab record, or it seems that the
695// filesystem was uncleanly shut down, we'll run fsck on the filesystem.
696//
697// If needed, we'll also enable (or disable) filesystem features as specified by
698// the fstab record.
699//
Tom Cherrya7f1a9f2020-11-19 11:39:39 -0800700static int prepare_fs_for_mount(const std::string& blk_device, const FstabEntry& entry,
701 const std::string& alt_mount_point = "") {
702 auto& mount_point = alt_mount_point.empty() ? entry.mount_point : alt_mount_point;
703 // We need this because sometimes we have legacy symlinks that are
704 // lingering around and need cleaning up.
705 struct stat info;
706 if (lstat(mount_point.c_str(), &info) == 0 && (info.st_mode & S_IFMT) == S_IFLNK) {
707 unlink(mount_point.c_str());
708 }
709 mkdir(mount_point.c_str(), 0755);
710
Jaegeuk Kim05ca9152021-04-02 21:28:51 -0700711 // Don't need to return error, since it's a salt
712 if (entry.readahead_size_kb != -1) {
713 SetReadAheadSize(blk_device, entry.readahead_size_kb);
714 }
715
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700716 int fs_stat = 0;
717
Tom Cherry23319eb2018-11-30 16:16:05 -0800718 if (is_extfs(entry.fs_type)) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700719 struct ext4_super_block sb;
720
Eric Biggersdc3e8972020-08-04 11:11:13 -0700721 if (read_ext4_superblock(blk_device, &sb, &fs_stat)) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700722 if ((sb.s_feature_incompat & EXT4_FEATURE_INCOMPAT_RECOVER) != 0 ||
723 (sb.s_state & EXT4_VALID_FS) == 0) {
724 LINFO << "Filesystem on " << blk_device << " was not cleanly shutdown; "
725 << "state flags: 0x" << std::hex << sb.s_state << ", "
726 << "incompat feature flags: 0x" << std::hex << sb.s_feature_incompat;
727 fs_stat |= FS_STAT_UNCLEAN_SHUTDOWN;
728 }
729
730 // Note: quotas should be enabled before running fsck.
Tom Cherry23319eb2018-11-30 16:16:05 -0800731 tune_quota(blk_device, entry, &sb, &fs_stat);
liminghao9a0fd1d2016-07-22 11:48:14 +0800732 } else {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700733 return fs_stat;
liminghao9a0fd1d2016-07-22 11:48:14 +0800734 }
Tom Cherry23319eb2018-11-30 16:16:05 -0800735 } else if (is_f2fs(entry.fs_type)) {
Jaegeuk Kim5d14b982018-11-21 13:24:10 -0800736 if (!read_f2fs_superblock(blk_device, &fs_stat)) {
737 return fs_stat;
738 }
liminghao9a0fd1d2016-07-22 11:48:14 +0800739 }
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700740
Tom Cherry23319eb2018-11-30 16:16:05 -0800741 if (entry.fs_mgr_flags.check ||
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700742 (fs_stat & (FS_STAT_UNCLEAN_SHUTDOWN | FS_STAT_QUOTA_ENABLED))) {
Tom Cherrya7f1a9f2020-11-19 11:39:39 -0800743 check_fs(blk_device, entry.fs_type, mount_point, &fs_stat);
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700744 }
745
Tom Cherry23319eb2018-11-30 16:16:05 -0800746 if (is_extfs(entry.fs_type) &&
Tom Cherry685c2c72019-02-04 13:33:32 -0800747 (entry.reserved_size != 0 || entry.fs_mgr_flags.file_encryption ||
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800748 entry.fs_mgr_flags.fs_verity || entry.fs_mgr_flags.ext_meta_csum)) {
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700749 struct ext4_super_block sb;
750
Eric Biggersdc3e8972020-08-04 11:11:13 -0700751 if (read_ext4_superblock(blk_device, &sb, &fs_stat)) {
Tom Cherry23319eb2018-11-30 16:16:05 -0800752 tune_reserved_size(blk_device, entry, &sb, &fs_stat);
753 tune_encrypt(blk_device, entry, &sb, &fs_stat);
Leo Liou0b721d32019-01-15 20:43:37 +0800754 tune_verity(blk_device, entry, &sb, &fs_stat);
Jaegeuk Kim5ba5b902020-08-14 12:34:36 -0700755 tune_casefold(blk_device, entry, &sb, &fs_stat);
Jaegeuk Kim78f040c2020-02-11 15:22:46 -0800756 tune_metadata_csum(blk_device, entry, &sb, &fs_stat);
Eric Biggers8d3bcd42017-07-05 12:21:15 -0700757 }
758 }
759
760 return fs_stat;
liminghao9a0fd1d2016-07-22 11:48:14 +0800761}
762
Tom Cherry0d2621f2018-12-04 13:15:09 -0800763// Mark the given block device as read-only, using the BLKROSET ioctl.
Yifan Hongccdba572019-01-08 13:33:52 -0800764bool fs_mgr_set_blk_ro(const std::string& blockdev, bool readonly) {
Tom Cherry0d2621f2018-12-04 13:15:09 -0800765 unique_fd fd(TEMP_FAILURE_RETRY(open(blockdev.c_str(), O_RDONLY | O_CLOEXEC)));
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700766 if (fd < 0) {
Tom Cherry0d2621f2018-12-04 13:15:09 -0800767 return false;
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700768 }
769
Yifan Hongccdba572019-01-08 13:33:52 -0800770 int ON = readonly;
Tom Cherry0d2621f2018-12-04 13:15:09 -0800771 return ioctl(fd, BLKROSET, &ON) == 0;
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700772}
773
Bowgo Tsaid1fe3bd2017-07-05 15:37:15 +0800774// Orange state means the device is unlocked, see the following link for details.
775// https://source.android.com/security/verifiedboot/verified-boot#device_state
776bool fs_mgr_is_device_unlocked() {
777 std::string verified_boot_state;
778 if (fs_mgr_get_boot_config("verifiedbootstate", &verified_boot_state)) {
779 return verified_boot_state == "orange";
780 }
781 return false;
782}
783
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800784// __mount(): wrapper around the mount() system call which also
785// sets the underlying block device to read-only if the mount is read-only.
786// See "man 2 mount" for return values.
Tom Cherry23319eb2018-11-30 16:16:05 -0800787static int __mount(const std::string& source, const std::string& target, const FstabEntry& entry) {
Mark Salyzyn69a5bd42017-06-28 13:36:52 -0700788 errno = 0;
Tom Cherry23319eb2018-11-30 16:16:05 -0800789 unsigned long mountflags = entry.flags;
Daniel Rosenberg5620c6c2019-01-16 16:28:21 -0800790 int ret = 0;
791 int save_errno = 0;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800792 int gc_allowance = 0;
793 std::string opts;
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700794 std::string checkpoint_opts;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800795 bool try_f2fs_gc_allowance = is_f2fs(entry.fs_type) && entry.fs_checkpoint_opts.length() > 0;
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700796 bool try_f2fs_fallback = false;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800797 Timer t;
798
Daniel Rosenberg5620c6c2019-01-16 16:28:21 -0800799 do {
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700800 if (save_errno == EINVAL && (try_f2fs_gc_allowance || try_f2fs_fallback)) {
801 PINFO << "Kernel does not support " << checkpoint_opts << ", trying without.";
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800802 try_f2fs_gc_allowance = false;
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700803 // Attempt without gc allowance before dropping.
804 try_f2fs_fallback = !try_f2fs_fallback;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800805 }
806 if (try_f2fs_gc_allowance) {
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700807 checkpoint_opts = entry.fs_checkpoint_opts + ":" + std::to_string(gc_allowance) + "%";
808 } else if (try_f2fs_fallback) {
809 checkpoint_opts = entry.fs_checkpoint_opts;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800810 } else {
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700811 checkpoint_opts = "";
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800812 }
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700813 opts = entry.fs_options + checkpoint_opts;
Daniel Rosenberg5620c6c2019-01-16 16:28:21 -0800814 if (save_errno == EAGAIN) {
815 PINFO << "Retrying mount (source=" << source << ",target=" << target
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800816 << ",type=" << entry.fs_type << ", gc_allowance=" << gc_allowance << "%)=" << ret
817 << "(" << save_errno << ")";
Daniel Rosenberg5620c6c2019-01-16 16:28:21 -0800818 }
819 ret = mount(source.c_str(), target.c_str(), entry.fs_type.c_str(), mountflags,
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800820 opts.c_str());
Daniel Rosenberg5620c6c2019-01-16 16:28:21 -0800821 save_errno = errno;
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800822 if (try_f2fs_gc_allowance) gc_allowance += 10;
823 } while ((ret && save_errno == EAGAIN && gc_allowance <= 100) ||
Jerry Wong1f3e92c2021-07-09 09:53:21 -0700824 (ret && save_errno == EINVAL && (try_f2fs_gc_allowance || try_f2fs_fallback)));
Mark Salyzyn8243f662018-09-26 14:27:04 -0700825 const char* target_missing = "";
826 const char* source_missing = "";
827 if (save_errno == ENOENT) {
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800828 if (access(target.c_str(), F_OK)) {
Mark Salyzyn8243f662018-09-26 14:27:04 -0700829 target_missing = "(missing)";
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800830 } else if (access(source.c_str(), F_OK)) {
Mark Salyzyn8243f662018-09-26 14:27:04 -0700831 source_missing = "(missing)";
832 }
833 errno = save_errno;
834 }
835 PINFO << __FUNCTION__ << "(source=" << source << source_missing << ",target=" << target
Tom Cherry23319eb2018-11-30 16:16:05 -0800836 << target_missing << ",type=" << entry.fs_type << ")=" << ret;
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700837 if ((ret == 0) && (mountflags & MS_RDONLY) != 0) {
Sami Tolvanen214f33b2014-12-18 16:15:30 +0000838 fs_mgr_set_blk_ro(source);
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700839 }
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -0800840 android::base::SetProperty("ro.boottime.init.mount." + Basename(target),
841 std::to_string(t.duration().count()));
JP Abgrall5c01dac2014-06-18 14:54:37 -0700842 errno = save_errno;
Nick Kraleviche18c0d52013-04-16 16:41:32 -0700843 return ret;
844}
845
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800846static bool fs_match(const std::string& in1, const std::string& in2) {
847 if (in1.empty() || in2.empty()) {
848 return false;
849 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800850
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800851 auto in1_end = in1.size() - 1;
852 while (in1_end > 0 && in1[in1_end] == '/') {
853 in1_end--;
854 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800855
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800856 auto in2_end = in2.size() - 1;
857 while (in2_end > 0 && in2[in2_end] == '/') {
858 in2_end--;
859 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800860
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800861 if (in1_end != in2_end) {
862 return false;
863 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800864
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800865 for (size_t i = 0; i <= in1_end; ++i) {
866 if (in1[i] != in2[i]) {
867 return false;
868 }
869 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800870
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800871 return true;
Ken Sumrallc1bf8962012-01-06 19:09:42 -0800872}
873
Tom Cherry23319eb2018-11-30 16:16:05 -0800874// Tries to mount any of the consecutive fstab entries that match
875// the mountpoint of the one given by fstab[start_idx].
876//
877// end_idx: On return, will be the last entry that was looked at.
878// attempted_idx: On return, will indicate which fstab entry
879// succeeded. In case of failure, it will be the start_idx.
880// Sets errno to match the 1st mount failure on failure.
881static bool mount_with_alternatives(const Fstab& fstab, int start_idx, int* end_idx,
882 int* attempted_idx) {
Yi Konge93040c2018-12-14 15:40:08 -0800883 unsigned long i;
JP Abgrallf22b7452014-07-02 13:16:04 -0700884 int mount_errno = 0;
Tom Cherry23319eb2018-11-30 16:16:05 -0800885 bool mounted = false;
JP Abgrallf22b7452014-07-02 13:16:04 -0700886
Tom Cherry23319eb2018-11-30 16:16:05 -0800887 // Hunt down an fstab entry for the same mount point that might succeed.
JP Abgrallf22b7452014-07-02 13:16:04 -0700888 for (i = start_idx;
Tom Cherry23319eb2018-11-30 16:16:05 -0800889 // We required that fstab entries for the same mountpoint be consecutive.
890 i < fstab.size() && fstab[start_idx].mount_point == fstab[i].mount_point; i++) {
891 // Don't try to mount/encrypt the same mount point again.
892 // Deal with alternate entries for the same point which are required to be all following
893 // each other.
894 if (mounted) {
895 LERROR << __FUNCTION__ << "(): skipping fstab dup mountpoint=" << fstab[i].mount_point
896 << " rec[" << i << "].fs_type=" << fstab[i].fs_type << " already mounted as "
897 << fstab[*attempted_idx].fs_type;
898 continue;
899 }
JP Abgrallf22b7452014-07-02 13:16:04 -0700900
Tom Cherry23319eb2018-11-30 16:16:05 -0800901 int fs_stat = prepare_fs_for_mount(fstab[i].blk_device, fstab[i]);
902 if (fs_stat & FS_STAT_INVALID_MAGIC) {
903 LERROR << __FUNCTION__
904 << "(): skipping mount due to invalid magic, mountpoint=" << fstab[i].mount_point
905 << " blk_dev=" << realpath(fstab[i].blk_device) << " rec[" << i
906 << "].fs_type=" << fstab[i].fs_type;
Eric Biggers63fb1952021-11-08 16:38:53 -0800907 mount_errno = EINVAL; // continue bootup for metadata encryption
Tom Cherry23319eb2018-11-30 16:16:05 -0800908 continue;
909 }
liminghao9a0fd1d2016-07-22 11:48:14 +0800910
Tom Cherry23319eb2018-11-30 16:16:05 -0800911 int retry_count = 2;
912 while (retry_count-- > 0) {
913 if (!__mount(fstab[i].blk_device, fstab[i].mount_point, fstab[i])) {
914 *attempted_idx = i;
915 mounted = true;
916 if (i != start_idx) {
917 LERROR << __FUNCTION__ << "(): Mounted " << fstab[i].blk_device << " on "
918 << fstab[i].mount_point << " with fs_type=" << fstab[i].fs_type
919 << " instead of " << fstab[start_idx].fs_type;
NIEJuhu5c31ffe2017-03-09 12:19:08 +0800920 }
Tom Cherry23319eb2018-11-30 16:16:05 -0800921 fs_stat &= ~FS_STAT_FULL_MOUNT_FAILED;
922 mount_errno = 0;
923 break;
924 } else {
925 if (retry_count <= 0) break; // run check_fs only once
926 fs_stat |= FS_STAT_FULL_MOUNT_FAILED;
927 // back up the first errno for crypto decisions.
928 if (mount_errno == 0) {
929 mount_errno = errno;
930 }
931 // retry after fsck
932 check_fs(fstab[i].blk_device, fstab[i].fs_type, fstab[i].mount_point, &fs_stat);
JP Abgrallf22b7452014-07-02 13:16:04 -0700933 }
Tom Cherry23319eb2018-11-30 16:16:05 -0800934 }
935 log_fs_stat(fstab[i].blk_device, fs_stat);
JP Abgrallf22b7452014-07-02 13:16:04 -0700936 }
937
938 /* Adjust i for the case where it was still withing the recs[] */
Tom Cherry23319eb2018-11-30 16:16:05 -0800939 if (i < fstab.size()) --i;
JP Abgrallf22b7452014-07-02 13:16:04 -0700940
941 *end_idx = i;
942 if (!mounted) {
943 *attempted_idx = start_idx;
944 errno = mount_errno;
Tom Cherry23319eb2018-11-30 16:16:05 -0800945 return false;
JP Abgrallf22b7452014-07-02 13:16:04 -0700946 }
Tom Cherry23319eb2018-11-30 16:16:05 -0800947 return true;
JP Abgrall4bb7bba2014-06-19 22:12:20 -0700948}
949
Tom Cherry23319eb2018-11-30 16:16:05 -0800950static bool TranslateExtLabels(FstabEntry* entry) {
951 if (!StartsWith(entry->blk_device, "LABEL=")) {
Tom Cherry0d2621f2018-12-04 13:15:09 -0800952 return true;
Christoffer Dall82982342014-12-17 21:26:54 +0100953 }
954
Tom Cherry23319eb2018-11-30 16:16:05 -0800955 std::string label = entry->blk_device.substr(6);
Tom Cherry0d2621f2018-12-04 13:15:09 -0800956 if (label.size() > 16) {
957 LERROR << "FS label is longer than allowed by filesystem";
958 return false;
959 }
Christoffer Dall82982342014-12-17 21:26:54 +0100960
Tom Cherry0d2621f2018-12-04 13:15:09 -0800961 auto blockdir = std::unique_ptr<DIR, decltype(&closedir)>{opendir("/dev/block"), closedir};
Christoffer Dall82982342014-12-17 21:26:54 +0100962 if (!blockdir) {
bowgotsai47878de2017-01-23 14:04:34 +0800963 LERROR << "couldn't open /dev/block";
Tom Cherry0d2621f2018-12-04 13:15:09 -0800964 return false;
Christoffer Dall82982342014-12-17 21:26:54 +0100965 }
966
Tom Cherry0d2621f2018-12-04 13:15:09 -0800967 struct dirent* ent;
968 while ((ent = readdir(blockdir.get()))) {
Christoffer Dall82982342014-12-17 21:26:54 +0100969 if (ent->d_type != DT_BLK)
970 continue;
971
Tom Cherry0d2621f2018-12-04 13:15:09 -0800972 unique_fd fd(TEMP_FAILURE_RETRY(
973 openat(dirfd(blockdir.get()), ent->d_name, O_RDONLY | O_CLOEXEC)));
Christoffer Dall82982342014-12-17 21:26:54 +0100974 if (fd < 0) {
bowgotsai47878de2017-01-23 14:04:34 +0800975 LERROR << "Cannot open block device /dev/block/" << ent->d_name;
Tom Cherry0d2621f2018-12-04 13:15:09 -0800976 return false;
Christoffer Dall82982342014-12-17 21:26:54 +0100977 }
978
Tom Cherry0d2621f2018-12-04 13:15:09 -0800979 ext4_super_block super_block;
Christoffer Dall82982342014-12-17 21:26:54 +0100980 if (TEMP_FAILURE_RETRY(lseek(fd, 1024, SEEK_SET)) < 0 ||
Tom Cherry0d2621f2018-12-04 13:15:09 -0800981 TEMP_FAILURE_RETRY(read(fd, &super_block, sizeof(super_block))) !=
982 sizeof(super_block)) {
983 // Probably a loopback device or something else without a readable superblock.
Christoffer Dall82982342014-12-17 21:26:54 +0100984 continue;
985 }
986
Tom Cherry0d2621f2018-12-04 13:15:09 -0800987 if (super_block.s_magic != EXT4_SUPER_MAGIC) {
bowgotsai47878de2017-01-23 14:04:34 +0800988 LINFO << "/dev/block/" << ent->d_name << " not ext{234}";
Christoffer Dall82982342014-12-17 21:26:54 +0100989 continue;
990 }
991
Tom Cherry0d2621f2018-12-04 13:15:09 -0800992 if (label == super_block.s_volume_name) {
Tom Cherryc3e7bd32018-12-06 10:28:26 -0800993 std::string new_blk_device = "/dev/block/"s + ent->d_name;
Christoffer Dall82982342014-12-17 21:26:54 +0100994
Tom Cherry23319eb2018-11-30 16:16:05 -0800995 LINFO << "resolved label " << entry->blk_device << " to " << new_blk_device;
Christoffer Dall82982342014-12-17 21:26:54 +0100996
Tom Cherry23319eb2018-11-30 16:16:05 -0800997 entry->blk_device = new_blk_device;
Tom Cherry0d2621f2018-12-04 13:15:09 -0800998 return true;
Christoffer Dall82982342014-12-17 21:26:54 +0100999 }
1000 }
1001
Tom Cherry0d2621f2018-12-04 13:15:09 -08001002 return false;
Christoffer Dall82982342014-12-17 21:26:54 +01001003}
1004
Tom Cherry23319eb2018-11-30 16:16:05 -08001005static bool should_use_metadata_encryption(const FstabEntry& entry) {
Eric Biggers63fb1952021-11-08 16:38:53 -08001006 return !entry.metadata_key_dir.empty() && entry.fs_mgr_flags.file_encryption;
Paul Lawrence9dbe97b2017-04-21 12:41:48 -07001007}
1008
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001009// Check to see if a mountable volume has encryption requirements
Tom Cherry23319eb2018-11-30 16:16:05 -08001010static int handle_encryptable(const FstabEntry& entry) {
Eric Biggers63fb1952021-11-08 16:38:53 -08001011 if (should_use_metadata_encryption(entry)) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001012 if (umount(entry.mount_point.c_str()) == 0) {
Paul Lawrence9dbe97b2017-04-21 12:41:48 -07001013 return FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION;
1014 } else {
Tom Cherry23319eb2018-11-30 16:16:05 -08001015 PERROR << "Could not umount " << entry.mount_point << " - fail since can't encrypt";
Paul Lawrence9dbe97b2017-04-21 12:41:48 -07001016 return FS_MGR_MNTALL_FAIL;
1017 }
Eric Biggers63fb1952021-11-08 16:38:53 -08001018 } else if (entry.fs_mgr_flags.file_encryption) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001019 LINFO << entry.mount_point << " is file encrypted";
Paul Lawrence69080182016-02-02 10:31:30 -08001020 return FS_MGR_MNTALL_DEV_FILE_ENCRYPTED;
Paul Lawrence1098aac2016-03-04 15:52:33 -08001021 } else {
1022 return FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE;
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001023 }
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001024}
1025
Paul Crowley9acab5a2020-08-14 11:05:05 -07001026static void set_type_property(int status) {
1027 switch (status) {
Paul Crowley9acab5a2020-08-14 11:05:05 -07001028 case FS_MGR_MNTALL_DEV_FILE_ENCRYPTED:
1029 case FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED:
1030 case FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION:
1031 SetProperty("ro.crypto.type", "file");
1032 break;
1033 }
1034}
1035
Tom Cherry3a803eb2019-09-25 16:23:50 -07001036static bool call_vdc(const std::vector<std::string>& args, int* ret) {
Paul Crowleyc6846962018-01-30 09:56:03 -08001037 std::vector<char const*> argv;
1038 argv.emplace_back("/system/bin/vdc");
1039 for (auto& arg : args) {
1040 argv.emplace_back(arg.c_str());
1041 }
1042 LOG(INFO) << "Calling: " << android::base::Join(argv, ' ');
Tom Cherry3a803eb2019-09-25 16:23:50 -07001043 int err = logwrap_fork_execvp(argv.size(), argv.data(), ret, false, LOG_ALOG, false, nullptr);
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001044 if (err != 0) {
1045 LOG(ERROR) << "vdc call failed with error code: " << err;
1046 return false;
1047 }
1048 LOG(DEBUG) << "vdc finished successfully";
Tom Cherry3a803eb2019-09-25 16:23:50 -07001049 if (ret != nullptr) {
1050 *ret = WEXITSTATUS(*ret);
1051 }
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001052 return true;
1053}
1054
Tom Cherry23319eb2018-11-30 16:16:05 -08001055bool fs_mgr_update_logical_partition(FstabEntry* entry) {
David Anderson62e5b202018-05-01 17:09:17 -07001056 // Logical partitions are specified with a named partition rather than a
1057 // block device, so if the block device is a path, then it has already
1058 // been updated.
Tom Cherry23319eb2018-11-30 16:16:05 -08001059 if (entry->blk_device[0] == '/') {
David Anderson62e5b202018-05-01 17:09:17 -07001060 return true;
1061 }
1062
David Andersonb5acb1a2018-06-26 17:07:55 -07001063 DeviceMapper& dm = DeviceMapper::Instance();
David Anderson62e5b202018-05-01 17:09:17 -07001064 std::string device_name;
Tom Cherry23319eb2018-11-30 16:16:05 -08001065 if (!dm.GetDmDevicePathByName(entry->blk_device, &device_name)) {
David Anderson62e5b202018-05-01 17:09:17 -07001066 return false;
1067 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001068
1069 entry->blk_device = device_name;
1070 return true;
1071}
1072
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001073static bool SupportsCheckpoint(FstabEntry* entry) {
1074 return entry->fs_mgr_flags.checkpoint_blk || entry->fs_mgr_flags.checkpoint_fs;
1075}
1076
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001077class CheckpointManager {
1078 public:
Paul Lawrence20553642020-06-12 07:32:23 -07001079 CheckpointManager(int needs_checkpoint = -1, bool metadata_encrypted = false)
1080 : needs_checkpoint_(needs_checkpoint), metadata_encrypted_(metadata_encrypted) {}
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001081
Nikita Ioffe12a36072019-10-23 20:11:32 +01001082 bool NeedsCheckpoint() {
1083 if (needs_checkpoint_ != UNKNOWN) {
1084 return needs_checkpoint_ == YES;
1085 }
1086 if (!call_vdc({"checkpoint", "needsCheckpoint"}, &needs_checkpoint_)) {
1087 LERROR << "Failed to find if checkpointing is needed. Assuming no.";
1088 needs_checkpoint_ = NO;
1089 }
1090 return needs_checkpoint_ == YES;
1091 }
1092
Paul Lawrence323959e2019-06-25 14:36:52 -07001093 bool Update(FstabEntry* entry, const std::string& block_device = std::string()) {
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001094 if (!SupportsCheckpoint(entry)) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001095 return true;
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001096 }
Paul Lawrence786d0b22018-09-21 10:49:38 -07001097
Paul Lawrence20553642020-06-12 07:32:23 -07001098 if (entry->fs_mgr_flags.checkpoint_blk && !metadata_encrypted_) {
Tom Cherry3a803eb2019-09-25 16:23:50 -07001099 call_vdc({"checkpoint", "restoreCheckpoint", entry->blk_device}, nullptr);
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001100 }
1101
Nikita Ioffe12a36072019-10-23 20:11:32 +01001102 if (!NeedsCheckpoint()) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001103 return true;
1104 }
1105
Paul Lawrence323959e2019-06-25 14:36:52 -07001106 if (!UpdateCheckpointPartition(entry, block_device)) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001107 LERROR << "Could not set up checkpoint partition, skipping!";
Paul Lawrence786d0b22018-09-21 10:49:38 -07001108 return false;
1109 }
1110
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001111 return true;
1112 }
1113
Tom Cherry23319eb2018-11-30 16:16:05 -08001114 bool Revert(FstabEntry* entry) {
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001115 if (!SupportsCheckpoint(entry)) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001116 return true;
Paul Lawrence786d0b22018-09-21 10:49:38 -07001117 }
1118
Tom Cherry23319eb2018-11-30 16:16:05 -08001119 if (device_map_.find(entry->blk_device) == device_map_.end()) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001120 return true;
Paul Lawrence786d0b22018-09-21 10:49:38 -07001121 }
1122
Tom Cherry23319eb2018-11-30 16:16:05 -08001123 std::string bow_device = entry->blk_device;
1124 entry->blk_device = device_map_[bow_device];
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001125 device_map_.erase(bow_device);
1126
Paul Lawrence786d0b22018-09-21 10:49:38 -07001127 DeviceMapper& dm = DeviceMapper::Instance();
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001128 if (!dm.DeleteDevice("bow")) {
1129 PERROR << "Failed to remove bow device";
Paul Lawrence786d0b22018-09-21 10:49:38 -07001130 }
1131
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001132 return true;
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001133 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001134
1135 private:
Paul Lawrence323959e2019-06-25 14:36:52 -07001136 bool UpdateCheckpointPartition(FstabEntry* entry, const std::string& block_device) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001137 if (entry->fs_mgr_flags.checkpoint_fs) {
1138 if (is_f2fs(entry->fs_type)) {
Daniel Rosenberg7c59f1a2020-02-28 18:37:22 -08001139 entry->fs_checkpoint_opts = ",checkpoint=disable";
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001140 } else {
Tom Cherry23319eb2018-11-30 16:16:05 -08001141 LERROR << entry->fs_type << " does not implement checkpoints.";
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001142 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001143 } else if (entry->fs_mgr_flags.checkpoint_blk) {
Paul Lawrence323959e2019-06-25 14:36:52 -07001144 auto actual_block_device = block_device.empty() ? entry->blk_device : block_device;
1145 if (fs_mgr_find_bow_device(actual_block_device).empty()) {
1146 unique_fd fd(
1147 TEMP_FAILURE_RETRY(open(entry->blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
1148 if (fd < 0) {
1149 PERROR << "Cannot open device " << entry->blk_device;
1150 return false;
1151 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001152
Paul Lawrence323959e2019-06-25 14:36:52 -07001153 uint64_t size = get_block_device_size(fd) / 512;
1154 if (!size) {
1155 PERROR << "Cannot get device size";
1156 return false;
1157 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001158
Paul Lawrence323959e2019-06-25 14:36:52 -07001159 android::dm::DmTable table;
Paul Lawrence2f0c6cb2020-06-01 12:58:04 -07001160 auto bowTarget =
1161 std::make_unique<android::dm::DmTargetBow>(0, size, entry->blk_device);
1162
1163 // dm-bow uses the first block as a log record, and relocates the real first block
1164 // elsewhere. For metadata encrypted devices, dm-bow sits below dm-default-key, and
1165 // for post Android Q devices dm-default-key uses a block size of 4096 always.
1166 // So if dm-bow's block size, which by default is the block size of the underlying
1167 // hardware, is less than dm-default-key's, blocks will get broken up and I/O will
1168 // fail as it won't be data_unit_size aligned.
1169 // However, since it is possible there is an already shipping non
1170 // metadata-encrypted device with smaller blocks, we must not change this for
1171 // devices shipped with Q or earlier unless they explicitly selected dm-default-key
1172 // v2
Paul Lawrence2f0c6cb2020-06-01 12:58:04 -07001173 unsigned int options_format_version = android::base::GetUintProperty<unsigned int>(
1174 "ro.crypto.dm_default_key.options_format.version",
Eric Biggers75ebdd92020-08-10 11:14:51 -07001175 (android::fscrypt::GetFirstApiLevel() <= __ANDROID_API_Q__ ? 1 : 2));
Paul Lawrence2f0c6cb2020-06-01 12:58:04 -07001176 if (options_format_version > 1) {
1177 bowTarget->SetBlockSize(4096);
1178 }
1179
1180 if (!table.AddTarget(std::move(bowTarget))) {
Paul Lawrence323959e2019-06-25 14:36:52 -07001181 LERROR << "Failed to add bow target";
1182 return false;
1183 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001184
Paul Lawrence323959e2019-06-25 14:36:52 -07001185 DeviceMapper& dm = DeviceMapper::Instance();
1186 if (!dm.CreateDevice("bow", table)) {
1187 PERROR << "Failed to create bow device";
1188 return false;
1189 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001190
Paul Lawrence323959e2019-06-25 14:36:52 -07001191 std::string name;
1192 if (!dm.GetDmDevicePathByName("bow", &name)) {
1193 PERROR << "Failed to get bow device name";
1194 return false;
1195 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001196
Paul Lawrence323959e2019-06-25 14:36:52 -07001197 device_map_[name] = entry->blk_device;
1198 entry->blk_device = name;
1199 }
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001200 }
1201 return true;
1202 }
1203
1204 enum { UNKNOWN = -1, NO = 0, YES = 1 };
1205 int needs_checkpoint_;
Paul Lawrence20553642020-06-12 07:32:23 -07001206 bool metadata_encrypted_;
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001207 std::map<std::string, std::string> device_map_;
1208};
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001209
Paul Lawrence323959e2019-06-25 14:36:52 -07001210std::string fs_mgr_find_bow_device(const std::string& block_device) {
1211 if (block_device.substr(0, 5) != "/dev/") {
1212 LOG(ERROR) << "Expected block device, got " << block_device;
1213 return std::string();
1214 }
1215
1216 std::string sys_dir = std::string("/sys/") + block_device.substr(5);
1217
1218 for (;;) {
1219 std::string name;
1220 if (!android::base::ReadFileToString(sys_dir + "/dm/name", &name)) {
1221 PLOG(ERROR) << block_device << " is not dm device";
1222 return std::string();
1223 }
1224
1225 if (name == "bow\n") return sys_dir;
1226
1227 std::string slaves = sys_dir + "/slaves";
1228 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(slaves.c_str()), closedir);
1229 if (!directory) {
1230 PLOG(ERROR) << "Can't open slave directory " << slaves;
1231 return std::string();
1232 }
1233
1234 int count = 0;
1235 for (dirent* entry = readdir(directory.get()); entry; entry = readdir(directory.get())) {
1236 if (entry->d_type != DT_LNK) continue;
1237
1238 if (count == 1) {
1239 LOG(ERROR) << "Too many slaves in " << slaves;
1240 return std::string();
1241 }
1242
1243 ++count;
1244 sys_dir = std::string("/sys/block/") + entry->d_name;
1245 }
1246
1247 if (count != 1) {
1248 LOG(ERROR) << "No slave in " << slaves;
1249 return std::string();
1250 }
1251 }
1252}
1253
David Anderson671bd812020-01-24 19:19:27 -08001254static constexpr const char* kUserdataWrapperName = "userdata-wrapper";
1255
1256static void WrapUserdata(FstabEntry* entry, dev_t dev, const std::string& block_device) {
1257 DeviceMapper& dm = DeviceMapper::Instance();
1258 if (dm.GetState(kUserdataWrapperName) != DmDeviceState::INVALID) {
1259 // This will report failure for us. If we do fail to get the path,
1260 // we leave the device unwrapped.
1261 dm.GetDmDevicePathByName(kUserdataWrapperName, &entry->blk_device);
1262 return;
1263 }
1264
1265 unique_fd fd(open(block_device.c_str(), O_RDONLY | O_CLOEXEC));
1266 if (fd < 0) {
1267 PLOG(ERROR) << "open failed: " << entry->blk_device;
1268 return;
1269 }
1270
1271 auto dev_str = android::base::StringPrintf("%u:%u", major(dev), minor(dev));
1272 uint64_t sectors = get_block_device_size(fd) / 512;
1273
1274 android::dm::DmTable table;
1275 table.Emplace<DmTargetLinear>(0, sectors, dev_str, 0);
1276
1277 std::string dm_path;
1278 if (!dm.CreateDevice(kUserdataWrapperName, table, &dm_path, 20s)) {
1279 LOG(ERROR) << "Failed to create userdata wrapper device";
1280 return;
1281 }
1282 entry->blk_device = dm_path;
1283}
1284
1285// When using Virtual A/B, partitions can be backed by /data and mapped with
1286// device-mapper in first-stage init. This can happen when merging an OTA or
1287// when using adb remount to house "scratch". In this case, /data cannot be
1288// mounted directly off the userdata block device, and e2fsck will refuse to
1289// scan it, because the kernel reports the block device as in-use.
1290//
1291// As a workaround, when mounting /data, we create a trivial dm-linear wrapper
1292// if the underlying block device already has dependencies. Note that we make
1293// an exception for metadata-encrypted devices, since dm-default-key is already
1294// a wrapper.
1295static void WrapUserdataIfNeeded(FstabEntry* entry, const std::string& actual_block_device = {}) {
1296 const auto& block_device =
1297 actual_block_device.empty() ? entry->blk_device : actual_block_device;
Paul Crowley7823e322020-01-30 16:03:45 -08001298 if (entry->mount_point != "/data" || !entry->metadata_key_dir.empty() ||
David Anderson671bd812020-01-24 19:19:27 -08001299 android::base::StartsWith(block_device, "/dev/block/dm-")) {
1300 return;
1301 }
1302
1303 struct stat st;
1304 if (stat(block_device.c_str(), &st) < 0) {
1305 PLOG(ERROR) << "stat failed: " << block_device;
1306 return;
1307 }
1308
1309 std::string path = android::base::StringPrintf("/sys/dev/block/%u:%u/holders",
1310 major(st.st_rdev), minor(st.st_rdev));
1311 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
1312 if (!dir) {
1313 PLOG(ERROR) << "opendir failed: " << path;
1314 return;
1315 }
1316
1317 struct dirent* d;
1318 bool has_holders = false;
1319 while ((d = readdir(dir.get())) != nullptr) {
1320 if (strcmp(d->d_name, ".") != 0 && strcmp(d->d_name, "..") != 0) {
1321 has_holders = true;
1322 break;
1323 }
1324 }
1325
1326 if (has_holders) {
1327 WrapUserdata(entry, st.st_rdev, block_device);
1328 }
1329}
1330
David Anderson42c32bf2019-01-14 16:51:52 -08001331static bool IsMountPointMounted(const std::string& mount_point) {
1332 // Check if this is already mounted.
1333 Fstab fstab;
1334 if (!ReadFstabFromFile("/proc/mounts", &fstab)) {
1335 return false;
1336 }
Tom Cherry2e545f82019-01-29 08:49:57 -08001337 return GetEntryForMountPoint(&fstab, mount_point) != nullptr;
David Anderson42c32bf2019-01-14 16:51:52 -08001338}
1339
Tom Cherry23319eb2018-11-30 16:16:05 -08001340// When multiple fstab records share the same mount_point, it will try to mount each
1341// one in turn, and ignore any duplicates after a first successful mount.
1342// Returns -1 on error, and FS_MGR_MNTALL_* otherwise.
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001343MountAllResult fs_mgr_mount_all(Fstab* fstab, int mount_mode) {
Paul Lawrence1098aac2016-03-04 15:52:33 -08001344 int encryptable = FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE;
Mohamad Ayyash38afe5f2014-03-10 15:40:29 -07001345 int error_count = 0;
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001346 CheckpointManager checkpoint_manager;
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001347 AvbUniquePtr avb_handle(nullptr);
Jaegeuk Kima7635712020-12-15 08:46:44 -08001348 bool wiped = false;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001349
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001350 bool userdata_mounted = false;
Tom Cherry23319eb2018-11-30 16:16:05 -08001351 if (fstab->empty()) {
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001352 return {FS_MGR_MNTALL_FAIL, userdata_mounted};
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001353 }
1354
Woody Chow7fb93c12020-01-21 10:50:34 +09001355 // Keep i int to prevent unsigned integer overflow from (i = top_idx - 1),
1356 // where top_idx is 0. It will give SIGABRT
1357 for (int i = 0; i < static_cast<int>(fstab->size()); i++) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001358 auto& current_entry = (*fstab)[i];
1359
David Anderson42c32bf2019-01-14 16:51:52 -08001360 // If a filesystem should have been mounted in the first stage, we
1361 // ignore it here. With one exception, if the filesystem is
1362 // formattable, then it can only be formatted in the second stage,
1363 // so we allow it to mount here.
1364 if (current_entry.fs_mgr_flags.first_stage_mount &&
1365 (!current_entry.fs_mgr_flags.formattable ||
1366 IsMountPointMounted(current_entry.mount_point))) {
1367 continue;
1368 }
1369
Tom Cherry23319eb2018-11-30 16:16:05 -08001370 // Don't mount entries that are managed by vold or not for the mount mode.
1371 if (current_entry.fs_mgr_flags.vold_managed || current_entry.fs_mgr_flags.recovery_only ||
Tom Cherry23319eb2018-11-30 16:16:05 -08001372 ((mount_mode == MOUNT_MODE_LATE) && !current_entry.fs_mgr_flags.late_mount) ||
1373 ((mount_mode == MOUNT_MODE_EARLY) && current_entry.fs_mgr_flags.late_mount)) {
Ken Sumrallab6b8522013-02-13 12:58:40 -08001374 continue;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001375 }
1376
Tom Cherry23319eb2018-11-30 16:16:05 -08001377 // Skip swap and raw partition entries such as boot, recovery, etc.
1378 if (current_entry.fs_type == "swap" || current_entry.fs_type == "emmc" ||
1379 current_entry.fs_type == "mtd") {
Ken Sumrallab6b8522013-02-13 12:58:40 -08001380 continue;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001381 }
1382
Tom Cherry23319eb2018-11-30 16:16:05 -08001383 // Skip mounting the root partition, as it will already have been mounted.
1384 if (current_entry.mount_point == "/" || current_entry.mount_point == "/system") {
1385 if ((current_entry.flags & MS_RDONLY) != 0) {
1386 fs_mgr_set_blk_ro(current_entry.blk_device);
Daniel Rosenberg31a4faf2015-06-29 17:33:05 -07001387 }
1388 continue;
1389 }
1390
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001391 // Terrible hack to make it possible to remount /data.
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001392 // TODO: refactor fs_mgr_mount_all and get rid of this.
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001393 if (mount_mode == MOUNT_MODE_ONLY_USERDATA && current_entry.mount_point != "/data") {
1394 continue;
1395 }
1396
Tom Cherry23319eb2018-11-30 16:16:05 -08001397 // Translate LABEL= file system labels into block devices.
1398 if (is_extfs(current_entry.fs_type)) {
1399 if (!TranslateExtLabels(&current_entry)) {
bowgotsai47878de2017-01-23 14:04:34 +08001400 LERROR << "Could not translate label to block device";
Christoffer Dall82982342014-12-17 21:26:54 +01001401 continue;
1402 }
1403 }
1404
Tom Cherry23319eb2018-11-30 16:16:05 -08001405 if (current_entry.fs_mgr_flags.logical) {
1406 if (!fs_mgr_update_logical_partition(&current_entry)) {
David Anderson62e5b202018-05-01 17:09:17 -07001407 LERROR << "Could not set up logical partition, skipping!";
1408 continue;
1409 }
1410 }
1411
David Anderson671bd812020-01-24 19:19:27 -08001412 WrapUserdataIfNeeded(&current_entry);
1413
Tom Cherry23319eb2018-11-30 16:16:05 -08001414 if (!checkpoint_manager.Update(&current_entry)) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001415 continue;
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001416 }
1417
David Anderson5c475c72019-06-11 17:40:49 -07001418 if (current_entry.fs_mgr_flags.wait && !WaitForFile(current_entry.blk_device, 20s)) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001419 LERROR << "Skipping '" << current_entry.blk_device << "' during mount_all";
Jinguang Dong9d344962017-06-13 10:20:34 +08001420 continue;
Ken Sumrallab6b8522013-02-13 12:58:40 -08001421 }
1422
Tom Cherry23319eb2018-11-30 16:16:05 -08001423 if (current_entry.fs_mgr_flags.avb) {
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001424 if (!avb_handle) {
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001425 avb_handle = AvbHandle::Open();
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001426 if (!avb_handle) {
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001427 LERROR << "Failed to open AvbHandle";
Paul Crowley9acab5a2020-08-14 11:05:05 -07001428 set_type_property(encryptable);
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001429 return {FS_MGR_MNTALL_FAIL, userdata_mounted};
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001430 }
1431 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001432 if (avb_handle->SetUpAvbHashtree(&current_entry, true /* wait_for_verity_dev */) ==
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001433 AvbHashtreeResult::kFail) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001434 LERROR << "Failed to set up AVB on partition: " << current_entry.mount_point
1435 << ", skipping!";
1436 // Skips mounting the device.
bowgotsaib51722b2017-01-11 22:21:38 +08001437 continue;
1438 }
Bowgo Tsaif3e28e12019-02-20 21:53:47 +08001439 } else if (!current_entry.avb_keys.empty()) {
Bowgo Tsaidefe1cb2019-01-25 12:07:09 +08001440 if (AvbHandle::SetUpStandaloneAvbHashtree(&current_entry) == AvbHashtreeResult::kFail) {
1441 LERROR << "Failed to set up AVB on standalone partition: "
1442 << current_entry.mount_point << ", skipping!";
1443 // Skips mounting the device.
1444 continue;
1445 }
Geremy Condra3ad3d1c2013-02-22 18:11:41 -08001446 }
bowgotsaib51722b2017-01-11 22:21:38 +08001447
JP Abgrallf22b7452014-07-02 13:16:04 -07001448 int last_idx_inspected;
Chris Fries79f33842013-09-05 13:19:21 -05001449 int top_idx = i;
Tom Cherry23319eb2018-11-30 16:16:05 -08001450 int attempted_idx = -1;
Chris Fries79f33842013-09-05 13:19:21 -05001451
Tom Cherry23319eb2018-11-30 16:16:05 -08001452 bool mret = mount_with_alternatives(*fstab, i, &last_idx_inspected, &attempted_idx);
1453 auto& attempted_entry = (*fstab)[attempted_idx];
JP Abgrallf22b7452014-07-02 13:16:04 -07001454 i = last_idx_inspected;
Tom Cherry23319eb2018-11-30 16:16:05 -08001455 int mount_errno = errno;
JP Abgrallf786fe52014-06-18 07:28:14 +00001456
Tom Cherry23319eb2018-11-30 16:16:05 -08001457 // Handle success and deal with encryptability.
1458 if (mret) {
1459 int status = handle_encryptable(attempted_entry);
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001460
1461 if (status == FS_MGR_MNTALL_FAIL) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001462 // Fatal error - no point continuing.
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001463 return {status, userdata_mounted};
Paul Lawrence166fa3d2014-02-03 13:27:49 -08001464 }
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001465
Paul Lawrence1098aac2016-03-04 15:52:33 -08001466 if (status != FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
1467 if (encryptable != FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001468 // Log and continue
bowgotsai47878de2017-01-23 14:04:34 +08001469 LERROR << "Only one encryptable/encrypted partition supported";
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001470 }
1471 encryptable = status;
Paul Crowleyc6846962018-01-30 09:56:03 -08001472 if (status == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
Paul Lawrence323959e2019-06-25 14:36:52 -07001473 if (!call_vdc({"cryptfs", "encryptFstab", attempted_entry.blk_device,
Jaegeuk Kima7635712020-12-15 08:46:44 -08001474 attempted_entry.mount_point, wiped ? "true" : "false",
1475 attempted_entry.fs_type},
Tom Cherry3a803eb2019-09-25 16:23:50 -07001476 nullptr)) {
Paul Crowleyc6846962018-01-30 09:56:03 -08001477 LERROR << "Encryption failed";
Paul Crowley9acab5a2020-08-14 11:05:05 -07001478 set_type_property(encryptable);
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001479 return {FS_MGR_MNTALL_FAIL, userdata_mounted};
Paul Crowleyc6846962018-01-30 09:56:03 -08001480 }
1481 }
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001482 }
1483
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001484 if (current_entry.mount_point == "/data") {
1485 userdata_mounted = true;
1486 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001487 // Success! Go get the next one.
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001488 continue;
1489 }
1490
Tom Cherry23319eb2018-11-30 16:16:05 -08001491 // Mounting failed, understand why and retry.
Jaegeuk Kima7635712020-12-15 08:46:44 -08001492 wiped = partition_wiped(current_entry.blk_device.c_str());
Tom Cherry23319eb2018-11-30 16:16:05 -08001493 if (mount_errno != EBUSY && mount_errno != EACCES &&
1494 current_entry.fs_mgr_flags.formattable && wiped) {
1495 // current_entry and attempted_entry point at the same partition, but sometimes
1496 // at two different lines in the fstab. Use current_entry for formatting
1497 // as that is the preferred one.
1498 LERROR << __FUNCTION__ << "(): " << realpath(current_entry.blk_device)
1499 << " is wiped and " << current_entry.mount_point << " " << current_entry.fs_type
1500 << " is formattable. Format it.";
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001501
Tom Cherry23319eb2018-11-30 16:16:05 -08001502 checkpoint_manager.Revert(&current_entry);
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001503
Jaegeuk Kima7635712020-12-15 08:46:44 -08001504 // EncryptInplace will be used when vdc gives an error or needs to format partitions
1505 // other than /data
1506 if (should_use_metadata_encryption(current_entry) &&
1507 current_entry.mount_point == "/data") {
1508
1509 // vdc->Format requires "ro.crypto.type" to set an encryption flag
1510 encryptable = FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED;
1511 set_type_property(encryptable);
1512
1513 if (!call_vdc({"cryptfs", "encryptFstab", current_entry.blk_device,
1514 current_entry.mount_point, "true" /* shouldFormat */,
1515 current_entry.fs_type},
1516 nullptr)) {
1517 LERROR << "Encryption failed";
1518 } else {
1519 userdata_mounted = true;
1520 continue;
1521 }
1522 }
1523
Eric Biggers4d0c5ef2021-11-08 16:38:54 -08001524 if (fs_mgr_do_format(current_entry) == 0) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001525 // Let's replay the mount actions.
Chris Fries79f33842013-09-05 13:19:21 -05001526 i = top_idx - 1;
1527 continue;
Matthew Bouyack9c59cbc2016-05-02 15:55:30 -07001528 } else {
bowgotsai47878de2017-01-23 14:04:34 +08001529 LERROR << __FUNCTION__ << "(): Format failed. "
1530 << "Suggest recovery...";
Matthew Bouyack9c59cbc2016-05-02 15:55:30 -07001531 encryptable = FS_MGR_MNTALL_DEV_NEEDS_RECOVERY;
1532 continue;
Chris Fries79f33842013-09-05 13:19:21 -05001533 }
1534 }
Paul Lawrence9dbe97b2017-04-21 12:41:48 -07001535
Tom Cherry23319eb2018-11-30 16:16:05 -08001536 // mount(2) returned an error, handle the encryptable/formattable case.
Eric Biggers63fb1952021-11-08 16:38:53 -08001537 if (mount_errno != EBUSY && mount_errno != EACCES &&
1538 should_use_metadata_encryption(attempted_entry)) {
Paul Lawrence323959e2019-06-25 14:36:52 -07001539 if (!call_vdc({"cryptfs", "mountFstab", attempted_entry.blk_device,
Tom Cherry3a803eb2019-09-25 16:23:50 -07001540 attempted_entry.mount_point},
1541 nullptr)) {
Paul Crowleyc6846962018-01-30 09:56:03 -08001542 ++error_count;
Qilin Tan12d95df2020-11-02 11:25:09 +08001543 } else if (current_entry.mount_point == "/data") {
1544 userdata_mounted = true;
Paul Crowleyc6846962018-01-30 09:56:03 -08001545 }
Paul Lawrence9dbe97b2017-04-21 12:41:48 -07001546 encryptable = FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED;
Paul Crowleyc6846962018-01-30 09:56:03 -08001547 continue;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001548 } else {
Bowgo Tsai59af33c2017-05-24 18:51:36 +08001549 // fs_options might be null so we cannot use PERROR << directly.
1550 // Use StringPrintf to output "(null)" instead.
Tom Cherry23319eb2018-11-30 16:16:05 -08001551 if (attempted_entry.fs_mgr_flags.no_fail) {
Bowgo Tsai59af33c2017-05-24 18:51:36 +08001552 PERROR << android::base::StringPrintf(
Tom Cherry23319eb2018-11-30 16:16:05 -08001553 "Ignoring failure to mount an un-encryptable or wiped "
1554 "partition on %s at %s options: %s",
1555 attempted_entry.blk_device.c_str(), attempted_entry.mount_point.c_str(),
1556 attempted_entry.fs_options.c_str());
Daniel Rosenbergd38e3c52016-04-07 20:10:25 -07001557 } else {
Bowgo Tsai59af33c2017-05-24 18:51:36 +08001558 PERROR << android::base::StringPrintf(
Tom Cherry23319eb2018-11-30 16:16:05 -08001559 "Failed to mount an un-encryptable or wiped partition "
1560 "on %s at %s options: %s",
1561 attempted_entry.blk_device.c_str(), attempted_entry.mount_point.c_str(),
1562 attempted_entry.fs_options.c_str());
Daniel Rosenbergd38e3c52016-04-07 20:10:25 -07001563 ++error_count;
1564 }
Mohamad Ayyash38afe5f2014-03-10 15:40:29 -07001565 continue;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001566 }
1567 }
1568
Paul Crowley9acab5a2020-08-14 11:05:05 -07001569 set_type_property(encryptable);
1570
Mark Salyzynd9e6c202018-06-20 14:08:09 -07001571#if ALLOW_ADBD_DISABLE_VERITY == 1 // "userdebug" build
Mark Salyzynf35db9b2018-09-20 15:23:00 -07001572 fs_mgr_overlayfs_mount_all(fstab);
Mark Salyzynd9e6c202018-06-20 14:08:09 -07001573#endif
1574
Mohamad Ayyash38afe5f2014-03-10 15:40:29 -07001575 if (error_count) {
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001576 return {FS_MGR_MNTALL_FAIL, userdata_mounted};
Mohamad Ayyash38afe5f2014-03-10 15:40:29 -07001577 } else {
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001578 return {encryptable, userdata_mounted};
Mohamad Ayyash38afe5f2014-03-10 15:40:29 -07001579 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001580}
1581
Yifan Hong402633d2019-04-09 10:11:34 -07001582int fs_mgr_umount_all(android::fs_mgr::Fstab* fstab) {
1583 AvbUniquePtr avb_handle(nullptr);
1584 int ret = FsMgrUmountStatus::SUCCESS;
1585 for (auto& current_entry : *fstab) {
1586 if (!IsMountPointMounted(current_entry.mount_point)) {
1587 continue;
1588 }
1589
1590 if (umount(current_entry.mount_point.c_str()) == -1) {
1591 PERROR << "Failed to umount " << current_entry.mount_point;
1592 ret |= FsMgrUmountStatus::ERROR_UMOUNT;
1593 continue;
1594 }
1595
1596 if (current_entry.fs_mgr_flags.logical) {
1597 if (!fs_mgr_update_logical_partition(&current_entry)) {
1598 LERROR << "Could not get logical partition blk_device, skipping!";
1599 ret |= FsMgrUmountStatus::ERROR_DEVICE_MAPPER;
1600 continue;
1601 }
1602 }
1603
1604 if (current_entry.fs_mgr_flags.avb || !current_entry.avb_keys.empty()) {
1605 if (!AvbHandle::TearDownAvbHashtree(&current_entry, true /* wait */)) {
1606 LERROR << "Failed to tear down AVB on mount point: " << current_entry.mount_point;
1607 ret |= FsMgrUmountStatus::ERROR_VERITY;
1608 continue;
1609 }
Yifan Hong402633d2019-04-09 10:11:34 -07001610 }
1611 }
1612 return ret;
1613}
1614
Nikita Ioffe7b41a152020-03-25 00:06:51 +00001615static std::chrono::milliseconds GetMillisProperty(const std::string& name,
1616 std::chrono::milliseconds default_value) {
1617 auto value = GetUintProperty(name, static_cast<uint64_t>(default_value.count()));
1618 return std::chrono::milliseconds(std::move(value));
1619}
1620
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001621static bool fs_mgr_unmount_all_data_mounts(const std::string& data_block_device) {
1622 LINFO << __FUNCTION__ << "(): about to umount everything on top of " << data_block_device;
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001623 Timer t;
Nikita Ioffe7b41a152020-03-25 00:06:51 +00001624 auto timeout = GetMillisProperty("init.userspace_reboot.userdata_remount.timeoutmillis", 5s);
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001625 while (true) {
1626 bool umount_done = true;
1627 Fstab proc_mounts;
1628 if (!ReadFstabFromFile("/proc/mounts", &proc_mounts)) {
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001629 LERROR << __FUNCTION__ << "(): Can't read /proc/mounts";
Greg Kaiserd8fdf602019-12-20 19:39:16 -08001630 return false;
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001631 }
1632 // Now proceed with other bind mounts on top of /data.
1633 for (const auto& entry : proc_mounts) {
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001634 std::string block_device;
1635 if (StartsWith(entry.blk_device, "/dev/block") &&
1636 !Realpath(entry.blk_device, &block_device)) {
1637 PWARNING << __FUNCTION__ << "(): failed to realpath " << entry.blk_device;
1638 block_device = entry.blk_device;
1639 }
1640 if (data_block_device == block_device) {
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001641 if (umount2(entry.mount_point.c_str(), 0) != 0) {
Nikita Ioffeb03e0cf2020-01-13 16:05:07 +00001642 PERROR << __FUNCTION__ << "(): Failed to umount " << entry.mount_point;
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001643 umount_done = false;
1644 }
1645 }
1646 }
1647 if (umount_done) {
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001648 LINFO << __FUNCTION__ << "(): Unmounting /data took " << t;
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001649 return true;
1650 }
1651 if (t.duration() > timeout) {
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001652 LERROR << __FUNCTION__ << "(): Timed out unmounting all mounts on "
1653 << data_block_device;
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001654 Fstab remaining_mounts;
1655 if (!ReadFstabFromFile("/proc/mounts", &remaining_mounts)) {
1656 LERROR << __FUNCTION__ << "(): Can't read /proc/mounts";
1657 } else {
1658 LERROR << __FUNCTION__ << "(): Following mounts remaining";
1659 for (const auto& e : remaining_mounts) {
1660 LERROR << __FUNCTION__ << "(): mount point: " << e.mount_point
1661 << " block device: " << e.blk_device;
1662 }
1663 }
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001664 return false;
1665 }
1666 std::this_thread::sleep_for(50ms);
1667 }
1668}
1669
Nikita Ioffe17824f02020-03-06 17:36:05 +00001670static bool UnwindDmDeviceStack(const std::string& block_device,
1671 std::vector<std::string>* dm_stack) {
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001672 if (!StartsWith(block_device, "/dev/block/")) {
1673 LWARNING << block_device << " is not a block device";
Nikita Ioffe17824f02020-03-06 17:36:05 +00001674 return false;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001675 }
Nikita Ioffe17824f02020-03-06 17:36:05 +00001676 std::string current = block_device;
1677 DeviceMapper& dm = DeviceMapper::Instance();
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001678 while (true) {
Nikita Ioffe17824f02020-03-06 17:36:05 +00001679 dm_stack->push_back(current);
1680 if (!dm.IsDmBlockDevice(current)) {
1681 break;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001682 }
Nikita Ioffe17824f02020-03-06 17:36:05 +00001683 auto parent = dm.GetParentBlockDeviceByPath(current);
1684 if (!parent) {
1685 return false;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001686 }
Nikita Ioffe17824f02020-03-06 17:36:05 +00001687 current = *parent;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001688 }
Nikita Ioffe17824f02020-03-06 17:36:05 +00001689 return true;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001690}
1691
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001692FstabEntry* fs_mgr_get_mounted_entry_for_userdata(Fstab* fstab,
1693 const std::string& data_block_device) {
Nikita Ioffe17824f02020-03-06 17:36:05 +00001694 std::vector<std::string> dm_stack;
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001695 if (!UnwindDmDeviceStack(data_block_device, &dm_stack)) {
1696 LERROR << "Failed to unwind dm-device stack for " << data_block_device;
Nikita Ioffe17824f02020-03-06 17:36:05 +00001697 return nullptr;
1698 }
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001699 for (auto& entry : *fstab) {
1700 if (entry.mount_point != "/data") {
1701 continue;
1702 }
1703 std::string block_device;
Nikita Ioffe17824f02020-03-06 17:36:05 +00001704 if (entry.fs_mgr_flags.logical) {
1705 if (!fs_mgr_update_logical_partition(&entry)) {
1706 LERROR << "Failed to update logic partition " << entry.blk_device;
1707 continue;
1708 }
1709 block_device = entry.blk_device;
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001710 } else if (!Realpath(entry.blk_device, &block_device)) {
1711 PWARNING << "Failed to realpath " << entry.blk_device;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001712 block_device = entry.blk_device;
1713 }
Nikita Ioffe17824f02020-03-06 17:36:05 +00001714 if (std::find(dm_stack.begin(), dm_stack.end(), block_device) != dm_stack.end()) {
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001715 return &entry;
1716 }
1717 }
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001718 LERROR << "Didn't find entry that was used to mount /data onto " << data_block_device;
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001719 return nullptr;
1720}
1721
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001722// TODO(b/143970043): return different error codes based on which step failed.
Nikita Ioffe12a36072019-10-23 20:11:32 +01001723int fs_mgr_remount_userdata_into_checkpointing(Fstab* fstab) {
Nikita Ioffe0dda4232019-12-16 23:22:55 +00001724 Fstab proc_mounts;
1725 if (!ReadFstabFromFile("/proc/mounts", &proc_mounts)) {
1726 LERROR << "Can't read /proc/mounts";
1727 return -1;
1728 }
Nikita Ioffe30b0c012020-03-06 15:55:20 +00001729 auto mounted_entry = GetEntryForMountPoint(&proc_mounts, "/data");
1730 if (mounted_entry == nullptr) {
Nikita Ioffed572c802019-12-09 21:13:08 +00001731 LERROR << "/data is not mounted";
1732 return -1;
1733 }
Nikita Ioffe7aa37f12020-04-06 23:28:40 +01001734 std::string block_device;
1735 if (!Realpath(mounted_entry->blk_device, &block_device)) {
1736 PERROR << "Failed to realpath " << mounted_entry->blk_device;
1737 return -1;
1738 }
1739 auto fstab_entry = fs_mgr_get_mounted_entry_for_userdata(fstab, block_device);
Nikita Ioffed572c802019-12-09 21:13:08 +00001740 if (fstab_entry == nullptr) {
Nikita Ioffe12a36072019-10-23 20:11:32 +01001741 LERROR << "Can't find /data in fstab";
1742 return -1;
1743 }
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001744 bool force_umount = GetBoolProperty("sys.init.userdata_remount.force_umount", false);
1745 if (force_umount) {
1746 LINFO << "Will force an umount of userdata even if it's not required";
1747 }
1748 if (!force_umount && !SupportsCheckpoint(fstab_entry)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +01001749 LINFO << "Userdata doesn't support checkpointing. Nothing to do";
1750 return 0;
1751 }
1752 CheckpointManager checkpoint_manager;
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001753 if (!force_umount && !checkpoint_manager.NeedsCheckpoint()) {
Nikita Ioffe12a36072019-10-23 20:11:32 +01001754 LINFO << "Checkpointing not needed. Don't remount";
1755 return 0;
1756 }
Nikita Ioffecb0c92e2020-01-10 17:34:59 +00001757 if (!force_umount && fstab_entry->fs_mgr_flags.checkpoint_fs) {
Nikita Ioffe12a36072019-10-23 20:11:32 +01001758 // Userdata is f2fs, simply remount it.
Nikita Ioffed572c802019-12-09 21:13:08 +00001759 if (!checkpoint_manager.Update(fstab_entry)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +01001760 LERROR << "Failed to remount userdata in checkpointing mode";
1761 return -1;
1762 }
Nikita Ioffed572c802019-12-09 21:13:08 +00001763 if (mount(block_device.c_str(), fstab_entry->mount_point.c_str(), "none",
1764 MS_REMOUNT | fstab_entry->flags, fstab_entry->fs_options.c_str()) != 0) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001765 PERROR << "Failed to remount userdata in checkpointing mode";
Nikita Ioffe12a36072019-10-23 20:11:32 +01001766 return -1;
1767 }
1768 } else {
Nikita Ioffed572c802019-12-09 21:13:08 +00001769 LINFO << "Unmounting /data before remounting into checkpointing mode";
Nikita Ioffe3d6a5fc2019-12-19 21:18:42 +00001770 if (!fs_mgr_unmount_all_data_mounts(block_device)) {
1771 LERROR << "Failed to umount /data";
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001772 return -1;
1773 }
1774 DeviceMapper& dm = DeviceMapper::Instance();
Nikita Ioffed572c802019-12-09 21:13:08 +00001775 while (dm.IsDmBlockDevice(block_device)) {
1776 auto next_device = dm.GetParentBlockDeviceByPath(block_device);
1777 auto name = dm.GetDmDeviceNameByPath(block_device);
1778 if (!name) {
1779 LERROR << "Failed to get dm-name for " << block_device;
1780 return -1;
1781 }
1782 LINFO << "Deleting " << block_device << " named " << *name;
1783 if (!dm.DeleteDevice(*name, 3s)) {
1784 return -1;
1785 }
1786 if (!next_device) {
1787 LERROR << "Failed to find parent device for " << block_device;
1788 }
1789 block_device = *next_device;
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001790 }
Nikita Ioffed572c802019-12-09 21:13:08 +00001791 LINFO << "Remounting /data";
Nikita Ioffebee7b8c2019-12-02 11:51:39 +00001792 // TODO(b/143970043): remove this hack after fs_mgr_mount_all is refactored.
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +01001793 auto result = fs_mgr_mount_all(fstab, MOUNT_MODE_ONLY_USERDATA);
1794 return result.code == FS_MGR_MNTALL_FAIL ? -1 : 0;
Nikita Ioffe12a36072019-10-23 20:11:32 +01001795 }
1796 return 0;
1797}
1798
Tom Cherry23319eb2018-11-30 16:16:05 -08001799// wrapper to __mount() and expects a fully prepared fstab_rec,
1800// unlike fs_mgr_do_mount which does more things with avb / verity etc.
Tom Cherrya7f1a9f2020-11-19 11:39:39 -08001801int fs_mgr_do_mount_one(const FstabEntry& entry, const std::string& alt_mount_point) {
Will Shiu589b7df2020-01-03 16:05:00 +08001802 // First check the filesystem if requested.
1803 if (entry.fs_mgr_flags.wait && !WaitForFile(entry.blk_device, 20s)) {
1804 LERROR << "Skipping mounting '" << entry.blk_device << "'";
1805 }
1806
Tom Cherrya7f1a9f2020-11-19 11:39:39 -08001807 auto& mount_point = alt_mount_point.empty() ? entry.mount_point : alt_mount_point;
Tom Cherry81ae0752018-07-30 16:23:49 -07001808
Tom Cherrya7f1a9f2020-11-19 11:39:39 -08001809 // Run fsck if needed
1810 prepare_fs_for_mount(entry.blk_device, entry, mount_point);
1811
1812 int ret = __mount(entry.blk_device, mount_point, entry);
Sandeep Patil56f9ada2017-02-14 14:00:14 -08001813 if (ret) {
1814 ret = (errno == EBUSY) ? FS_MGR_DOMNT_BUSY : FS_MGR_DOMNT_FAILED;
1815 }
1816
1817 return ret;
1818}
1819
Tom Cherry23319eb2018-11-30 16:16:05 -08001820// If tmp_mount_point is non-null, mount the filesystem there. This is for the
1821// tmp mount we do to check the user password
1822// If multiple fstab entries are to be mounted on "n_name", it will try to mount each one
1823// in turn, and stop on 1st success, or no more match.
1824static int fs_mgr_do_mount_helper(Fstab* fstab, const std::string& n_name,
1825 const std::string& n_blk_device, const char* tmp_mount_point,
Paul Lawrence20553642020-06-12 07:32:23 -07001826 int needs_checkpoint, bool metadata_encrypted) {
JP Abgrall5c01dac2014-06-18 14:54:37 -07001827 int mount_errors = 0;
1828 int first_mount_errno = 0;
Tom Cherry23319eb2018-11-30 16:16:05 -08001829 std::string mount_point;
Paul Lawrence20553642020-06-12 07:32:23 -07001830 CheckpointManager checkpoint_manager(needs_checkpoint, metadata_encrypted);
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001831 AvbUniquePtr avb_handle(nullptr);
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001832
Ken Sumrallab6b8522013-02-13 12:58:40 -08001833 if (!fstab) {
Bowgo Tsai359bed32017-04-27 15:44:39 +08001834 return FS_MGR_DOMNT_FAILED;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001835 }
1836
Tom Cherry23319eb2018-11-30 16:16:05 -08001837 for (auto& fstab_entry : *fstab) {
1838 if (!fs_match(fstab_entry.mount_point, n_name)) {
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001839 continue;
1840 }
1841
Tom Cherry23319eb2018-11-30 16:16:05 -08001842 // We found our match.
1843 // If this swap or a raw partition, report an error.
1844 if (fstab_entry.fs_type == "swap" || fstab_entry.fs_type == "emmc" ||
1845 fstab_entry.fs_type == "mtd") {
1846 LERROR << "Cannot mount filesystem of type " << fstab_entry.fs_type << " on "
1847 << n_blk_device;
Bowgo Tsai359bed32017-04-27 15:44:39 +08001848 return FS_MGR_DOMNT_FAILED;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001849 }
1850
Tom Cherry23319eb2018-11-30 16:16:05 -08001851 if (fstab_entry.fs_mgr_flags.logical) {
1852 if (!fs_mgr_update_logical_partition(&fstab_entry)) {
David Anderson62e5b202018-05-01 17:09:17 -07001853 LERROR << "Could not set up logical partition, skipping!";
1854 continue;
1855 }
1856 }
1857
David Anderson671bd812020-01-24 19:19:27 -08001858 WrapUserdataIfNeeded(&fstab_entry, n_blk_device);
1859
Paul Lawrence323959e2019-06-25 14:36:52 -07001860 if (!checkpoint_manager.Update(&fstab_entry, n_blk_device)) {
Paul Lawrenceb920cb42018-10-04 08:37:17 -07001861 LERROR << "Could not set up checkpoint partition, skipping!";
1862 continue;
Daniel Rosenberg4c93b252018-08-28 01:41:18 -07001863 }
1864
Tom Cherry23319eb2018-11-30 16:16:05 -08001865 // First check the filesystem if requested.
David Anderson5c475c72019-06-11 17:40:49 -07001866 if (fstab_entry.fs_mgr_flags.wait && !WaitForFile(n_blk_device, 20s)) {
Jinguang Dong9d344962017-06-13 10:20:34 +08001867 LERROR << "Skipping mounting '" << n_blk_device << "'";
1868 continue;
Ken Sumrallab6b8522013-02-13 12:58:40 -08001869 }
1870
Tom Cherrya7f1a9f2020-11-19 11:39:39 -08001871 // Now mount it where requested */
1872 if (tmp_mount_point) {
1873 mount_point = tmp_mount_point;
1874 } else {
1875 mount_point = fstab_entry.mount_point;
1876 }
1877
1878 int fs_stat = prepare_fs_for_mount(n_blk_device, fstab_entry, mount_point);
liminghao9a0fd1d2016-07-22 11:48:14 +08001879
Tom Cherry23319eb2018-11-30 16:16:05 -08001880 if (fstab_entry.fs_mgr_flags.avb) {
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001881 if (!avb_handle) {
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001882 avb_handle = AvbHandle::Open();
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001883 if (!avb_handle) {
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001884 LERROR << "Failed to open AvbHandle";
Bowgo Tsai359bed32017-04-27 15:44:39 +08001885 return FS_MGR_DOMNT_FAILED;
Bowgo Tsai95c966a2017-03-30 18:42:54 +08001886 }
1887 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001888 if (avb_handle->SetUpAvbHashtree(&fstab_entry, true /* wait_for_verity_dev */) ==
Bowgo Tsaic1bc2812018-11-26 17:49:23 +08001889 AvbHashtreeResult::kFail) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001890 LERROR << "Failed to set up AVB on partition: " << fstab_entry.mount_point
1891 << ", skipping!";
1892 // Skips mounting the device.
bowgotsaib51722b2017-01-11 22:21:38 +08001893 continue;
1894 }
Bowgo Tsaif3e28e12019-02-20 21:53:47 +08001895 } else if (!fstab_entry.avb_keys.empty()) {
Bowgo Tsaidefe1cb2019-01-25 12:07:09 +08001896 if (AvbHandle::SetUpStandaloneAvbHashtree(&fstab_entry) == AvbHashtreeResult::kFail) {
1897 LERROR << "Failed to set up AVB on standalone partition: "
1898 << fstab_entry.mount_point << ", skipping!";
1899 // Skips mounting the device.
1900 continue;
1901 }
Geremy Condra3ad3d1c2013-02-22 18:11:41 -08001902 }
1903
Keun-young Park40db04d2017-04-13 17:31:08 -07001904 int retry_count = 2;
1905 while (retry_count-- > 0) {
Tom Cherry23319eb2018-11-30 16:16:05 -08001906 if (!__mount(n_blk_device, mount_point, fstab_entry)) {
Keun-young Park40db04d2017-04-13 17:31:08 -07001907 fs_stat &= ~FS_STAT_FULL_MOUNT_FAILED;
Bowgo Tsai359bed32017-04-27 15:44:39 +08001908 return FS_MGR_DOMNT_SUCCESS;
Keun-young Park40db04d2017-04-13 17:31:08 -07001909 } else {
1910 if (retry_count <= 0) break; // run check_fs only once
1911 if (!first_mount_errno) first_mount_errno = errno;
1912 mount_errors++;
1913 fs_stat |= FS_STAT_FULL_MOUNT_FAILED;
1914 // try again after fsck
Tom Cherrya7f1a9f2020-11-19 11:39:39 -08001915 check_fs(n_blk_device, fstab_entry.fs_type, mount_point, &fs_stat);
Keun-young Park40db04d2017-04-13 17:31:08 -07001916 }
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001917 }
Tom Cherry23319eb2018-11-30 16:16:05 -08001918 log_fs_stat(fstab_entry.blk_device, fs_stat);
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001919 }
Bowgo Tsai359bed32017-04-27 15:44:39 +08001920
1921 // Reach here means the mount attempt fails.
JP Abgrall5c01dac2014-06-18 14:54:37 -07001922 if (mount_errors) {
Bowgo Tsai359bed32017-04-27 15:44:39 +08001923 PERROR << "Cannot mount filesystem on " << n_blk_device << " at " << mount_point;
1924 if (first_mount_errno == EBUSY) return FS_MGR_DOMNT_BUSY;
JP Abgrall5c01dac2014-06-18 14:54:37 -07001925 } else {
Tom Cherry23319eb2018-11-30 16:16:05 -08001926 // We didn't find a match, say so and return an error.
Bowgo Tsai359bed32017-04-27 15:44:39 +08001927 LERROR << "Cannot find mount point " << n_name << " in fstab";
JP Abgrall5c01dac2014-06-18 14:54:37 -07001928 }
Bowgo Tsai359bed32017-04-27 15:44:39 +08001929 return FS_MGR_DOMNT_FAILED;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001930}
1931
Tom Cherry2e545f82019-01-29 08:49:57 -08001932int 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 -07001933 return fs_mgr_do_mount_helper(fstab, n_name, n_blk_device, tmp_mount_point, -1, false);
Tom Cherry2e545f82019-01-29 08:49:57 -08001934}
1935
1936int 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 -07001937 bool needs_checkpoint, bool metadata_encrypted) {
1938 return fs_mgr_do_mount_helper(fstab, n_name, n_blk_device, tmp_mount_point, needs_checkpoint,
1939 metadata_encrypted);
Tom Cherry2e545f82019-01-29 08:49:57 -08001940}
1941
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001942/*
1943 * mount a tmpfs filesystem at the given point.
1944 * return 0 on success, non-zero on failure.
1945 */
Wei Wang4d71bc52017-02-24 17:41:38 -08001946int fs_mgr_do_tmpfs_mount(const char *n_name)
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001947{
1948 int ret;
1949
Luis Hector Chavezf29b39d2017-07-10 15:25:55 -07001950 ret = mount("tmpfs", n_name, "tmpfs", MS_NOATIME | MS_NOSUID | MS_NODEV | MS_NOEXEC,
1951 CRYPTO_TMPFS_OPTIONS);
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001952 if (ret < 0) {
bowgotsai47878de2017-01-23 14:04:34 +08001953 LERROR << "Cannot mount tmpfs filesystem at " << n_name;
Ken Sumrallc1bf8962012-01-06 19:09:42 -08001954 return -1;
1955 }
1956
1957 /* Success */
1958 return 0;
1959}
1960
Bart Van Asscheec5f6352021-07-29 13:50:43 -07001961static bool ConfigureIoScheduler(const std::string& device_path) {
1962 if (!StartsWith(device_path, "/dev/")) {
1963 LERROR << __func__ << ": invalid argument " << device_path;
1964 return false;
1965 }
1966
1967 const std::string iosched_path =
1968 StringPrintf("/sys/block/%s/queue/scheduler", Basename(device_path).c_str());
1969 unique_fd iosched_fd(open(iosched_path.c_str(), O_RDWR | O_CLOEXEC));
1970 if (iosched_fd.get() == -1) {
1971 PERROR << __func__ << ": failed to open " << iosched_path;
1972 return false;
1973 }
1974
1975 // Kernels before v4.1 only support 'noop'. Kernels [v4.1, v5.0) support
1976 // 'noop' and 'none'. Kernels v5.0 and later only support 'none'.
1977 static constexpr const std::array<std::string_view, 2> kNoScheduler = {"none", "noop"};
1978
1979 for (const std::string_view& scheduler : kNoScheduler) {
1980 int ret = write(iosched_fd.get(), scheduler.data(), scheduler.size());
1981 if (ret > 0) {
1982 return true;
1983 }
1984 }
1985
1986 PERROR << __func__ << ": failed to write to " << iosched_path;
1987 return false;
1988}
1989
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08001990static bool InstallZramDevice(const std::string& device) {
1991 if (!android::base::WriteStringToFile(device, ZRAM_BACK_DEV)) {
1992 PERROR << "Cannot write " << device << " in: " << ZRAM_BACK_DEV;
1993 return false;
1994 }
1995 LINFO << "Success to set " << device << " to " << ZRAM_BACK_DEV;
1996 return true;
1997}
1998
Minchan Kim12e96152019-10-15 14:41:18 -07001999static bool PrepareZramBackingDevice(off64_t size) {
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002000
Minchan Kim12e96152019-10-15 14:41:18 -07002001 constexpr const char* file_path = "/data/per_boot/zram_swap";
2002 if (size == 0) return true;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002003
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002004 // Prepare target path
Minchan Kim12e96152019-10-15 14:41:18 -07002005 unique_fd target_fd(TEMP_FAILURE_RETRY(open(file_path, O_RDWR | O_CREAT | O_CLOEXEC, 0600)));
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002006 if (target_fd.get() == -1) {
Minchan Kim12e96152019-10-15 14:41:18 -07002007 PERROR << "Cannot open target path: " << file_path;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002008 return false;
2009 }
2010 if (fallocate(target_fd.get(), 0, 0, size) < 0) {
Minchan Kim12e96152019-10-15 14:41:18 -07002011 PERROR << "Cannot truncate target path: " << file_path;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002012 return false;
2013 }
2014
Nikita Ioffebcaeb702020-04-20 17:38:17 +01002015 // Allocate loop device and attach it to file_path.
2016 LoopControl loop_control;
Bart Van Assche06b95de2021-07-29 13:53:53 -07002017 std::string loop_device;
2018 if (!loop_control.Attach(target_fd.get(), 5s, &loop_device)) {
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002019 return false;
2020 }
2021
Bart Van Asscheec5f6352021-07-29 13:50:43 -07002022 ConfigureIoScheduler(loop_device);
2023
Bart Van Assche0223cd82021-08-06 10:21:12 -07002024 ConfigureQueueDepth(loop_device, "/");
2025
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002026 // set block size & direct IO
Bart Van Assche06b95de2021-07-29 13:53:53 -07002027 unique_fd loop_fd(TEMP_FAILURE_RETRY(open(loop_device.c_str(), O_RDWR | O_CLOEXEC)));
2028 if (loop_fd.get() == -1) {
2029 PERROR << "Cannot open " << loop_device;
Nikita Ioffebcaeb702020-04-20 17:38:17 +01002030 return false;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002031 }
Liangcai Fand884ba52021-09-06 17:56:18 +08002032 if (!LoopControl::SetAutoClearStatus(loop_fd.get())) {
2033 PERROR << "Failed set LO_FLAGS_AUTOCLEAR for " << loop_device;
2034 }
Bart Van Assche06b95de2021-07-29 13:53:53 -07002035 if (!LoopControl::EnableDirectIo(loop_fd.get())) {
Nikita Ioffebcaeb702020-04-20 17:38:17 +01002036 return false;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002037 }
2038
Bart Van Assche06b95de2021-07-29 13:53:53 -07002039 return InstallZramDevice(loop_device);
Jaegeuk Kim2aedc822018-11-20 13:27:06 -08002040}
2041
Tom Cherry30554572018-11-30 15:21:04 -08002042bool fs_mgr_swapon_all(const Fstab& fstab) {
2043 bool ret = true;
2044 for (const auto& entry : fstab) {
2045 // Skip non-swap entries.
2046 if (entry.fs_type != "swap") {
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002047 continue;
2048 }
2049
Tom Cherry30554572018-11-30 15:21:04 -08002050 if (entry.zram_size > 0) {
JeongHyeon Leec159edc2021-06-24 11:21:08 +09002051 if (!PrepareZramBackingDevice(entry.zram_backingdev_size)) {
Minchan Kim12e96152019-10-15 14:41:18 -07002052 LERROR << "Failure of zram backing device file for '" << entry.blk_device << "'";
2053 }
Tom Cherry30554572018-11-30 15:21:04 -08002054 // A zram_size was specified, so we need to configure the
2055 // device. There is no point in having multiple zram devices
2056 // on a system (all the memory comes from the same pool) so
2057 // we can assume the device number is 0.
2058 if (entry.max_comp_streams >= 0) {
Tom Cherryf274e782018-10-03 13:13:41 -07002059 auto zram_mcs_fp = std::unique_ptr<FILE, decltype(&fclose)>{
2060 fopen(ZRAM_CONF_MCS, "re"), fclose};
Tom Cherry30554572018-11-30 15:21:04 -08002061 if (zram_mcs_fp == nullptr) {
Tom Cherryf274e782018-10-03 13:13:41 -07002062 LERROR << "Unable to open zram conf comp device " << ZRAM_CONF_MCS;
Tom Cherry30554572018-11-30 15:21:04 -08002063 ret = false;
Tom Cherryf274e782018-10-03 13:13:41 -07002064 continue;
2065 }
Tom Cherry30554572018-11-30 15:21:04 -08002066 fprintf(zram_mcs_fp.get(), "%d\n", entry.max_comp_streams);
Peter Enderborg4d217f02016-08-26 15:09:35 +02002067 }
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002068
Tom Cherryf274e782018-10-03 13:13:41 -07002069 auto zram_fp =
2070 std::unique_ptr<FILE, decltype(&fclose)>{fopen(ZRAM_CONF_DEV, "re+"), fclose};
Tom Cherry30554572018-11-30 15:21:04 -08002071 if (zram_fp == nullptr) {
bowgotsai47878de2017-01-23 14:04:34 +08002072 LERROR << "Unable to open zram conf device " << ZRAM_CONF_DEV;
Tom Cherry30554572018-11-30 15:21:04 -08002073 ret = false;
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002074 continue;
2075 }
Tom Cherry30554572018-11-30 15:21:04 -08002076 fprintf(zram_fp.get(), "%" PRId64 "\n", entry.zram_size);
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002077 }
2078
David Anderson5c475c72019-06-11 17:40:49 -07002079 if (entry.fs_mgr_flags.wait && !WaitForFile(entry.blk_device, 20s)) {
Tom Cherry30554572018-11-30 15:21:04 -08002080 LERROR << "Skipping mkswap for '" << entry.blk_device << "'";
2081 ret = false;
Jinguang Dong9d344962017-06-13 10:20:34 +08002082 continue;
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002083 }
2084
Tom Cherry30554572018-11-30 15:21:04 -08002085 // Initialize the swap area.
2086 const char* mkswap_argv[2] = {
2087 MKSWAP_BIN,
2088 entry.blk_device.c_str(),
2089 };
Tom Cherry3a803eb2019-09-25 16:23:50 -07002090 int err = logwrap_fork_execvp(ARRAY_SIZE(mkswap_argv), mkswap_argv, nullptr, false,
2091 LOG_KLOG, false, nullptr);
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002092 if (err) {
Tom Cherry30554572018-11-30 15:21:04 -08002093 LERROR << "mkswap failed for " << entry.blk_device;
2094 ret = false;
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002095 continue;
2096 }
2097
2098 /* If -1, then no priority was specified in fstab, so don't set
2099 * SWAP_FLAG_PREFER or encode the priority */
Tom Cherry30554572018-11-30 15:21:04 -08002100 int flags = 0;
2101 if (entry.swap_prio >= 0) {
2102 flags = (entry.swap_prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK;
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002103 flags |= SWAP_FLAG_PREFER;
2104 } else {
2105 flags = 0;
2106 }
Tom Cherry30554572018-11-30 15:21:04 -08002107 err = swapon(entry.blk_device.c_str(), flags);
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002108 if (err) {
Tom Cherry30554572018-11-30 15:21:04 -08002109 LERROR << "swapon failed for " << entry.blk_device;
2110 ret = false;
Ken Sumrall5bc31a22013-07-08 19:11:55 -07002111 }
2112 }
2113
2114 return ret;
2115}
2116
Tom Cherrycf80b6d2019-01-07 14:25:31 -08002117bool fs_mgr_is_verity_enabled(const FstabEntry& entry) {
David Anderson6cdd9bd2021-10-29 16:13:22 -07002118 if (!entry.fs_mgr_flags.avb) {
Bowgo Tsaiaaf70e72017-03-02 00:03:56 +08002119 return false;
2120 }
2121
David Anderson40b59482018-06-25 17:55:01 -07002122 DeviceMapper& dm = DeviceMapper::Instance();
2123
David Anderson7082f682019-03-18 19:17:11 -07002124 std::string mount_point = GetVerityDeviceName(entry);
Tom Cherrycf80b6d2019-01-07 14:25:31 -08002125 if (dm.GetState(mount_point) == DmDeviceState::INVALID) {
2126 return false;
2127 }
2128
Tom Cherrycf80b6d2019-01-07 14:25:31 -08002129 std::vector<DeviceMapper::TargetInfo> table;
2130 if (!dm.GetTableStatus(mount_point, &table) || table.empty() || table[0].data.empty()) {
David Anderson6cdd9bd2021-10-29 16:13:22 -07002131 return false;
Tom Cherrycf80b6d2019-01-07 14:25:31 -08002132 }
2133
David Anderson6cdd9bd2021-10-29 16:13:22 -07002134 auto status = table[0].data.c_str();
Tom Cherrycf80b6d2019-01-07 14:25:31 -08002135 if (*status == 'C' || *status == 'V') {
2136 return true;
2137 }
2138
2139 return false;
Bowgo Tsaiaaf70e72017-03-02 00:03:56 +08002140}
David Anderson5cbd2e42018-09-27 10:53:04 -07002141
Tianjie10bec652021-08-30 16:10:09 -07002142std::optional<HashtreeInfo> fs_mgr_get_hashtree_info(const android::fs_mgr::FstabEntry& entry) {
David Anderson6cdd9bd2021-10-29 16:13:22 -07002143 if (!entry.fs_mgr_flags.avb) {
Tianjie10bec652021-08-30 16:10:09 -07002144 return {};
Tianjie327237d2021-01-20 19:02:34 -08002145 }
2146 DeviceMapper& dm = DeviceMapper::Instance();
2147 std::string device = GetVerityDeviceName(entry);
2148
2149 std::vector<DeviceMapper::TargetInfo> table;
2150 if (dm.GetState(device) == DmDeviceState::INVALID || !dm.GetTableInfo(device, &table)) {
Tianjie10bec652021-08-30 16:10:09 -07002151 return {};
Tianjie327237d2021-01-20 19:02:34 -08002152 }
2153 for (const auto& target : table) {
2154 if (strcmp(target.spec.target_type, "verity") != 0) {
2155 continue;
2156 }
2157
2158 // The format is stable for dm-verity version 0 & 1. And the data is expected to have
2159 // the fixed format:
2160 // <version> <dev> <hash_dev> <data_block_size> <hash_block_size> <num_data_blocks>
2161 // <hash_start_block> <algorithm> <digest> <salt>
2162 // Details in https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/verity.html
2163
2164 std::vector<std::string> tokens = android::base::Split(target.data, " \t\r\n");
2165 if (tokens[0] != "0" && tokens[0] != "1") {
2166 LOG(WARNING) << "Unrecognized device mapper version in " << target.data;
Tianjie10bec652021-08-30 16:10:09 -07002167 return {};
Tianjie327237d2021-01-20 19:02:34 -08002168 }
2169
Tianjie10bec652021-08-30 16:10:09 -07002170 // Hashtree algorithm & root digest are the 8th & 9th token in the output.
2171 return HashtreeInfo{.algorithm = android::base::Trim(tokens[7]),
2172 .root_digest = android::base::Trim(tokens[8])};
Tianjie327237d2021-01-20 19:02:34 -08002173 }
2174
Tianjie10bec652021-08-30 16:10:09 -07002175 return {};
Tianjie327237d2021-01-20 19:02:34 -08002176}
2177
David Andersonee725f62019-03-13 19:10:48 -07002178bool fs_mgr_verity_is_check_at_most_once(const android::fs_mgr::FstabEntry& entry) {
David Anderson6cdd9bd2021-10-29 16:13:22 -07002179 if (!entry.fs_mgr_flags.avb) {
David Andersonee725f62019-03-13 19:10:48 -07002180 return false;
2181 }
2182
2183 DeviceMapper& dm = DeviceMapper::Instance();
David Anderson7082f682019-03-18 19:17:11 -07002184 std::string device = GetVerityDeviceName(entry);
David Andersonee725f62019-03-13 19:10:48 -07002185
2186 std::vector<DeviceMapper::TargetInfo> table;
2187 if (dm.GetState(device) == DmDeviceState::INVALID || !dm.GetTableInfo(device, &table)) {
2188 return false;
2189 }
2190 for (const auto& target : table) {
2191 if (strcmp(target.spec.target_type, "verity") == 0 &&
2192 target.data.find("check_at_most_once") != std::string::npos) {
2193 return true;
2194 }
2195 }
2196 return false;
2197}
2198
David Anderson0bfa1c82018-10-30 15:06:46 -07002199std::string fs_mgr_get_super_partition_name(int slot) {
2200 // Devices upgrading to dynamic partitions are allowed to specify a super
David Anderson0b0ee7a2019-04-18 14:14:33 -07002201 // partition name. This includes cuttlefish, which is a non-A/B device.
David Anderson0bfa1c82018-10-30 15:06:46 -07002202 std::string super_partition;
Devin Moore20b74252021-03-04 08:23:31 -08002203 if (fs_mgr_get_boot_config_from_bootconfig_source("super_partition", &super_partition) ||
2204 fs_mgr_get_boot_config_from_kernel_cmdline("super_partition", &super_partition)) {
David Anderson0b0ee7a2019-04-18 14:14:33 -07002205 if (fs_mgr_get_slot_suffix().empty()) {
2206 return super_partition;
2207 }
David Anderson0bfa1c82018-10-30 15:06:46 -07002208 std::string suffix;
2209 if (slot == 0) {
2210 suffix = "_a";
2211 } else if (slot == 1) {
2212 suffix = "_b";
2213 } else if (slot == -1) {
2214 suffix = fs_mgr_get_slot_suffix();
2215 }
David Anderson0bfa1c82018-10-30 15:06:46 -07002216 return super_partition + suffix;
2217 }
David Anderson5cbd2e42018-09-27 10:53:04 -07002218 return LP_METADATA_DEFAULT_PARTITION_NAME;
2219}
Yi-Yo Chiang23816e82021-05-19 17:19:58 +08002220
Yi-Yo Chiang3431d522021-05-27 22:29:32 +08002221bool fs_mgr_create_canonical_mount_point(const std::string& mount_point) {
2222 auto saved_errno = errno;
2223 auto ok = true;
2224 auto created_mount_point = !mkdir(mount_point.c_str(), 0755);
2225 std::string real_mount_point;
2226 if (!Realpath(mount_point, &real_mount_point)) {
2227 ok = false;
2228 PERROR << "failed to realpath(" << mount_point << ")";
2229 } else if (mount_point != real_mount_point) {
2230 ok = false;
2231 LERROR << "mount point is not canonical: realpath(" << mount_point << ") -> "
2232 << real_mount_point;
2233 }
2234 if (!ok && created_mount_point) {
2235 rmdir(mount_point.c_str());
2236 }
2237 errno = saved_errno;
2238 return ok;
2239}
2240
Yi-Yo Chiang23816e82021-05-19 17:19:58 +08002241bool fs_mgr_mount_overlayfs_fstab_entry(const FstabEntry& entry) {
2242 auto overlayfs_valid_result = fs_mgr_overlayfs_valid();
2243 if (overlayfs_valid_result == OverlayfsValidResult::kNotSupported) {
2244 LERROR << __FUNCTION__ << "(): kernel does not support overlayfs";
2245 return false;
2246 }
2247
2248#if ALLOW_ADBD_DISABLE_VERITY == 0
2249 // Allowlist the mount point if user build.
2250 static const std::vector<const std::string> kAllowedPaths = {
2251 "/odm", "/odm_dlkm", "/oem", "/product", "/system_ext", "/vendor", "/vendor_dlkm",
2252 };
2253 static const std::vector<const std::string> kAllowedPrefixes = {
2254 "/mnt/product/",
2255 "/mnt/vendor/",
2256 };
2257 if (std::none_of(kAllowedPaths.begin(), kAllowedPaths.end(),
2258 [&entry](const auto& path) -> bool {
2259 return entry.mount_point == path ||
2260 StartsWith(entry.mount_point, path + "/");
2261 }) &&
2262 std::none_of(kAllowedPrefixes.begin(), kAllowedPrefixes.end(),
2263 [&entry](const auto& prefix) -> bool {
2264 return entry.mount_point != prefix &&
2265 StartsWith(entry.mount_point, prefix);
2266 })) {
2267 LERROR << __FUNCTION__
2268 << "(): mount point is forbidden on user build: " << entry.mount_point;
2269 return false;
2270 }
2271#endif // ALLOW_ADBD_DISABLE_VERITY == 0
2272
Yi-Yo Chiang3431d522021-05-27 22:29:32 +08002273 if (!fs_mgr_create_canonical_mount_point(entry.mount_point)) {
Yi-Yo Chiang23816e82021-05-19 17:19:58 +08002274 return false;
2275 }
2276
Yi-Yo Chiange7783a92021-08-03 01:02:31 +08002277 auto lowerdir = entry.lowerdir;
2278 if (entry.fs_mgr_flags.overlayfs_remove_missing_lowerdir) {
2279 bool removed_any = false;
2280 std::vector<std::string> lowerdirs;
2281 for (const auto& dir : android::base::Split(entry.lowerdir, ":")) {
2282 if (access(dir.c_str(), F_OK)) {
2283 PWARNING << __FUNCTION__ << "(): remove missing lowerdir '" << dir << "'";
2284 removed_any = true;
2285 } else {
2286 lowerdirs.push_back(dir);
2287 }
2288 }
2289 if (removed_any) {
2290 lowerdir = android::base::Join(lowerdirs, ":");
2291 }
2292 }
2293
2294 auto options = "lowerdir=" + lowerdir;
Yi-Yo Chiang23816e82021-05-19 17:19:58 +08002295 if (overlayfs_valid_result == OverlayfsValidResult::kOverrideCredsRequired) {
2296 options += ",override_creds=off";
2297 }
2298
2299 // Use "overlay-" + entry.blk_device as the mount() source, so that adb-remout-test don't
2300 // confuse this with adb remount overlay, whose device name is "overlay".
2301 // Overlayfs is a pseudo filesystem, so the source device is a symbolic value and isn't used to
2302 // back the filesystem. However the device name would be shown in /proc/mounts.
2303 auto source = "overlay-" + entry.blk_device;
2304 auto report = "__mount(source=" + source + ",target=" + entry.mount_point + ",type=overlay," +
2305 options + ")=";
2306 auto ret = mount(source.c_str(), entry.mount_point.c_str(), "overlay", MS_RDONLY | MS_NOATIME,
2307 options.c_str());
2308 if (ret) {
2309 PERROR << report << ret;
2310 return false;
2311 }
2312 LINFO << report << ret;
2313 return true;
2314}
David Anderson6cdd9bd2021-10-29 16:13:22 -07002315
2316bool fs_mgr_load_verity_state(int* mode) {
2317 // unless otherwise specified, use EIO mode.
2318 *mode = VERITY_MODE_EIO;
2319
2320 // The bootloader communicates verity mode via the kernel commandline
2321 std::string verity_mode;
2322 if (!fs_mgr_get_boot_config("veritymode", &verity_mode)) {
2323 return false;
2324 }
2325
2326 if (verity_mode == "enforcing") {
2327 *mode = VERITY_MODE_DEFAULT;
2328 } else if (verity_mode == "logging") {
2329 *mode = VERITY_MODE_LOGGING;
2330 }
2331
2332 return true;
2333}