fs_mgr.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  1. /*
  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. #include "fs_mgr.h"
  17. #include <ctype.h>
  18. #include <dirent.h>
  19. #include <errno.h>
  20. #include <fcntl.h>
  21. #include <inttypes.h>
  22. #include <libgen.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <sys/ioctl.h>
  27. #include <sys/mount.h>
  28. #include <sys/stat.h>
  29. #include <sys/swap.h>
  30. #include <sys/types.h>
  31. #include <sys/wait.h>
  32. #include <time.h>
  33. #include <unistd.h>
  34. #include <functional>
  35. #include <map>
  36. #include <memory>
  37. #include <string>
  38. #include <thread>
  39. #include <utility>
  40. #include <vector>
  41. #include <android-base/file.h>
  42. #include <android-base/properties.h>
  43. #include <android-base/stringprintf.h>
  44. #include <android-base/strings.h>
  45. #include <android-base/unique_fd.h>
  46. #include <cutils/android_filesystem_config.h>
  47. #include <cutils/android_reboot.h>
  48. #include <cutils/partition_utils.h>
  49. #include <cutils/properties.h>
  50. #include <ext4_utils/ext4.h>
  51. #include <ext4_utils/ext4_sb.h>
  52. #include <ext4_utils/ext4_utils.h>
  53. #include <ext4_utils/wipe.h>
  54. #include <fs_avb/fs_avb.h>
  55. #include <fs_mgr_overlayfs.h>
  56. #include <libdm/dm.h>
  57. #include <liblp/metadata_format.h>
  58. #include <linux/fs.h>
  59. #include <linux/loop.h>
  60. #include <linux/magic.h>
  61. #include <log/log_properties.h>
  62. #include <logwrap/logwrap.h>
  63. #include "fs_mgr_priv.h"
  64. #define KEY_LOC_PROP "ro.crypto.keyfile.userdata"
  65. #define KEY_IN_FOOTER "footer"
  66. #define E2FSCK_BIN "/system/bin/e2fsck"
  67. #define F2FS_FSCK_BIN "/system/bin/fsck.f2fs"
  68. #define MKSWAP_BIN "/system/bin/mkswap"
  69. #define TUNE2FS_BIN "/system/bin/tune2fs"
  70. #define FSCK_LOG_FILE "/dev/fscklogs/log"
  71. #define ZRAM_CONF_DEV "/sys/block/zram0/disksize"
  72. #define ZRAM_CONF_MCS "/sys/block/zram0/max_comp_streams"
  73. #define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
  74. #define SYSFS_EXT4_VERITY "/sys/fs/ext4/features/verity"
  75. #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
  76. using android::base::Basename;
  77. using android::base::Realpath;
  78. using android::base::StartsWith;
  79. using android::base::unique_fd;
  80. using android::dm::DeviceMapper;
  81. using android::dm::DmDeviceState;
  82. // Realistically, this file should be part of the android::fs_mgr namespace;
  83. using namespace android::fs_mgr;
  84. using namespace std::literals;
  85. // record fs stat
  86. enum FsStatFlags {
  87. FS_STAT_IS_EXT4 = 0x0001,
  88. FS_STAT_NEW_IMAGE_VERSION = 0x0002,
  89. FS_STAT_E2FSCK_F_ALWAYS = 0x0004,
  90. FS_STAT_UNCLEAN_SHUTDOWN = 0x0008,
  91. FS_STAT_QUOTA_ENABLED = 0x0010,
  92. FS_STAT_RO_MOUNT_FAILED = 0x0040,
  93. FS_STAT_RO_UNMOUNT_FAILED = 0x0080,
  94. FS_STAT_FULL_MOUNT_FAILED = 0x0100,
  95. FS_STAT_E2FSCK_FAILED = 0x0200,
  96. FS_STAT_E2FSCK_FS_FIXED = 0x0400,
  97. FS_STAT_INVALID_MAGIC = 0x0800,
  98. FS_STAT_TOGGLE_QUOTAS_FAILED = 0x10000,
  99. FS_STAT_SET_RESERVED_BLOCKS_FAILED = 0x20000,
  100. FS_STAT_ENABLE_ENCRYPTION_FAILED = 0x40000,
  101. FS_STAT_ENABLE_VERITY_FAILED = 0x80000,
  102. };
  103. // TODO: switch to inotify()
  104. bool fs_mgr_wait_for_file(const std::string& filename,
  105. const std::chrono::milliseconds relative_timeout,
  106. FileWaitMode file_wait_mode) {
  107. auto start_time = std::chrono::steady_clock::now();
  108. while (true) {
  109. int rv = access(filename.c_str(), F_OK);
  110. if (file_wait_mode == FileWaitMode::Exists) {
  111. if (!rv || errno != ENOENT) return true;
  112. } else if (file_wait_mode == FileWaitMode::DoesNotExist) {
  113. if (rv && errno == ENOENT) return true;
  114. }
  115. std::this_thread::sleep_for(50ms);
  116. auto now = std::chrono::steady_clock::now();
  117. auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
  118. if (time_elapsed > relative_timeout) return false;
  119. }
  120. }
  121. static void log_fs_stat(const std::string& blk_device, int fs_stat) {
  122. if ((fs_stat & FS_STAT_IS_EXT4) == 0) return; // only log ext4
  123. std::string msg =
  124. android::base::StringPrintf("\nfs_stat,%s,0x%x\n", blk_device.c_str(), fs_stat);
  125. android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(FSCK_LOG_FILE, O_WRONLY | O_CLOEXEC |
  126. O_APPEND | O_CREAT, 0664)));
  127. if (fd == -1 || !android::base::WriteStringToFd(msg, fd)) {
  128. LWARNING << __FUNCTION__ << "() cannot log " << msg;
  129. }
  130. }
  131. static bool is_extfs(const std::string& fs_type) {
  132. return fs_type == "ext4" || fs_type == "ext3" || fs_type == "ext2";
  133. }
  134. static bool is_f2fs(const std::string& fs_type) {
  135. return fs_type == "f2fs";
  136. }
  137. static std::string realpath(const std::string& blk_device) {
  138. std::string real_path;
  139. if (!Realpath(blk_device, &real_path)) {
  140. real_path = blk_device;
  141. }
  142. return real_path;
  143. }
  144. static bool should_force_check(int fs_stat) {
  145. return fs_stat &
  146. (FS_STAT_E2FSCK_F_ALWAYS | FS_STAT_UNCLEAN_SHUTDOWN | FS_STAT_QUOTA_ENABLED |
  147. FS_STAT_RO_MOUNT_FAILED | FS_STAT_RO_UNMOUNT_FAILED | FS_STAT_FULL_MOUNT_FAILED |
  148. FS_STAT_E2FSCK_FAILED | FS_STAT_TOGGLE_QUOTAS_FAILED |
  149. FS_STAT_SET_RESERVED_BLOCKS_FAILED | FS_STAT_ENABLE_ENCRYPTION_FAILED);
  150. }
  151. static void check_fs(const std::string& blk_device, const std::string& fs_type,
  152. const std::string& target, int* fs_stat) {
  153. int status;
  154. int ret;
  155. long tmpmnt_flags = MS_NOATIME | MS_NOEXEC | MS_NOSUID;
  156. auto tmpmnt_opts = "errors=remount-ro"s;
  157. const char* e2fsck_argv[] = {E2FSCK_BIN, "-y", blk_device.c_str()};
  158. const char* e2fsck_forced_argv[] = {E2FSCK_BIN, "-f", "-y", blk_device.c_str()};
  159. if (*fs_stat & FS_STAT_INVALID_MAGIC) { // will fail, so do not try
  160. return;
  161. }
  162. /* Check for the types of filesystems we know how to check */
  163. if (is_extfs(fs_type)) {
  164. /*
  165. * First try to mount and unmount the filesystem. We do this because
  166. * the kernel is more efficient than e2fsck in running the journal and
  167. * processing orphaned inodes, and on at least one device with a
  168. * performance issue in the emmc firmware, it can take e2fsck 2.5 minutes
  169. * to do what the kernel does in about a second.
  170. *
  171. * After mounting and unmounting the filesystem, run e2fsck, and if an
  172. * error is recorded in the filesystem superblock, e2fsck will do a full
  173. * check. Otherwise, it does nothing. If the kernel cannot mount the
  174. * filesytsem due to an error, e2fsck is still run to do a full check
  175. * fix the filesystem.
  176. */
  177. if (!(*fs_stat & FS_STAT_FULL_MOUNT_FAILED)) { // already tried if full mount failed
  178. errno = 0;
  179. if (fs_type == "ext4") {
  180. // This option is only valid with ext4
  181. tmpmnt_opts += ",nomblk_io_submit";
  182. }
  183. ret = mount(blk_device.c_str(), target.c_str(), fs_type.c_str(), tmpmnt_flags,
  184. tmpmnt_opts.c_str());
  185. PINFO << __FUNCTION__ << "(): mount(" << blk_device << "," << target << "," << fs_type
  186. << ")=" << ret;
  187. if (!ret) {
  188. bool umounted = false;
  189. int retry_count = 5;
  190. while (retry_count-- > 0) {
  191. umounted = umount(target.c_str()) == 0;
  192. if (umounted) {
  193. LINFO << __FUNCTION__ << "(): unmount(" << target << ") succeeded";
  194. break;
  195. }
  196. PERROR << __FUNCTION__ << "(): umount(" << target << ") failed";
  197. if (retry_count) sleep(1);
  198. }
  199. if (!umounted) {
  200. // boot may fail but continue and leave it to later stage for now.
  201. PERROR << __FUNCTION__ << "(): umount(" << target << ") timed out";
  202. *fs_stat |= FS_STAT_RO_UNMOUNT_FAILED;
  203. }
  204. } else {
  205. *fs_stat |= FS_STAT_RO_MOUNT_FAILED;
  206. }
  207. }
  208. /*
  209. * Some system images do not have e2fsck for licensing reasons
  210. * (e.g. recent SDK system images). Detect these and skip the check.
  211. */
  212. if (access(E2FSCK_BIN, X_OK)) {
  213. LINFO << "Not running " << E2FSCK_BIN << " on " << realpath(blk_device)
  214. << " (executable not in system image)";
  215. } else {
  216. LINFO << "Running " << E2FSCK_BIN << " on " << realpath(blk_device);
  217. if (should_force_check(*fs_stat)) {
  218. ret = android_fork_execvp_ext(
  219. ARRAY_SIZE(e2fsck_forced_argv), const_cast<char**>(e2fsck_forced_argv), &status,
  220. true, LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), nullptr, 0);
  221. } else {
  222. ret = android_fork_execvp_ext(
  223. ARRAY_SIZE(e2fsck_argv), const_cast<char**>(e2fsck_argv), &status, true,
  224. LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), nullptr, 0);
  225. }
  226. if (ret < 0) {
  227. /* No need to check for error in fork, we can't really handle it now */
  228. LERROR << "Failed trying to run " << E2FSCK_BIN;
  229. *fs_stat |= FS_STAT_E2FSCK_FAILED;
  230. } else if (status != 0) {
  231. LINFO << "e2fsck returned status 0x" << std::hex << status;
  232. *fs_stat |= FS_STAT_E2FSCK_FS_FIXED;
  233. }
  234. }
  235. } else if (is_f2fs(fs_type)) {
  236. const char* f2fs_fsck_argv[] = {F2FS_FSCK_BIN, "-a", blk_device.c_str()};
  237. const char* f2fs_fsck_forced_argv[] = {F2FS_FSCK_BIN, "-f", blk_device.c_str()};
  238. if (should_force_check(*fs_stat)) {
  239. LINFO << "Running " << F2FS_FSCK_BIN << " -f " << realpath(blk_device);
  240. ret = android_fork_execvp_ext(
  241. ARRAY_SIZE(f2fs_fsck_forced_argv), const_cast<char**>(f2fs_fsck_forced_argv), &status,
  242. true, LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), nullptr, 0);
  243. } else {
  244. LINFO << "Running " << F2FS_FSCK_BIN << " -a " << realpath(blk_device);
  245. ret = android_fork_execvp_ext(
  246. ARRAY_SIZE(f2fs_fsck_argv), const_cast<char**>(f2fs_fsck_argv), &status, true,
  247. LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), nullptr, 0);
  248. }
  249. if (ret < 0) {
  250. /* No need to check for error in fork, we can't really handle it now */
  251. LERROR << "Failed trying to run " << F2FS_FSCK_BIN;
  252. }
  253. }
  254. return;
  255. }
  256. static ext4_fsblk_t ext4_blocks_count(const struct ext4_super_block* es) {
  257. return ((ext4_fsblk_t)le32_to_cpu(es->s_blocks_count_hi) << 32) |
  258. le32_to_cpu(es->s_blocks_count_lo);
  259. }
  260. static ext4_fsblk_t ext4_r_blocks_count(const struct ext4_super_block* es) {
  261. return ((ext4_fsblk_t)le32_to_cpu(es->s_r_blocks_count_hi) << 32) |
  262. le32_to_cpu(es->s_r_blocks_count_lo);
  263. }
  264. static bool is_ext4_superblock_valid(const struct ext4_super_block* es) {
  265. if (es->s_magic != EXT4_SUPER_MAGIC) return false;
  266. if (es->s_rev_level != EXT4_DYNAMIC_REV && es->s_rev_level != EXT4_GOOD_OLD_REV) return false;
  267. if (EXT4_INODES_PER_GROUP(es) == 0) return false;
  268. return true;
  269. }
  270. // Read the primary superblock from an ext4 filesystem. On failure return
  271. // false. If it's not an ext4 filesystem, also set FS_STAT_INVALID_MAGIC.
  272. static bool read_ext4_superblock(const std::string& blk_device, struct ext4_super_block* sb,
  273. int* fs_stat) {
  274. android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
  275. if (fd < 0) {
  276. PERROR << "Failed to open '" << blk_device << "'";
  277. return false;
  278. }
  279. if (TEMP_FAILURE_RETRY(pread(fd, sb, sizeof(*sb), 1024)) != sizeof(*sb)) {
  280. PERROR << "Can't read '" << blk_device << "' superblock";
  281. return false;
  282. }
  283. if (!is_ext4_superblock_valid(sb)) {
  284. LINFO << "Invalid ext4 superblock on '" << blk_device << "'";
  285. // not a valid fs, tune2fs, fsck, and mount will all fail.
  286. *fs_stat |= FS_STAT_INVALID_MAGIC;
  287. return false;
  288. }
  289. *fs_stat |= FS_STAT_IS_EXT4;
  290. LINFO << "superblock s_max_mnt_count:" << sb->s_max_mnt_count << "," << blk_device;
  291. if (sb->s_max_mnt_count == 0xffff) { // -1 (int16) in ext2, but uint16 in ext4
  292. *fs_stat |= FS_STAT_NEW_IMAGE_VERSION;
  293. }
  294. return true;
  295. }
  296. // exported silent version of the above that just answer the question is_ext4
  297. bool fs_mgr_is_ext4(const std::string& blk_device) {
  298. android::base::ErrnoRestorer restore;
  299. android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
  300. if (fd < 0) return false;
  301. ext4_super_block sb;
  302. if (TEMP_FAILURE_RETRY(pread(fd, &sb, sizeof(sb), 1024)) != sizeof(sb)) return false;
  303. if (!is_ext4_superblock_valid(&sb)) return false;
  304. return true;
  305. }
  306. // Some system images do not have tune2fs for licensing reasons.
  307. // Detect these and skip running it.
  308. static bool tune2fs_available(void) {
  309. return access(TUNE2FS_BIN, X_OK) == 0;
  310. }
  311. static bool run_tune2fs(const char* argv[], int argc) {
  312. int ret;
  313. ret = android_fork_execvp_ext(argc, const_cast<char**>(argv), nullptr, true,
  314. LOG_KLOG | LOG_FILE, true, nullptr, nullptr, 0);
  315. return ret == 0;
  316. }
  317. // Enable/disable quota support on the filesystem if needed.
  318. static void tune_quota(const std::string& blk_device, const FstabEntry& entry,
  319. const struct ext4_super_block* sb, int* fs_stat) {
  320. bool has_quota = (sb->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_RO_COMPAT_QUOTA)) != 0;
  321. bool want_quota = entry.fs_mgr_flags.quota;
  322. if (has_quota == want_quota) {
  323. return;
  324. }
  325. if (!tune2fs_available()) {
  326. LERROR << "Unable to " << (want_quota ? "enable" : "disable") << " quotas on " << blk_device
  327. << " because " TUNE2FS_BIN " is missing";
  328. return;
  329. }
  330. const char* argv[] = {TUNE2FS_BIN, nullptr, nullptr, blk_device.c_str()};
  331. if (want_quota) {
  332. LINFO << "Enabling quotas on " << blk_device;
  333. argv[1] = "-Oquota";
  334. argv[2] = "-Qusrquota,grpquota";
  335. *fs_stat |= FS_STAT_QUOTA_ENABLED;
  336. } else {
  337. LINFO << "Disabling quotas on " << blk_device;
  338. argv[1] = "-O^quota";
  339. argv[2] = "-Q^usrquota,^grpquota";
  340. }
  341. if (!run_tune2fs(argv, ARRAY_SIZE(argv))) {
  342. LERROR << "Failed to run " TUNE2FS_BIN " to " << (want_quota ? "enable" : "disable")
  343. << " quotas on " << blk_device;
  344. *fs_stat |= FS_STAT_TOGGLE_QUOTAS_FAILED;
  345. }
  346. }
  347. // Set the number of reserved filesystem blocks if needed.
  348. static void tune_reserved_size(const std::string& blk_device, const FstabEntry& entry,
  349. const struct ext4_super_block* sb, int* fs_stat) {
  350. if (entry.reserved_size == 0) {
  351. return;
  352. }
  353. // The size to reserve is given in the fstab, but we won't reserve more
  354. // than 2% of the filesystem.
  355. const uint64_t max_reserved_blocks = ext4_blocks_count(sb) * 0.02;
  356. uint64_t reserved_blocks = entry.reserved_size / EXT4_BLOCK_SIZE(sb);
  357. if (reserved_blocks > max_reserved_blocks) {
  358. LWARNING << "Reserved blocks " << reserved_blocks << " is too large; "
  359. << "capping to " << max_reserved_blocks;
  360. reserved_blocks = max_reserved_blocks;
  361. }
  362. if ((ext4_r_blocks_count(sb) == reserved_blocks) && (sb->s_def_resgid == AID_RESERVED_DISK)) {
  363. return;
  364. }
  365. if (!tune2fs_available()) {
  366. LERROR << "Unable to set the number of reserved blocks on " << blk_device
  367. << " because " TUNE2FS_BIN " is missing";
  368. return;
  369. }
  370. LINFO << "Setting reserved block count on " << blk_device << " to " << reserved_blocks;
  371. auto reserved_blocks_str = std::to_string(reserved_blocks);
  372. auto reserved_gid_str = std::to_string(AID_RESERVED_DISK);
  373. const char* argv[] = {
  374. TUNE2FS_BIN, "-r", reserved_blocks_str.c_str(), "-g", reserved_gid_str.c_str(),
  375. blk_device.c_str()};
  376. if (!run_tune2fs(argv, ARRAY_SIZE(argv))) {
  377. LERROR << "Failed to run " TUNE2FS_BIN " to set the number of reserved blocks on "
  378. << blk_device;
  379. *fs_stat |= FS_STAT_SET_RESERVED_BLOCKS_FAILED;
  380. }
  381. }
  382. // Enable file-based encryption if needed.
  383. static void tune_encrypt(const std::string& blk_device, const FstabEntry& entry,
  384. const struct ext4_super_block* sb, int* fs_stat) {
  385. bool has_encrypt = (sb->s_feature_incompat & cpu_to_le32(EXT4_FEATURE_INCOMPAT_ENCRYPT)) != 0;
  386. bool want_encrypt = entry.fs_mgr_flags.file_encryption;
  387. if (has_encrypt || !want_encrypt) {
  388. return;
  389. }
  390. if (!tune2fs_available()) {
  391. LERROR << "Unable to enable ext4 encryption on " << blk_device
  392. << " because " TUNE2FS_BIN " is missing";
  393. return;
  394. }
  395. const char* argv[] = {TUNE2FS_BIN, "-Oencrypt", blk_device.c_str()};
  396. LINFO << "Enabling ext4 encryption on " << blk_device;
  397. if (!run_tune2fs(argv, ARRAY_SIZE(argv))) {
  398. LERROR << "Failed to run " TUNE2FS_BIN " to enable "
  399. << "ext4 encryption on " << blk_device;
  400. *fs_stat |= FS_STAT_ENABLE_ENCRYPTION_FAILED;
  401. }
  402. }
  403. // Enable fs-verity if needed.
  404. static void tune_verity(const std::string& blk_device, const FstabEntry& entry,
  405. const struct ext4_super_block* sb, int* fs_stat) {
  406. bool has_verity = (sb->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_RO_COMPAT_VERITY)) != 0;
  407. bool want_verity = entry.fs_mgr_flags.fs_verity;
  408. if (has_verity || !want_verity) {
  409. return;
  410. }
  411. std::string verity_support;
  412. if (!android::base::ReadFileToString(SYSFS_EXT4_VERITY, &verity_support)) {
  413. LERROR << "Failed to open " << SYSFS_EXT4_VERITY;
  414. return;
  415. }
  416. if (!(android::base::Trim(verity_support) == "supported")) {
  417. LERROR << "Current ext4 verity not supported by kernel";
  418. return;
  419. }
  420. if (!tune2fs_available()) {
  421. LERROR << "Unable to enable ext4 verity on " << blk_device
  422. << " because " TUNE2FS_BIN " is missing";
  423. return;
  424. }
  425. LINFO << "Enabling ext4 verity on " << blk_device;
  426. const char* argv[] = {TUNE2FS_BIN, "-O", "verity", blk_device.c_str()};
  427. if (!run_tune2fs(argv, ARRAY_SIZE(argv))) {
  428. LERROR << "Failed to run " TUNE2FS_BIN " to enable "
  429. << "ext4 verity on " << blk_device;
  430. *fs_stat |= FS_STAT_ENABLE_VERITY_FAILED;
  431. }
  432. }
  433. // Read the primary superblock from an f2fs filesystem. On failure return
  434. // false. If it's not an f2fs filesystem, also set FS_STAT_INVALID_MAGIC.
  435. #define F2FS_BLKSIZE 4096
  436. #define F2FS_SUPER_OFFSET 1024
  437. static bool read_f2fs_superblock(const std::string& blk_device, int* fs_stat) {
  438. android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
  439. __le32 sb1, sb2;
  440. if (fd < 0) {
  441. PERROR << "Failed to open '" << blk_device << "'";
  442. return false;
  443. }
  444. if (TEMP_FAILURE_RETRY(pread(fd, &sb1, sizeof(sb1), F2FS_SUPER_OFFSET)) != sizeof(sb1)) {
  445. PERROR << "Can't read '" << blk_device << "' superblock1";
  446. return false;
  447. }
  448. if (TEMP_FAILURE_RETRY(pread(fd, &sb2, sizeof(sb2), F2FS_BLKSIZE + F2FS_SUPER_OFFSET)) !=
  449. sizeof(sb2)) {
  450. PERROR << "Can't read '" << blk_device << "' superblock2";
  451. return false;
  452. }
  453. if (sb1 != cpu_to_le32(F2FS_SUPER_MAGIC) && sb2 != cpu_to_le32(F2FS_SUPER_MAGIC)) {
  454. LINFO << "Invalid f2fs superblock on '" << blk_device << "'";
  455. *fs_stat |= FS_STAT_INVALID_MAGIC;
  456. return false;
  457. }
  458. return true;
  459. }
  460. // exported silent version of the above that just answer the question is_f2fs
  461. bool fs_mgr_is_f2fs(const std::string& blk_device) {
  462. android::base::ErrnoRestorer restore;
  463. android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
  464. if (fd < 0) return false;
  465. __le32 sb;
  466. if (TEMP_FAILURE_RETRY(pread(fd, &sb, sizeof(sb), F2FS_SUPER_OFFSET)) != sizeof(sb)) {
  467. return false;
  468. }
  469. if (sb == cpu_to_le32(F2FS_SUPER_MAGIC)) return true;
  470. if (TEMP_FAILURE_RETRY(pread(fd, &sb, sizeof(sb), F2FS_BLKSIZE + F2FS_SUPER_OFFSET)) !=
  471. sizeof(sb)) {
  472. return false;
  473. }
  474. return sb == cpu_to_le32(F2FS_SUPER_MAGIC);
  475. }
  476. //
  477. // Prepare the filesystem on the given block device to be mounted.
  478. //
  479. // If the "check" option was given in the fstab record, or it seems that the
  480. // filesystem was uncleanly shut down, we'll run fsck on the filesystem.
  481. //
  482. // If needed, we'll also enable (or disable) filesystem features as specified by
  483. // the fstab record.
  484. //
  485. static int prepare_fs_for_mount(const std::string& blk_device, const FstabEntry& entry) {
  486. int fs_stat = 0;
  487. if (is_extfs(entry.fs_type)) {
  488. struct ext4_super_block sb;
  489. if (read_ext4_superblock(blk_device, &sb, &fs_stat)) {
  490. if ((sb.s_feature_incompat & EXT4_FEATURE_INCOMPAT_RECOVER) != 0 ||
  491. (sb.s_state & EXT4_VALID_FS) == 0) {
  492. LINFO << "Filesystem on " << blk_device << " was not cleanly shutdown; "
  493. << "state flags: 0x" << std::hex << sb.s_state << ", "
  494. << "incompat feature flags: 0x" << std::hex << sb.s_feature_incompat;
  495. fs_stat |= FS_STAT_UNCLEAN_SHUTDOWN;
  496. }
  497. // Note: quotas should be enabled before running fsck.
  498. tune_quota(blk_device, entry, &sb, &fs_stat);
  499. } else {
  500. return fs_stat;
  501. }
  502. } else if (is_f2fs(entry.fs_type)) {
  503. if (!read_f2fs_superblock(blk_device, &fs_stat)) {
  504. return fs_stat;
  505. }
  506. }
  507. if (entry.fs_mgr_flags.check ||
  508. (fs_stat & (FS_STAT_UNCLEAN_SHUTDOWN | FS_STAT_QUOTA_ENABLED))) {
  509. check_fs(blk_device, entry.fs_type, entry.mount_point, &fs_stat);
  510. }
  511. if (is_extfs(entry.fs_type) &&
  512. (entry.reserved_size != 0 || entry.fs_mgr_flags.file_encryption ||
  513. entry.fs_mgr_flags.fs_verity)) {
  514. struct ext4_super_block sb;
  515. if (read_ext4_superblock(blk_device, &sb, &fs_stat)) {
  516. tune_reserved_size(blk_device, entry, &sb, &fs_stat);
  517. tune_encrypt(blk_device, entry, &sb, &fs_stat);
  518. tune_verity(blk_device, entry, &sb, &fs_stat);
  519. }
  520. }
  521. return fs_stat;
  522. }
  523. // Mark the given block device as read-only, using the BLKROSET ioctl.
  524. bool fs_mgr_set_blk_ro(const std::string& blockdev, bool readonly) {
  525. unique_fd fd(TEMP_FAILURE_RETRY(open(blockdev.c_str(), O_RDONLY | O_CLOEXEC)));
  526. if (fd < 0) {
  527. return false;
  528. }
  529. int ON = readonly;
  530. return ioctl(fd, BLKROSET, &ON) == 0;
  531. }
  532. // Orange state means the device is unlocked, see the following link for details.
  533. // https://source.android.com/security/verifiedboot/verified-boot#device_state
  534. bool fs_mgr_is_device_unlocked() {
  535. std::string verified_boot_state;
  536. if (fs_mgr_get_boot_config("verifiedbootstate", &verified_boot_state)) {
  537. return verified_boot_state == "orange";
  538. }
  539. return false;
  540. }
  541. // __mount(): wrapper around the mount() system call which also
  542. // sets the underlying block device to read-only if the mount is read-only.
  543. // See "man 2 mount" for return values.
  544. static int __mount(const std::string& source, const std::string& target, const FstabEntry& entry) {
  545. // We need this because sometimes we have legacy symlinks that are
  546. // lingering around and need cleaning up.
  547. struct stat info;
  548. if (lstat(target.c_str(), &info) == 0 && (info.st_mode & S_IFMT) == S_IFLNK) {
  549. unlink(target.c_str());
  550. }
  551. mkdir(target.c_str(), 0755);
  552. errno = 0;
  553. unsigned long mountflags = entry.flags;
  554. int ret = 0;
  555. int save_errno = 0;
  556. do {
  557. if (save_errno == EAGAIN) {
  558. PINFO << "Retrying mount (source=" << source << ",target=" << target
  559. << ",type=" << entry.fs_type << ")=" << ret << "(" << save_errno << ")";
  560. }
  561. ret = mount(source.c_str(), target.c_str(), entry.fs_type.c_str(), mountflags,
  562. entry.fs_options.c_str());
  563. save_errno = errno;
  564. } while (ret && save_errno == EAGAIN);
  565. const char* target_missing = "";
  566. const char* source_missing = "";
  567. if (save_errno == ENOENT) {
  568. if (access(target.c_str(), F_OK)) {
  569. target_missing = "(missing)";
  570. } else if (access(source.c_str(), F_OK)) {
  571. source_missing = "(missing)";
  572. }
  573. errno = save_errno;
  574. }
  575. PINFO << __FUNCTION__ << "(source=" << source << source_missing << ",target=" << target
  576. << target_missing << ",type=" << entry.fs_type << ")=" << ret;
  577. if ((ret == 0) && (mountflags & MS_RDONLY) != 0) {
  578. fs_mgr_set_blk_ro(source);
  579. }
  580. errno = save_errno;
  581. return ret;
  582. }
  583. static bool fs_match(const std::string& in1, const std::string& in2) {
  584. if (in1.empty() || in2.empty()) {
  585. return false;
  586. }
  587. auto in1_end = in1.size() - 1;
  588. while (in1_end > 0 && in1[in1_end] == '/') {
  589. in1_end--;
  590. }
  591. auto in2_end = in2.size() - 1;
  592. while (in2_end > 0 && in2[in2_end] == '/') {
  593. in2_end--;
  594. }
  595. if (in1_end != in2_end) {
  596. return false;
  597. }
  598. for (size_t i = 0; i <= in1_end; ++i) {
  599. if (in1[i] != in2[i]) {
  600. return false;
  601. }
  602. }
  603. return true;
  604. }
  605. // Tries to mount any of the consecutive fstab entries that match
  606. // the mountpoint of the one given by fstab[start_idx].
  607. //
  608. // end_idx: On return, will be the last entry that was looked at.
  609. // attempted_idx: On return, will indicate which fstab entry
  610. // succeeded. In case of failure, it will be the start_idx.
  611. // Sets errno to match the 1st mount failure on failure.
  612. static bool mount_with_alternatives(const Fstab& fstab, int start_idx, int* end_idx,
  613. int* attempted_idx) {
  614. unsigned long i;
  615. int mount_errno = 0;
  616. bool mounted = false;
  617. // Hunt down an fstab entry for the same mount point that might succeed.
  618. for (i = start_idx;
  619. // We required that fstab entries for the same mountpoint be consecutive.
  620. i < fstab.size() && fstab[start_idx].mount_point == fstab[i].mount_point; i++) {
  621. // Don't try to mount/encrypt the same mount point again.
  622. // Deal with alternate entries for the same point which are required to be all following
  623. // each other.
  624. if (mounted) {
  625. LERROR << __FUNCTION__ << "(): skipping fstab dup mountpoint=" << fstab[i].mount_point
  626. << " rec[" << i << "].fs_type=" << fstab[i].fs_type << " already mounted as "
  627. << fstab[*attempted_idx].fs_type;
  628. continue;
  629. }
  630. int fs_stat = prepare_fs_for_mount(fstab[i].blk_device, fstab[i]);
  631. if (fs_stat & FS_STAT_INVALID_MAGIC) {
  632. LERROR << __FUNCTION__
  633. << "(): skipping mount due to invalid magic, mountpoint=" << fstab[i].mount_point
  634. << " blk_dev=" << realpath(fstab[i].blk_device) << " rec[" << i
  635. << "].fs_type=" << fstab[i].fs_type;
  636. mount_errno = EINVAL; // continue bootup for FDE
  637. continue;
  638. }
  639. int retry_count = 2;
  640. while (retry_count-- > 0) {
  641. if (!__mount(fstab[i].blk_device, fstab[i].mount_point, fstab[i])) {
  642. *attempted_idx = i;
  643. mounted = true;
  644. if (i != start_idx) {
  645. LERROR << __FUNCTION__ << "(): Mounted " << fstab[i].blk_device << " on "
  646. << fstab[i].mount_point << " with fs_type=" << fstab[i].fs_type
  647. << " instead of " << fstab[start_idx].fs_type;
  648. }
  649. fs_stat &= ~FS_STAT_FULL_MOUNT_FAILED;
  650. mount_errno = 0;
  651. break;
  652. } else {
  653. if (retry_count <= 0) break; // run check_fs only once
  654. fs_stat |= FS_STAT_FULL_MOUNT_FAILED;
  655. // back up the first errno for crypto decisions.
  656. if (mount_errno == 0) {
  657. mount_errno = errno;
  658. }
  659. // retry after fsck
  660. check_fs(fstab[i].blk_device, fstab[i].fs_type, fstab[i].mount_point, &fs_stat);
  661. }
  662. }
  663. log_fs_stat(fstab[i].blk_device, fs_stat);
  664. }
  665. /* Adjust i for the case where it was still withing the recs[] */
  666. if (i < fstab.size()) --i;
  667. *end_idx = i;
  668. if (!mounted) {
  669. *attempted_idx = start_idx;
  670. errno = mount_errno;
  671. return false;
  672. }
  673. return true;
  674. }
  675. static bool TranslateExtLabels(FstabEntry* entry) {
  676. if (!StartsWith(entry->blk_device, "LABEL=")) {
  677. return true;
  678. }
  679. std::string label = entry->blk_device.substr(6);
  680. if (label.size() > 16) {
  681. LERROR << "FS label is longer than allowed by filesystem";
  682. return false;
  683. }
  684. auto blockdir = std::unique_ptr<DIR, decltype(&closedir)>{opendir("/dev/block"), closedir};
  685. if (!blockdir) {
  686. LERROR << "couldn't open /dev/block";
  687. return false;
  688. }
  689. struct dirent* ent;
  690. while ((ent = readdir(blockdir.get()))) {
  691. if (ent->d_type != DT_BLK)
  692. continue;
  693. unique_fd fd(TEMP_FAILURE_RETRY(
  694. openat(dirfd(blockdir.get()), ent->d_name, O_RDONLY | O_CLOEXEC)));
  695. if (fd < 0) {
  696. LERROR << "Cannot open block device /dev/block/" << ent->d_name;
  697. return false;
  698. }
  699. ext4_super_block super_block;
  700. if (TEMP_FAILURE_RETRY(lseek(fd, 1024, SEEK_SET)) < 0 ||
  701. TEMP_FAILURE_RETRY(read(fd, &super_block, sizeof(super_block))) !=
  702. sizeof(super_block)) {
  703. // Probably a loopback device or something else without a readable superblock.
  704. continue;
  705. }
  706. if (super_block.s_magic != EXT4_SUPER_MAGIC) {
  707. LINFO << "/dev/block/" << ent->d_name << " not ext{234}";
  708. continue;
  709. }
  710. if (label == super_block.s_volume_name) {
  711. std::string new_blk_device = "/dev/block/"s + ent->d_name;
  712. LINFO << "resolved label " << entry->blk_device << " to " << new_blk_device;
  713. entry->blk_device = new_blk_device;
  714. return true;
  715. }
  716. }
  717. return false;
  718. }
  719. static bool needs_block_encryption(const FstabEntry& entry) {
  720. if (android::base::GetBoolProperty("ro.vold.forceencryption", false) && entry.is_encryptable())
  721. return true;
  722. if (entry.fs_mgr_flags.force_crypt) return true;
  723. if (entry.fs_mgr_flags.crypt) {
  724. // Check for existence of convert_fde breadcrumb file.
  725. auto convert_fde_name = entry.mount_point + "/misc/vold/convert_fde";
  726. if (access(convert_fde_name.c_str(), F_OK) == 0) return true;
  727. }
  728. if (entry.fs_mgr_flags.force_fde_or_fbe) {
  729. // Check for absence of convert_fbe breadcrumb file.
  730. auto convert_fbe_name = entry.mount_point + "/convert_fbe";
  731. if (access(convert_fbe_name.c_str(), F_OK) != 0) return true;
  732. }
  733. return false;
  734. }
  735. static bool should_use_metadata_encryption(const FstabEntry& entry) {
  736. return !entry.key_dir.empty() &&
  737. (entry.fs_mgr_flags.file_encryption || entry.fs_mgr_flags.force_fde_or_fbe);
  738. }
  739. // Check to see if a mountable volume has encryption requirements
  740. static int handle_encryptable(const FstabEntry& entry) {
  741. // If this is block encryptable, need to trigger encryption.
  742. if (needs_block_encryption(entry)) {
  743. if (umount(entry.mount_point.c_str()) == 0) {
  744. return FS_MGR_MNTALL_DEV_NEEDS_ENCRYPTION;
  745. } else {
  746. PWARNING << "Could not umount " << entry.mount_point << " - allow continue unencrypted";
  747. return FS_MGR_MNTALL_DEV_NOT_ENCRYPTED;
  748. }
  749. } else if (should_use_metadata_encryption(entry)) {
  750. if (umount(entry.mount_point.c_str()) == 0) {
  751. return FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION;
  752. } else {
  753. PERROR << "Could not umount " << entry.mount_point << " - fail since can't encrypt";
  754. return FS_MGR_MNTALL_FAIL;
  755. }
  756. } else if (entry.fs_mgr_flags.file_encryption || entry.fs_mgr_flags.force_fde_or_fbe) {
  757. LINFO << entry.mount_point << " is file encrypted";
  758. return FS_MGR_MNTALL_DEV_FILE_ENCRYPTED;
  759. } else if (entry.is_encryptable()) {
  760. return FS_MGR_MNTALL_DEV_NOT_ENCRYPTED;
  761. } else {
  762. return FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE;
  763. }
  764. }
  765. static bool call_vdc(const std::vector<std::string>& args) {
  766. std::vector<char const*> argv;
  767. argv.emplace_back("/system/bin/vdc");
  768. for (auto& arg : args) {
  769. argv.emplace_back(arg.c_str());
  770. }
  771. LOG(INFO) << "Calling: " << android::base::Join(argv, ' ');
  772. int ret =
  773. android_fork_execvp(argv.size(), const_cast<char**>(argv.data()), nullptr, false, true);
  774. if (ret != 0) {
  775. LOG(ERROR) << "vdc returned error code: " << ret;
  776. return false;
  777. }
  778. LOG(DEBUG) << "vdc finished successfully";
  779. return true;
  780. }
  781. static bool call_vdc_ret(const std::vector<std::string>& args, int* ret) {
  782. std::vector<char const*> argv;
  783. argv.emplace_back("/system/bin/vdc");
  784. for (auto& arg : args) {
  785. argv.emplace_back(arg.c_str());
  786. }
  787. LOG(INFO) << "Calling: " << android::base::Join(argv, ' ');
  788. int err = android_fork_execvp(argv.size(), const_cast<char**>(argv.data()), ret, false, true);
  789. if (err != 0) {
  790. LOG(ERROR) << "vdc call failed with error code: " << err;
  791. return false;
  792. }
  793. LOG(DEBUG) << "vdc finished successfully";
  794. *ret = WEXITSTATUS(*ret);
  795. return true;
  796. }
  797. bool fs_mgr_update_logical_partition(FstabEntry* entry) {
  798. // Logical partitions are specified with a named partition rather than a
  799. // block device, so if the block device is a path, then it has already
  800. // been updated.
  801. if (entry->blk_device[0] == '/') {
  802. return true;
  803. }
  804. DeviceMapper& dm = DeviceMapper::Instance();
  805. std::string device_name;
  806. if (!dm.GetDmDevicePathByName(entry->blk_device, &device_name)) {
  807. return false;
  808. }
  809. entry->blk_device = device_name;
  810. return true;
  811. }
  812. class CheckpointManager {
  813. public:
  814. CheckpointManager(int needs_checkpoint = -1) : needs_checkpoint_(needs_checkpoint) {}
  815. bool Update(FstabEntry* entry, const std::string& block_device = std::string()) {
  816. if (!entry->fs_mgr_flags.checkpoint_blk && !entry->fs_mgr_flags.checkpoint_fs) {
  817. return true;
  818. }
  819. if (entry->fs_mgr_flags.checkpoint_blk) {
  820. call_vdc({"checkpoint", "restoreCheckpoint", entry->blk_device});
  821. }
  822. if (needs_checkpoint_ == UNKNOWN &&
  823. !call_vdc_ret({"checkpoint", "needsCheckpoint"}, &needs_checkpoint_)) {
  824. LERROR << "Failed to find if checkpointing is needed. Assuming no.";
  825. needs_checkpoint_ = NO;
  826. }
  827. if (needs_checkpoint_ != YES) {
  828. return true;
  829. }
  830. if (!UpdateCheckpointPartition(entry, block_device)) {
  831. LERROR << "Could not set up checkpoint partition, skipping!";
  832. return false;
  833. }
  834. return true;
  835. }
  836. bool Revert(FstabEntry* entry) {
  837. if (!entry->fs_mgr_flags.checkpoint_blk && !entry->fs_mgr_flags.checkpoint_fs) {
  838. return true;
  839. }
  840. if (device_map_.find(entry->blk_device) == device_map_.end()) {
  841. return true;
  842. }
  843. std::string bow_device = entry->blk_device;
  844. entry->blk_device = device_map_[bow_device];
  845. device_map_.erase(bow_device);
  846. DeviceMapper& dm = DeviceMapper::Instance();
  847. if (!dm.DeleteDevice("bow")) {
  848. PERROR << "Failed to remove bow device";
  849. }
  850. return true;
  851. }
  852. private:
  853. bool UpdateCheckpointPartition(FstabEntry* entry, const std::string& block_device) {
  854. if (entry->fs_mgr_flags.checkpoint_fs) {
  855. if (is_f2fs(entry->fs_type)) {
  856. entry->fs_options += ",checkpoint=disable";
  857. } else {
  858. LERROR << entry->fs_type << " does not implement checkpoints.";
  859. }
  860. } else if (entry->fs_mgr_flags.checkpoint_blk) {
  861. auto actual_block_device = block_device.empty() ? entry->blk_device : block_device;
  862. if (fs_mgr_find_bow_device(actual_block_device).empty()) {
  863. unique_fd fd(
  864. TEMP_FAILURE_RETRY(open(entry->blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
  865. if (fd < 0) {
  866. PERROR << "Cannot open device " << entry->blk_device;
  867. return false;
  868. }
  869. uint64_t size = get_block_device_size(fd) / 512;
  870. if (!size) {
  871. PERROR << "Cannot get device size";
  872. return false;
  873. }
  874. android::dm::DmTable table;
  875. if (!table.AddTarget(std::make_unique<android::dm::DmTargetBow>(
  876. 0, size, entry->blk_device))) {
  877. LERROR << "Failed to add bow target";
  878. return false;
  879. }
  880. DeviceMapper& dm = DeviceMapper::Instance();
  881. if (!dm.CreateDevice("bow", table)) {
  882. PERROR << "Failed to create bow device";
  883. return false;
  884. }
  885. std::string name;
  886. if (!dm.GetDmDevicePathByName("bow", &name)) {
  887. PERROR << "Failed to get bow device name";
  888. return false;
  889. }
  890. device_map_[name] = entry->blk_device;
  891. entry->blk_device = name;
  892. }
  893. }
  894. return true;
  895. }
  896. enum { UNKNOWN = -1, NO = 0, YES = 1 };
  897. int needs_checkpoint_;
  898. std::map<std::string, std::string> device_map_;
  899. };
  900. std::string fs_mgr_find_bow_device(const std::string& block_device) {
  901. if (block_device.substr(0, 5) != "/dev/") {
  902. LOG(ERROR) << "Expected block device, got " << block_device;
  903. return std::string();
  904. }
  905. std::string sys_dir = std::string("/sys/") + block_device.substr(5);
  906. for (;;) {
  907. std::string name;
  908. if (!android::base::ReadFileToString(sys_dir + "/dm/name", &name)) {
  909. PLOG(ERROR) << block_device << " is not dm device";
  910. return std::string();
  911. }
  912. if (name == "bow\n") return sys_dir;
  913. std::string slaves = sys_dir + "/slaves";
  914. std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(slaves.c_str()), closedir);
  915. if (!directory) {
  916. PLOG(ERROR) << "Can't open slave directory " << slaves;
  917. return std::string();
  918. }
  919. int count = 0;
  920. for (dirent* entry = readdir(directory.get()); entry; entry = readdir(directory.get())) {
  921. if (entry->d_type != DT_LNK) continue;
  922. if (count == 1) {
  923. LOG(ERROR) << "Too many slaves in " << slaves;
  924. return std::string();
  925. }
  926. ++count;
  927. sys_dir = std::string("/sys/block/") + entry->d_name;
  928. }
  929. if (count != 1) {
  930. LOG(ERROR) << "No slave in " << slaves;
  931. return std::string();
  932. }
  933. }
  934. }
  935. static bool IsMountPointMounted(const std::string& mount_point) {
  936. // Check if this is already mounted.
  937. Fstab fstab;
  938. if (!ReadFstabFromFile("/proc/mounts", &fstab)) {
  939. return false;
  940. }
  941. return GetEntryForMountPoint(&fstab, mount_point) != nullptr;
  942. }
  943. // When multiple fstab records share the same mount_point, it will try to mount each
  944. // one in turn, and ignore any duplicates after a first successful mount.
  945. // Returns -1 on error, and FS_MGR_MNTALL_* otherwise.
  946. int fs_mgr_mount_all(Fstab* fstab, int mount_mode) {
  947. int encryptable = FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE;
  948. int error_count = 0;
  949. CheckpointManager checkpoint_manager;
  950. AvbUniquePtr avb_handle(nullptr);
  951. if (fstab->empty()) {
  952. return FS_MGR_MNTALL_FAIL;
  953. }
  954. for (size_t i = 0; i < fstab->size(); i++) {
  955. auto& current_entry = (*fstab)[i];
  956. // If a filesystem should have been mounted in the first stage, we
  957. // ignore it here. With one exception, if the filesystem is
  958. // formattable, then it can only be formatted in the second stage,
  959. // so we allow it to mount here.
  960. if (current_entry.fs_mgr_flags.first_stage_mount &&
  961. (!current_entry.fs_mgr_flags.formattable ||
  962. IsMountPointMounted(current_entry.mount_point))) {
  963. continue;
  964. }
  965. // Don't mount entries that are managed by vold or not for the mount mode.
  966. if (current_entry.fs_mgr_flags.vold_managed || current_entry.fs_mgr_flags.recovery_only ||
  967. ((mount_mode == MOUNT_MODE_LATE) && !current_entry.fs_mgr_flags.late_mount) ||
  968. ((mount_mode == MOUNT_MODE_EARLY) && current_entry.fs_mgr_flags.late_mount)) {
  969. continue;
  970. }
  971. // Skip swap and raw partition entries such as boot, recovery, etc.
  972. if (current_entry.fs_type == "swap" || current_entry.fs_type == "emmc" ||
  973. current_entry.fs_type == "mtd") {
  974. continue;
  975. }
  976. // Skip mounting the root partition, as it will already have been mounted.
  977. if (current_entry.mount_point == "/" || current_entry.mount_point == "/system") {
  978. if ((current_entry.flags & MS_RDONLY) != 0) {
  979. fs_mgr_set_blk_ro(current_entry.blk_device);
  980. }
  981. continue;
  982. }
  983. // Translate LABEL= file system labels into block devices.
  984. if (is_extfs(current_entry.fs_type)) {
  985. if (!TranslateExtLabels(&current_entry)) {
  986. LERROR << "Could not translate label to block device";
  987. continue;
  988. }
  989. }
  990. if (current_entry.fs_mgr_flags.logical) {
  991. if (!fs_mgr_update_logical_partition(&current_entry)) {
  992. LERROR << "Could not set up logical partition, skipping!";
  993. continue;
  994. }
  995. }
  996. if (!checkpoint_manager.Update(&current_entry)) {
  997. continue;
  998. }
  999. if (current_entry.fs_mgr_flags.wait &&
  1000. !fs_mgr_wait_for_file(current_entry.blk_device, 20s)) {
  1001. LERROR << "Skipping '" << current_entry.blk_device << "' during mount_all";
  1002. continue;
  1003. }
  1004. if (current_entry.fs_mgr_flags.avb) {
  1005. if (!avb_handle) {
  1006. avb_handle = AvbHandle::Open();
  1007. if (!avb_handle) {
  1008. LERROR << "Failed to open AvbHandle";
  1009. return FS_MGR_MNTALL_FAIL;
  1010. }
  1011. }
  1012. if (avb_handle->SetUpAvbHashtree(&current_entry, true /* wait_for_verity_dev */) ==
  1013. AvbHashtreeResult::kFail) {
  1014. LERROR << "Failed to set up AVB on partition: " << current_entry.mount_point
  1015. << ", skipping!";
  1016. // Skips mounting the device.
  1017. continue;
  1018. }
  1019. } else if (!current_entry.avb_keys.empty()) {
  1020. if (AvbHandle::SetUpStandaloneAvbHashtree(&current_entry) == AvbHashtreeResult::kFail) {
  1021. LERROR << "Failed to set up AVB on standalone partition: "
  1022. << current_entry.mount_point << ", skipping!";
  1023. // Skips mounting the device.
  1024. continue;
  1025. }
  1026. } else if ((current_entry.fs_mgr_flags.verify)) {
  1027. int rc = fs_mgr_setup_verity(&current_entry, true);
  1028. if (rc == FS_MGR_SETUP_VERITY_DISABLED || rc == FS_MGR_SETUP_VERITY_SKIPPED) {
  1029. LINFO << "Verity disabled";
  1030. } else if (rc != FS_MGR_SETUP_VERITY_SUCCESS) {
  1031. LERROR << "Could not set up verified partition, skipping!";
  1032. continue;
  1033. }
  1034. }
  1035. int last_idx_inspected;
  1036. int top_idx = i;
  1037. int attempted_idx = -1;
  1038. bool mret = mount_with_alternatives(*fstab, i, &last_idx_inspected, &attempted_idx);
  1039. auto& attempted_entry = (*fstab)[attempted_idx];
  1040. i = last_idx_inspected;
  1041. int mount_errno = errno;
  1042. // Handle success and deal with encryptability.
  1043. if (mret) {
  1044. int status = handle_encryptable(attempted_entry);
  1045. if (status == FS_MGR_MNTALL_FAIL) {
  1046. // Fatal error - no point continuing.
  1047. return status;
  1048. }
  1049. if (status != FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
  1050. if (encryptable != FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
  1051. // Log and continue
  1052. LERROR << "Only one encryptable/encrypted partition supported";
  1053. }
  1054. encryptable = status;
  1055. if (status == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
  1056. if (!call_vdc({"cryptfs", "encryptFstab", attempted_entry.blk_device,
  1057. attempted_entry.mount_point})) {
  1058. LERROR << "Encryption failed";
  1059. return FS_MGR_MNTALL_FAIL;
  1060. }
  1061. }
  1062. }
  1063. // Success! Go get the next one.
  1064. continue;
  1065. }
  1066. // Mounting failed, understand why and retry.
  1067. bool wiped = partition_wiped(current_entry.blk_device.c_str());
  1068. bool crypt_footer = false;
  1069. if (mount_errno != EBUSY && mount_errno != EACCES &&
  1070. current_entry.fs_mgr_flags.formattable && wiped) {
  1071. // current_entry and attempted_entry point at the same partition, but sometimes
  1072. // at two different lines in the fstab. Use current_entry for formatting
  1073. // as that is the preferred one.
  1074. LERROR << __FUNCTION__ << "(): " << realpath(current_entry.blk_device)
  1075. << " is wiped and " << current_entry.mount_point << " " << current_entry.fs_type
  1076. << " is formattable. Format it.";
  1077. checkpoint_manager.Revert(&current_entry);
  1078. if (current_entry.is_encryptable() && current_entry.key_loc != KEY_IN_FOOTER) {
  1079. unique_fd fd(TEMP_FAILURE_RETRY(
  1080. open(current_entry.key_loc.c_str(), O_WRONLY | O_CLOEXEC)));
  1081. if (fd >= 0) {
  1082. LINFO << __FUNCTION__ << "(): also wipe " << current_entry.key_loc;
  1083. wipe_block_device(fd, get_file_size(fd));
  1084. } else {
  1085. PERROR << __FUNCTION__ << "(): " << current_entry.key_loc << " wouldn't open";
  1086. }
  1087. } else if (current_entry.is_encryptable() && current_entry.key_loc == KEY_IN_FOOTER) {
  1088. crypt_footer = true;
  1089. }
  1090. if (fs_mgr_do_format(current_entry, crypt_footer) == 0) {
  1091. // Let's replay the mount actions.
  1092. i = top_idx - 1;
  1093. continue;
  1094. } else {
  1095. LERROR << __FUNCTION__ << "(): Format failed. "
  1096. << "Suggest recovery...";
  1097. encryptable = FS_MGR_MNTALL_DEV_NEEDS_RECOVERY;
  1098. continue;
  1099. }
  1100. }
  1101. // mount(2) returned an error, handle the encryptable/formattable case.
  1102. if (mount_errno != EBUSY && mount_errno != EACCES && attempted_entry.is_encryptable()) {
  1103. if (wiped) {
  1104. LERROR << __FUNCTION__ << "(): " << attempted_entry.blk_device << " is wiped and "
  1105. << attempted_entry.mount_point << " " << attempted_entry.fs_type
  1106. << " is encryptable. Suggest recovery...";
  1107. encryptable = FS_MGR_MNTALL_DEV_NEEDS_RECOVERY;
  1108. continue;
  1109. } else {
  1110. // Need to mount a tmpfs at this mountpoint for now, and set
  1111. // properties that vold will query later for decrypting
  1112. LERROR << __FUNCTION__ << "(): possibly an encryptable blkdev "
  1113. << attempted_entry.blk_device << " for mount " << attempted_entry.mount_point
  1114. << " type " << attempted_entry.fs_type;
  1115. if (fs_mgr_do_tmpfs_mount(attempted_entry.mount_point.c_str()) < 0) {
  1116. ++error_count;
  1117. continue;
  1118. }
  1119. }
  1120. encryptable = FS_MGR_MNTALL_DEV_MIGHT_BE_ENCRYPTED;
  1121. } else if (mount_errno != EBUSY && mount_errno != EACCES &&
  1122. should_use_metadata_encryption(attempted_entry)) {
  1123. if (!call_vdc({"cryptfs", "mountFstab", attempted_entry.blk_device,
  1124. attempted_entry.mount_point})) {
  1125. ++error_count;
  1126. }
  1127. encryptable = FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED;
  1128. continue;
  1129. } else {
  1130. // fs_options might be null so we cannot use PERROR << directly.
  1131. // Use StringPrintf to output "(null)" instead.
  1132. if (attempted_entry.fs_mgr_flags.no_fail) {
  1133. PERROR << android::base::StringPrintf(
  1134. "Ignoring failure to mount an un-encryptable or wiped "
  1135. "partition on %s at %s options: %s",
  1136. attempted_entry.blk_device.c_str(), attempted_entry.mount_point.c_str(),
  1137. attempted_entry.fs_options.c_str());
  1138. } else {
  1139. PERROR << android::base::StringPrintf(
  1140. "Failed to mount an un-encryptable or wiped partition "
  1141. "on %s at %s options: %s",
  1142. attempted_entry.blk_device.c_str(), attempted_entry.mount_point.c_str(),
  1143. attempted_entry.fs_options.c_str());
  1144. ++error_count;
  1145. }
  1146. continue;
  1147. }
  1148. }
  1149. #if ALLOW_ADBD_DISABLE_VERITY == 1 // "userdebug" build
  1150. fs_mgr_overlayfs_mount_all(fstab);
  1151. #endif
  1152. if (error_count) {
  1153. return FS_MGR_MNTALL_FAIL;
  1154. } else {
  1155. return encryptable;
  1156. }
  1157. }
  1158. int fs_mgr_umount_all(android::fs_mgr::Fstab* fstab) {
  1159. AvbUniquePtr avb_handle(nullptr);
  1160. int ret = FsMgrUmountStatus::SUCCESS;
  1161. for (auto& current_entry : *fstab) {
  1162. if (!IsMountPointMounted(current_entry.mount_point)) {
  1163. continue;
  1164. }
  1165. if (umount(current_entry.mount_point.c_str()) == -1) {
  1166. PERROR << "Failed to umount " << current_entry.mount_point;
  1167. ret |= FsMgrUmountStatus::ERROR_UMOUNT;
  1168. continue;
  1169. }
  1170. if (current_entry.fs_mgr_flags.logical) {
  1171. if (!fs_mgr_update_logical_partition(&current_entry)) {
  1172. LERROR << "Could not get logical partition blk_device, skipping!";
  1173. ret |= FsMgrUmountStatus::ERROR_DEVICE_MAPPER;
  1174. continue;
  1175. }
  1176. }
  1177. if (current_entry.fs_mgr_flags.avb || !current_entry.avb_keys.empty()) {
  1178. if (!AvbHandle::TearDownAvbHashtree(&current_entry, true /* wait */)) {
  1179. LERROR << "Failed to tear down AVB on mount point: " << current_entry.mount_point;
  1180. ret |= FsMgrUmountStatus::ERROR_VERITY;
  1181. continue;
  1182. }
  1183. } else if ((current_entry.fs_mgr_flags.verify)) {
  1184. if (!fs_mgr_teardown_verity(&current_entry, true /* wait */)) {
  1185. LERROR << "Failed to tear down verified partition on mount point: "
  1186. << current_entry.mount_point;
  1187. ret |= FsMgrUmountStatus::ERROR_VERITY;
  1188. continue;
  1189. }
  1190. }
  1191. }
  1192. return ret;
  1193. }
  1194. // wrapper to __mount() and expects a fully prepared fstab_rec,
  1195. // unlike fs_mgr_do_mount which does more things with avb / verity etc.
  1196. int fs_mgr_do_mount_one(const FstabEntry& entry, const std::string& mount_point) {
  1197. // Run fsck if needed
  1198. prepare_fs_for_mount(entry.blk_device, entry);
  1199. int ret =
  1200. __mount(entry.blk_device, mount_point.empty() ? entry.mount_point : mount_point, entry);
  1201. if (ret) {
  1202. ret = (errno == EBUSY) ? FS_MGR_DOMNT_BUSY : FS_MGR_DOMNT_FAILED;
  1203. }
  1204. return ret;
  1205. }
  1206. // If tmp_mount_point is non-null, mount the filesystem there. This is for the
  1207. // tmp mount we do to check the user password
  1208. // If multiple fstab entries are to be mounted on "n_name", it will try to mount each one
  1209. // in turn, and stop on 1st success, or no more match.
  1210. static int fs_mgr_do_mount_helper(Fstab* fstab, const std::string& n_name,
  1211. const std::string& n_blk_device, const char* tmp_mount_point,
  1212. int needs_checkpoint) {
  1213. int mount_errors = 0;
  1214. int first_mount_errno = 0;
  1215. std::string mount_point;
  1216. CheckpointManager checkpoint_manager(needs_checkpoint);
  1217. AvbUniquePtr avb_handle(nullptr);
  1218. if (!fstab) {
  1219. return FS_MGR_DOMNT_FAILED;
  1220. }
  1221. for (auto& fstab_entry : *fstab) {
  1222. if (!fs_match(fstab_entry.mount_point, n_name)) {
  1223. continue;
  1224. }
  1225. // We found our match.
  1226. // If this swap or a raw partition, report an error.
  1227. if (fstab_entry.fs_type == "swap" || fstab_entry.fs_type == "emmc" ||
  1228. fstab_entry.fs_type == "mtd") {
  1229. LERROR << "Cannot mount filesystem of type " << fstab_entry.fs_type << " on "
  1230. << n_blk_device;
  1231. return FS_MGR_DOMNT_FAILED;
  1232. }
  1233. if (fstab_entry.fs_mgr_flags.logical) {
  1234. if (!fs_mgr_update_logical_partition(&fstab_entry)) {
  1235. LERROR << "Could not set up logical partition, skipping!";
  1236. continue;
  1237. }
  1238. }
  1239. if (!checkpoint_manager.Update(&fstab_entry, n_blk_device)) {
  1240. LERROR << "Could not set up checkpoint partition, skipping!";
  1241. continue;
  1242. }
  1243. // First check the filesystem if requested.
  1244. if (fstab_entry.fs_mgr_flags.wait && !fs_mgr_wait_for_file(n_blk_device, 20s)) {
  1245. LERROR << "Skipping mounting '" << n_blk_device << "'";
  1246. continue;
  1247. }
  1248. int fs_stat = prepare_fs_for_mount(n_blk_device, fstab_entry);
  1249. if (fstab_entry.fs_mgr_flags.avb) {
  1250. if (!avb_handle) {
  1251. avb_handle = AvbHandle::Open();
  1252. if (!avb_handle) {
  1253. LERROR << "Failed to open AvbHandle";
  1254. return FS_MGR_DOMNT_FAILED;
  1255. }
  1256. }
  1257. if (avb_handle->SetUpAvbHashtree(&fstab_entry, true /* wait_for_verity_dev */) ==
  1258. AvbHashtreeResult::kFail) {
  1259. LERROR << "Failed to set up AVB on partition: " << fstab_entry.mount_point
  1260. << ", skipping!";
  1261. // Skips mounting the device.
  1262. continue;
  1263. }
  1264. } else if (!fstab_entry.avb_keys.empty()) {
  1265. if (AvbHandle::SetUpStandaloneAvbHashtree(&fstab_entry) == AvbHashtreeResult::kFail) {
  1266. LERROR << "Failed to set up AVB on standalone partition: "
  1267. << fstab_entry.mount_point << ", skipping!";
  1268. // Skips mounting the device.
  1269. continue;
  1270. }
  1271. } else if (fstab_entry.fs_mgr_flags.verify) {
  1272. int rc = fs_mgr_setup_verity(&fstab_entry, true);
  1273. if (rc == FS_MGR_SETUP_VERITY_DISABLED || rc == FS_MGR_SETUP_VERITY_SKIPPED) {
  1274. LINFO << "Verity disabled";
  1275. } else if (rc != FS_MGR_SETUP_VERITY_SUCCESS) {
  1276. LERROR << "Could not set up verified partition, skipping!";
  1277. continue;
  1278. }
  1279. }
  1280. // Now mount it where requested */
  1281. if (tmp_mount_point) {
  1282. mount_point = tmp_mount_point;
  1283. } else {
  1284. mount_point = fstab_entry.mount_point;
  1285. }
  1286. int retry_count = 2;
  1287. while (retry_count-- > 0) {
  1288. if (!__mount(n_blk_device, mount_point, fstab_entry)) {
  1289. fs_stat &= ~FS_STAT_FULL_MOUNT_FAILED;
  1290. return FS_MGR_DOMNT_SUCCESS;
  1291. } else {
  1292. if (retry_count <= 0) break; // run check_fs only once
  1293. if (!first_mount_errno) first_mount_errno = errno;
  1294. mount_errors++;
  1295. fs_stat |= FS_STAT_FULL_MOUNT_FAILED;
  1296. // try again after fsck
  1297. check_fs(n_blk_device, fstab_entry.fs_type, fstab_entry.mount_point, &fs_stat);
  1298. }
  1299. }
  1300. log_fs_stat(fstab_entry.blk_device, fs_stat);
  1301. }
  1302. // Reach here means the mount attempt fails.
  1303. if (mount_errors) {
  1304. PERROR << "Cannot mount filesystem on " << n_blk_device << " at " << mount_point;
  1305. if (first_mount_errno == EBUSY) return FS_MGR_DOMNT_BUSY;
  1306. } else {
  1307. // We didn't find a match, say so and return an error.
  1308. LERROR << "Cannot find mount point " << n_name << " in fstab";
  1309. }
  1310. return FS_MGR_DOMNT_FAILED;
  1311. }
  1312. int fs_mgr_do_mount(Fstab* fstab, const char* n_name, char* n_blk_device, char* tmp_mount_point) {
  1313. return fs_mgr_do_mount_helper(fstab, n_name, n_blk_device, tmp_mount_point, -1);
  1314. }
  1315. int fs_mgr_do_mount(Fstab* fstab, const char* n_name, char* n_blk_device, char* tmp_mount_point,
  1316. bool needs_checkpoint) {
  1317. return fs_mgr_do_mount_helper(fstab, n_name, n_blk_device, tmp_mount_point, needs_checkpoint);
  1318. }
  1319. /*
  1320. * mount a tmpfs filesystem at the given point.
  1321. * return 0 on success, non-zero on failure.
  1322. */
  1323. int fs_mgr_do_tmpfs_mount(const char *n_name)
  1324. {
  1325. int ret;
  1326. ret = mount("tmpfs", n_name, "tmpfs", MS_NOATIME | MS_NOSUID | MS_NODEV | MS_NOEXEC,
  1327. CRYPTO_TMPFS_OPTIONS);
  1328. if (ret < 0) {
  1329. LERROR << "Cannot mount tmpfs filesystem at " << n_name;
  1330. return -1;
  1331. }
  1332. /* Success */
  1333. return 0;
  1334. }
  1335. static bool InstallZramDevice(const std::string& device) {
  1336. if (!android::base::WriteStringToFile(device, ZRAM_BACK_DEV)) {
  1337. PERROR << "Cannot write " << device << " in: " << ZRAM_BACK_DEV;
  1338. return false;
  1339. }
  1340. LINFO << "Success to set " << device << " to " << ZRAM_BACK_DEV;
  1341. return true;
  1342. }
  1343. static bool PrepareZramDevice(const std::string& loop, off64_t size, const std::string& bdev) {
  1344. if (loop.empty() && bdev.empty()) return true;
  1345. if (bdev.length()) {
  1346. return InstallZramDevice(bdev);
  1347. }
  1348. // Get free loopback
  1349. unique_fd loop_fd(TEMP_FAILURE_RETRY(open("/dev/loop-control", O_RDWR | O_CLOEXEC)));
  1350. if (loop_fd.get() == -1) {
  1351. PERROR << "Cannot open loop-control";
  1352. return false;
  1353. }
  1354. int num = ioctl(loop_fd.get(), LOOP_CTL_GET_FREE);
  1355. if (num == -1) {
  1356. PERROR << "Cannot get free loop slot";
  1357. return false;
  1358. }
  1359. // Prepare target path
  1360. unique_fd target_fd(TEMP_FAILURE_RETRY(open(loop.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600)));
  1361. if (target_fd.get() == -1) {
  1362. PERROR << "Cannot open target path: " << loop;
  1363. return false;
  1364. }
  1365. if (fallocate(target_fd.get(), 0, 0, size) < 0) {
  1366. PERROR << "Cannot truncate target path: " << loop;
  1367. return false;
  1368. }
  1369. // Connect loopback (device_fd) to target path (target_fd)
  1370. std::string device = android::base::StringPrintf("/dev/block/loop%d", num);
  1371. unique_fd device_fd(TEMP_FAILURE_RETRY(open(device.c_str(), O_RDWR | O_CLOEXEC)));
  1372. if (device_fd.get() == -1) {
  1373. PERROR << "Cannot open /dev/block/loop" << num;
  1374. return false;
  1375. }
  1376. if (ioctl(device_fd.get(), LOOP_SET_FD, target_fd.get())) {
  1377. PERROR << "Cannot set loopback to target path";
  1378. return false;
  1379. }
  1380. // set block size & direct IO
  1381. if (ioctl(device_fd.get(), LOOP_SET_BLOCK_SIZE, 4096)) {
  1382. PWARNING << "Cannot set 4KB blocksize to /dev/block/loop" << num;
  1383. }
  1384. if (ioctl(device_fd.get(), LOOP_SET_DIRECT_IO, 1)) {
  1385. PWARNING << "Cannot set direct_io to /dev/block/loop" << num;
  1386. }
  1387. return InstallZramDevice(device);
  1388. }
  1389. bool fs_mgr_swapon_all(const Fstab& fstab) {
  1390. bool ret = true;
  1391. for (const auto& entry : fstab) {
  1392. // Skip non-swap entries.
  1393. if (entry.fs_type != "swap") {
  1394. continue;
  1395. }
  1396. if (!PrepareZramDevice(entry.zram_loopback_path, entry.zram_loopback_size, entry.zram_backing_dev_path)) {
  1397. LERROR << "Skipping losetup for '" << entry.blk_device << "'";
  1398. }
  1399. if (entry.zram_size > 0) {
  1400. // A zram_size was specified, so we need to configure the
  1401. // device. There is no point in having multiple zram devices
  1402. // on a system (all the memory comes from the same pool) so
  1403. // we can assume the device number is 0.
  1404. if (entry.max_comp_streams >= 0) {
  1405. auto zram_mcs_fp = std::unique_ptr<FILE, decltype(&fclose)>{
  1406. fopen(ZRAM_CONF_MCS, "re"), fclose};
  1407. if (zram_mcs_fp == nullptr) {
  1408. LERROR << "Unable to open zram conf comp device " << ZRAM_CONF_MCS;
  1409. ret = false;
  1410. continue;
  1411. }
  1412. fprintf(zram_mcs_fp.get(), "%d\n", entry.max_comp_streams);
  1413. }
  1414. auto zram_fp =
  1415. std::unique_ptr<FILE, decltype(&fclose)>{fopen(ZRAM_CONF_DEV, "re+"), fclose};
  1416. if (zram_fp == nullptr) {
  1417. LERROR << "Unable to open zram conf device " << ZRAM_CONF_DEV;
  1418. ret = false;
  1419. continue;
  1420. }
  1421. fprintf(zram_fp.get(), "%" PRId64 "\n", entry.zram_size);
  1422. }
  1423. if (entry.fs_mgr_flags.wait && !fs_mgr_wait_for_file(entry.blk_device, 20s)) {
  1424. LERROR << "Skipping mkswap for '" << entry.blk_device << "'";
  1425. ret = false;
  1426. continue;
  1427. }
  1428. // Initialize the swap area.
  1429. const char* mkswap_argv[2] = {
  1430. MKSWAP_BIN,
  1431. entry.blk_device.c_str(),
  1432. };
  1433. int err = 0;
  1434. int status;
  1435. err = android_fork_execvp_ext(ARRAY_SIZE(mkswap_argv), const_cast<char**>(mkswap_argv),
  1436. &status, true, LOG_KLOG, false, nullptr, nullptr, 0);
  1437. if (err) {
  1438. LERROR << "mkswap failed for " << entry.blk_device;
  1439. ret = false;
  1440. continue;
  1441. }
  1442. /* If -1, then no priority was specified in fstab, so don't set
  1443. * SWAP_FLAG_PREFER or encode the priority */
  1444. int flags = 0;
  1445. if (entry.swap_prio >= 0) {
  1446. flags = (entry.swap_prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK;
  1447. flags |= SWAP_FLAG_PREFER;
  1448. } else {
  1449. flags = 0;
  1450. }
  1451. err = swapon(entry.blk_device.c_str(), flags);
  1452. if (err) {
  1453. LERROR << "swapon failed for " << entry.blk_device;
  1454. ret = false;
  1455. }
  1456. }
  1457. return ret;
  1458. }
  1459. bool fs_mgr_load_verity_state(int* mode) {
  1460. /* return the default mode, unless any of the verified partitions are in
  1461. * logging mode, in which case return that */
  1462. *mode = VERITY_MODE_DEFAULT;
  1463. Fstab fstab;
  1464. if (!ReadDefaultFstab(&fstab)) {
  1465. LERROR << "Failed to read default fstab";
  1466. return false;
  1467. }
  1468. for (const auto& entry : fstab) {
  1469. if (entry.fs_mgr_flags.avb) {
  1470. *mode = VERITY_MODE_RESTART; // avb only supports restart mode.
  1471. break;
  1472. } else if (!entry.fs_mgr_flags.verify) {
  1473. continue;
  1474. }
  1475. int current;
  1476. if (load_verity_state(entry, &current) < 0) {
  1477. continue;
  1478. }
  1479. if (current != VERITY_MODE_DEFAULT) {
  1480. *mode = current;
  1481. break;
  1482. }
  1483. }
  1484. return true;
  1485. }
  1486. bool fs_mgr_is_verity_enabled(const FstabEntry& entry) {
  1487. if (!entry.fs_mgr_flags.verify && !entry.fs_mgr_flags.avb) {
  1488. return false;
  1489. }
  1490. DeviceMapper& dm = DeviceMapper::Instance();
  1491. std::string mount_point = GetVerityDeviceName(entry);
  1492. if (dm.GetState(mount_point) == DmDeviceState::INVALID) {
  1493. return false;
  1494. }
  1495. const char* status;
  1496. std::vector<DeviceMapper::TargetInfo> table;
  1497. if (!dm.GetTableStatus(mount_point, &table) || table.empty() || table[0].data.empty()) {
  1498. if (!entry.fs_mgr_flags.verify_at_boot) {
  1499. return false;
  1500. }
  1501. status = "V";
  1502. } else {
  1503. status = table[0].data.c_str();
  1504. }
  1505. if (*status == 'C' || *status == 'V') {
  1506. return true;
  1507. }
  1508. return false;
  1509. }
  1510. bool fs_mgr_verity_is_check_at_most_once(const android::fs_mgr::FstabEntry& entry) {
  1511. if (!entry.fs_mgr_flags.verify && !entry.fs_mgr_flags.avb) {
  1512. return false;
  1513. }
  1514. DeviceMapper& dm = DeviceMapper::Instance();
  1515. std::string device = GetVerityDeviceName(entry);
  1516. std::vector<DeviceMapper::TargetInfo> table;
  1517. if (dm.GetState(device) == DmDeviceState::INVALID || !dm.GetTableInfo(device, &table)) {
  1518. return false;
  1519. }
  1520. for (const auto& target : table) {
  1521. if (strcmp(target.spec.target_type, "verity") == 0 &&
  1522. target.data.find("check_at_most_once") != std::string::npos) {
  1523. return true;
  1524. }
  1525. }
  1526. return false;
  1527. }
  1528. std::string fs_mgr_get_super_partition_name(int slot) {
  1529. // Devices upgrading to dynamic partitions are allowed to specify a super
  1530. // partition name. This includes cuttlefish, which is a non-A/B device.
  1531. std::string super_partition;
  1532. if (fs_mgr_get_boot_config_from_kernel_cmdline("super_partition", &super_partition)) {
  1533. if (fs_mgr_get_slot_suffix().empty()) {
  1534. return super_partition;
  1535. }
  1536. std::string suffix;
  1537. if (slot == 0) {
  1538. suffix = "_a";
  1539. } else if (slot == 1) {
  1540. suffix = "_b";
  1541. } else if (slot == -1) {
  1542. suffix = fs_mgr_get_slot_suffix();
  1543. }
  1544. return super_partition + suffix;
  1545. }
  1546. return LP_METADATA_DEFAULT_PARTITION_NAME;
  1547. }