xref: /aosp_15_r20/bootable/recovery/recovery_utils/roots.cpp (revision e7c364b630b241adcb6c7726a21055250b91fdac)
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "recovery_utils/roots.h"
18 
19 #include <fcntl.h>
20 #include <stdint.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27 
28 #include <iostream>
29 #include <string>
30 #include <vector>
31 
32 #include <android-base/logging.h>
33 #include <android-base/properties.h>
34 #include <android-base/stringprintf.h>
35 #include <android-base/unique_fd.h>
36 #include <ext4_utils/ext4_utils.h>
37 #include <ext4_utils/wipe.h>
38 #include <fs_mgr.h>
39 #include <fs_mgr/roots.h>
40 #include <fstab/fstab.h>
41 
42 #include "otautil/sysutil.h"
43 
44 using android::fs_mgr::Fstab;
45 using android::fs_mgr::FstabEntry;
46 using android::fs_mgr::ReadDefaultFstab;
47 
48 static Fstab fstab;
49 
50 constexpr const char* CACHE_ROOT = "/cache";
51 
load_volume_table()52 void load_volume_table() {
53   if (!ReadDefaultFstab(&fstab)) {
54     LOG(ERROR) << "Failed to read default fstab";
55     return;
56   }
57 
58   fstab.emplace_back(FstabEntry{
59       .blk_device = "ramdisk",
60       .mount_point = "/tmp",
61       .fs_type = "ramdisk",
62       .length = 0,
63   });
64 
65   std::cout << "recovery filesystem table" << std::endl << "=========================" << std::endl;
66   for (size_t i = 0; i < fstab.size(); ++i) {
67     const auto& entry = fstab[i];
68     std::cout << "  " << i << " " << entry.mount_point << " "
69               << " " << entry.fs_type << " " << entry.blk_device << " " << entry.length
70               << std::endl;
71   }
72   std::cout << std::endl;
73 }
74 
volume_for_mount_point(const std::string & mount_point)75 Volume* volume_for_mount_point(const std::string& mount_point) {
76   return android::fs_mgr::GetEntryForMountPoint(&fstab, mount_point);
77 }
78 
79 // Mount the volume specified by path at the given mount_point.
ensure_path_mounted_at(const std::string & path,const std::string & mount_point)80 int ensure_path_mounted_at(const std::string& path, const std::string& mount_point) {
81   return android::fs_mgr::EnsurePathMounted(&fstab, path, mount_point) ? 0 : -1;
82 }
83 
ensure_path_mounted(const std::string & path)84 int ensure_path_mounted(const std::string& path) {
85   // Mount at the default mount point.
86   return android::fs_mgr::EnsurePathMounted(&fstab, path) ? 0 : -1;
87 }
88 
ensure_path_unmounted(const std::string & path)89 int ensure_path_unmounted(const std::string& path) {
90   return android::fs_mgr::EnsurePathUnmounted(&fstab, path) ? 0 : -1;
91 }
92 
exec_cmd(const std::vector<std::string> & args)93 static int exec_cmd(const std::vector<std::string>& args) {
94   CHECK(!args.empty());
95   auto argv = StringVectorToNullTerminatedArray(args);
96 
97   pid_t child;
98   if ((child = fork()) == 0) {
99     execv(argv[0], argv.data());
100     _exit(EXIT_FAILURE);
101   }
102 
103   int status;
104   waitpid(child, &status, 0);
105   if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
106     LOG(ERROR) << args[0] << " failed with status " << WEXITSTATUS(status);
107   }
108   return WEXITSTATUS(status);
109 }
110 
get_file_size(int fd,uint64_t reserve_len)111 static int64_t get_file_size(int fd, uint64_t reserve_len) {
112   struct stat buf;
113   int ret = fstat(fd, &buf);
114   if (ret) return 0;
115 
116   int64_t computed_size;
117   if (S_ISREG(buf.st_mode)) {
118     computed_size = buf.st_size - reserve_len;
119   } else if (S_ISBLK(buf.st_mode)) {
120     uint64_t block_device_size = get_block_device_size(fd);
121     if (block_device_size < reserve_len ||
122         block_device_size > std::numeric_limits<int64_t>::max()) {
123       computed_size = 0;
124     } else {
125       computed_size = block_device_size - reserve_len;
126     }
127   } else {
128     computed_size = 0;
129   }
130 
131   return computed_size;
132 }
133 
LocateFormattableEntry(const std::vector<FstabEntry * > & entries)134 static FstabEntry* LocateFormattableEntry(const std::vector<FstabEntry*>& entries) {
135   if (entries.empty()) {
136     return nullptr;
137   }
138   FstabEntry* f2fs_entry = nullptr;
139   for (auto&& entry : entries) {
140     if (getpagesize() != 4096 && entry->fs_type == "f2fs") {
141       f2fs_entry = entry;
142       continue;
143     }
144     if (f2fs_entry) {
145       LOG(INFO) << "Skipping F2FS format for block device " << entry->blk_device << " @ "
146                 << entry->mount_point
147                 << " in non-4K mode for dev option enabled devices, "
148                    "as these devices need to toggle between 4K/16K mode, and F2FS does "
149                    "not support page_size != block_size configuration.";
150     }
151     return entry;
152   }
153   if (f2fs_entry) {
154     LOG(INFO) << "Using F2FS for " << f2fs_entry->blk_device << " @ " << f2fs_entry->mount_point
155               << " even though we are in non-4K mode. Device might require a data wipe after "
156                  "going back to 4K mode, as F2FS does not support page_size != block_size";
157   }
158   return f2fs_entry;
159 }
160 
WipeBlockDevice(const char * path)161 bool WipeBlockDevice(const char* path) {
162   android::base::unique_fd fd(open(path, O_RDWR));
163   if (fd == -1) {
164     PLOG(ERROR) << "WipeBlockDevice: failed to open " << path;
165     return false;
166   }
167   int64_t device_size = get_file_size(fd.get(), 0);
168   if (device_size < 0) {
169     PLOG(ERROR) << "WipeBlockDevice: failed to determine size of " << device_size;
170     return false;
171   }
172   if (device_size == 0) {
173     PLOG(ERROR) << "WipeBlockDevice: block device " << device_size << " has 0 length, skip wiping";
174     return false;
175   }
176   if (!wipe_block_device(fd.get(), device_size)) {
177     return true;
178   }
179   PLOG(ERROR) << "Failed to wipe " << path;
180   return false;
181 }
182 
format_volume(const std::string & volume,const std::string & directory,std::string_view new_fstype)183 int format_volume(const std::string& volume, const std::string& directory,
184                   std::string_view new_fstype) {
185   const auto entries = android::fs_mgr::GetEntriesForPath(&fstab, volume);
186   if (entries.empty()) {
187     LOG(ERROR) << "unknown volume \"" << volume << "\"";
188     return -1;
189   }
190 
191   const FstabEntry* v = LocateFormattableEntry(entries);
192   if (v == nullptr) {
193     LOG(ERROR) << "Unable to find formattable entry for \"" << volume << "\"";
194     return -1;
195   }
196   if (v->fs_type == "ramdisk") {
197     LOG(ERROR) << "can't format_volume \"" << volume << "\"";
198     return -1;
199   }
200   if (v->mount_point != volume) {
201     LOG(ERROR) << "can't give path \"" << volume << "\" to format_volume";
202     return -1;
203   }
204   if (ensure_path_unmounted(volume) != 0) {
205     LOG(ERROR) << "format_volume: Failed to unmount \"" << v->mount_point << "\"";
206     return -1;
207   }
208   if (v->fs_type != "ext4" && v->fs_type != "f2fs") {
209     LOG(ERROR) << "format_volume: fs_type \"" << v->fs_type << "\" unsupported";
210     return -1;
211   }
212 
213   bool needs_casefold = false;
214 
215   if (volume == "/data") {
216     needs_casefold = android::base::GetBoolProperty("external_storage.casefold.enabled", false);
217   }
218 
219   int64_t length = 0;
220   if (v->length > 0) {
221     length = v->length;
222   } else if (v->length < 0) {
223     android::base::unique_fd fd(open(v->blk_device.c_str(), O_RDONLY));
224     if (fd == -1) {
225       PLOG(ERROR) << "format_volume: failed to open " << v->blk_device;
226       return -1;
227     }
228     length = get_file_size(fd.get(), -v->length);
229     if (length <= 0) {
230       LOG(ERROR) << "get_file_size: invalid size " << length << " for " << v->blk_device;
231       return -1;
232     }
233   }
234 
235   // If the raw disk will be used as a metadata encrypted device mapper target,
236   // next boot will do encrypt_in_place the raw disk. While fs_mgr mounts /data
237   // as RO to avoid write file operations before encrypt_inplace, this code path
238   // is not well tested so we would like to avoid it if possible. For safety,
239   // let vold do the formatting on boot for metadata encrypted devices, except
240   // when user specified a new fstype. Because init formats /data according
241   // to fstab, it's difficult to override the fstab in init.
242   if (!v->metadata_key_dir.empty() && length == 0 && new_fstype.empty()) {
243     android::base::unique_fd fd(open(v->blk_device.c_str(), O_RDWR));
244     if (fd == -1) {
245       PLOG(ERROR) << "format_volume: failed to open " << v->blk_device;
246       return -1;
247     }
248     int64_t device_size = get_file_size(fd.get(), 0);
249     if (device_size > 0 && !wipe_block_device(fd.get(), device_size)) {
250       LOG(INFO) << "format_volume: wipe metadata encrypted " << v->blk_device << " with size "
251                 << device_size;
252       return 0;
253     }
254   }
255 
256   if ((v->fs_type == "ext4" && new_fstype.empty()) || new_fstype == "ext4") {
257     LOG(INFO) << "Formatting " << v->blk_device << " as ext4";
258     static constexpr int kBlockSize = 4096;
259     std::vector<std::string> mke2fs_args = {
260       "/system/bin/mke2fs", "-F", "-t", "ext4", "-b", std::to_string(kBlockSize),
261     };
262 
263     // Following is added for Project ID's quota as they require wider inodes.
264     // The Quotas themselves are enabled by tune2fs on boot.
265     mke2fs_args.push_back("-I");
266     mke2fs_args.push_back("512");
267 
268     if (v->fs_mgr_flags.ext_meta_csum) {
269       mke2fs_args.push_back("-O");
270       mke2fs_args.push_back("metadata_csum");
271       mke2fs_args.push_back("-O");
272       mke2fs_args.push_back("64bit");
273       mke2fs_args.push_back("-O");
274       mke2fs_args.push_back("extent");
275     }
276 
277     int raid_stride = v->logical_blk_size / kBlockSize;
278     int raid_stripe_width = v->erase_blk_size / kBlockSize;
279     // stride should be the max of 8KB and logical block size
280     if (v->logical_blk_size != 0 && v->logical_blk_size < 8192) {
281       raid_stride = 8192 / kBlockSize;
282     }
283     if (v->erase_blk_size != 0 && v->logical_blk_size != 0) {
284       mke2fs_args.push_back("-E");
285       mke2fs_args.push_back(
286           android::base::StringPrintf("stride=%d,stripe-width=%d", raid_stride, raid_stripe_width));
287     }
288     mke2fs_args.push_back(v->blk_device);
289     if (length != 0) {
290       mke2fs_args.push_back(std::to_string(length / kBlockSize));
291     }
292 
293     int result = exec_cmd(mke2fs_args);
294     if (result == 0 && !directory.empty()) {
295       std::vector<std::string> e2fsdroid_args = {
296         "/system/bin/e2fsdroid", "-e", "-f", directory, "-a", volume, v->blk_device,
297       };
298       result = exec_cmd(e2fsdroid_args);
299     }
300 
301     if (result != 0) {
302       PLOG(ERROR) << "format_volume: Failed to make ext4 on " << v->blk_device;
303       return -1;
304     }
305     return 0;
306   }
307 
308   // Has to be f2fs because we checked earlier.
309   LOG(INFO) << "Formatting " << v->blk_device << " as f2fs";
310   static constexpr int kSectorSize = 4096;
311   std::vector<std::string> make_f2fs_cmd = {
312     "/system/bin/make_f2fs",
313     "-g",
314     "android",
315   };
316 
317   make_f2fs_cmd.push_back("-O");
318   make_f2fs_cmd.push_back("project_quota,extra_attr");
319 
320   if (needs_casefold) {
321     make_f2fs_cmd.push_back("-O");
322     make_f2fs_cmd.push_back("casefold");
323     make_f2fs_cmd.push_back("-C");
324     make_f2fs_cmd.push_back("utf8");
325   }
326   if (v->fs_mgr_flags.fs_compress) {
327     make_f2fs_cmd.push_back("-O");
328     make_f2fs_cmd.push_back("compression");
329     make_f2fs_cmd.push_back("-O");
330     make_f2fs_cmd.push_back("extra_attr");
331   }
332   make_f2fs_cmd.push_back("-b");
333   make_f2fs_cmd.push_back(std::to_string(getpagesize()));
334   make_f2fs_cmd.push_back(v->blk_device);
335   if (length >= kSectorSize) {
336     make_f2fs_cmd.push_back(std::to_string(length / kSectorSize));
337   }
338 
339   if (exec_cmd(make_f2fs_cmd) != 0) {
340     PLOG(ERROR) << "format_volume: Failed to make_f2fs on " << v->blk_device
341                 << " wiping the block device to avoid leaving partially formatted data.";
342     WipeBlockDevice(v->blk_device.c_str());
343     return -1;
344   }
345   if (!directory.empty()) {
346     std::vector<std::string> sload_f2fs_cmd = {
347       "/system/bin/sload_f2fs", "-f", directory, "-t", volume, v->blk_device,
348     };
349     if (exec_cmd(sload_f2fs_cmd) != 0) {
350       PLOG(ERROR) << "format_volume: Failed to sload_f2fs on " << v->blk_device;
351       return -1;
352     }
353   }
354   return 0;
355 }
356 
format_volume(const std::string & volume)357 int format_volume(const std::string& volume) {
358   return format_volume(volume, "", "");
359 }
360 
setup_install_mounts()361 int setup_install_mounts() {
362   if (fstab.empty()) {
363     LOG(ERROR) << "can't set up install mounts: no fstab loaded";
364     return -1;
365   }
366   for (const FstabEntry& entry : fstab) {
367     // We don't want to do anything with "/".
368     if (entry.mount_point == "/") {
369       continue;
370     }
371 
372     if (entry.mount_point == "/tmp" || entry.mount_point == "/cache") {
373       if (ensure_path_mounted(entry.mount_point) != 0) {
374         LOG(ERROR) << "Failed to mount " << entry.mount_point;
375         return -1;
376       }
377     } else {
378       if (ensure_path_unmounted(entry.mount_point) != 0) {
379         LOG(ERROR) << "Failed to unmount " << entry.mount_point;
380         return -1;
381       }
382     }
383   }
384   return 0;
385 }
386 
HasCache()387 bool HasCache() {
388   CHECK(!fstab.empty());
389   static bool has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
390   return has_cache;
391 }
392