blob: c9888abd99a860c1c26de7e3f0639033e75f7e3e [file] [log] [blame]
Yifan Hong537802d2018-08-15 13:15:42 -07001//
2// Copyright (C) 2018 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
17#include "update_engine/dynamic_partition_control_android.h"
18
Yifan Hong420db9b2019-07-23 20:50:33 -070019#include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
Yifan Hong13d41cb2019-09-16 13:18:22 -070020#include <map>
Yifan Hong537802d2018-08-15 13:15:42 -070021#include <memory>
22#include <set>
23#include <string>
Tianjie99d570d2020-06-04 14:57:19 -070024#include <string_view>
25#include <utility>
Yifan Hong012508e2019-07-22 18:30:40 -070026#include <vector>
Yifan Hong537802d2018-08-15 13:15:42 -070027
28#include <android-base/properties.h>
29#include <android-base/strings.h>
30#include <base/files/file_util.h>
31#include <base/logging.h>
Yifan Hong012508e2019-07-22 18:30:40 -070032#include <base/strings/string_util.h>
Yifan Hong537802d2018-08-15 13:15:42 -070033#include <bootloader_message/bootloader_message.h>
Yifan Hong012508e2019-07-22 18:30:40 -070034#include <fs_mgr.h>
Yifan Hong537802d2018-08-15 13:15:42 -070035#include <fs_mgr_dm_linear.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080036#include <fs_mgr_overlayfs.h>
Yifan Hong29692902020-03-26 12:47:05 -070037#include <libavb/libavb.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080038#include <libdm/dm.h>
Yifan Hong420db9b2019-07-23 20:50:33 -070039#include <libsnapshot/snapshot.h>
Yifan Hongf9cb4492020-04-15 13:00:20 -070040#include <libsnapshot/snapshot_stub.h>
Yifan Hong537802d2018-08-15 13:15:42 -070041
Yifan Hong90965502020-02-19 15:22:47 -080042#include "update_engine/cleanup_previous_update_action.h"
Yifan Hong537802d2018-08-15 13:15:42 -070043#include "update_engine/common/boot_control_interface.h"
44#include "update_engine/common/utils.h"
Yifan Hong012508e2019-07-22 18:30:40 -070045#include "update_engine/dynamic_partition_utils.h"
Yifan Hong6a6d0f12020-03-11 13:20:52 -070046#include "update_engine/payload_consumer/delta_performer.h"
Yifan Hong537802d2018-08-15 13:15:42 -070047
48using android::base::GetBoolProperty;
Yifan Hong29692902020-03-26 12:47:05 -070049using android::base::GetProperty;
Yifan Hong537802d2018-08-15 13:15:42 -070050using android::base::Join;
51using android::dm::DeviceMapper;
52using android::dm::DmDeviceState;
53using android::fs_mgr::CreateLogicalPartition;
David Andersonbb90dfb2019-08-13 14:14:56 -070054using android::fs_mgr::CreateLogicalPartitionParams;
Yifan Hong537802d2018-08-15 13:15:42 -070055using android::fs_mgr::DestroyLogicalPartition;
Yifan Hong29692902020-03-26 12:47:05 -070056using android::fs_mgr::Fstab;
Yifan Hong537802d2018-08-15 13:15:42 -070057using android::fs_mgr::MetadataBuilder;
Yifan Hong012508e2019-07-22 18:30:40 -070058using android::fs_mgr::Partition;
Yifan Hong6e706b12018-11-09 16:50:51 -080059using android::fs_mgr::PartitionOpener;
Yifan Hong012508e2019-07-22 18:30:40 -070060using android::fs_mgr::SlotSuffixForSlotNumber;
Yifan Hongf5261562020-03-10 10:28:10 -070061using android::snapshot::OptimizeSourceCopyOperation;
Yifan Hong0850bca2020-01-16 15:14:07 -080062using android::snapshot::Return;
Yifan Hongf033ecb2020-01-07 18:13:56 -080063using android::snapshot::SnapshotManager;
Yifan Hongf9cb4492020-04-15 13:00:20 -070064using android::snapshot::SnapshotManagerStub;
Yifan Hong2257ee12020-01-13 18:33:00 -080065using android::snapshot::UpdateState;
Yifan Hong537802d2018-08-15 13:15:42 -070066
67namespace chromeos_update_engine {
68
Yifan Hong6e706b12018-11-09 16:50:51 -080069constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
70constexpr char kRetrfoitDynamicPartitions[] =
71 "ro.boot.dynamic_partitions_retrofit";
Yifan Hong413d5722019-07-23 14:21:09 -070072constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
73constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
Kelvin Zhangda1b3142020-09-24 17:09:02 -040074constexpr char kVirtualAbCompressionEnabled[] =
75 "ro.virtual_ab.compression.enabled";
76
77// Currently, android doesn't have a retrofit prop for VAB Compression. However,
78// struct FeatureFlag forces us to determine if a feature is 'retrofit'. So this
79// is here just to simplify code. Replace it with real retrofit prop name once
80// there is one.
81constexpr char kVirtualAbCompressionRetrofit[] = "";
Yifan Hong29692902020-03-26 12:47:05 -070082constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
Yifan Hong420db9b2019-07-23 20:50:33 -070083// Map timeout for dynamic partitions.
84constexpr std::chrono::milliseconds kMapTimeout{1000};
85// Map timeout for dynamic partitions with snapshots. Since several devices
86// needs to be mapped, this timeout is longer than |kMapTimeout|.
87constexpr std::chrono::milliseconds kMapSnapshotTimeout{5000};
88
Yifan Hongbae27842019-10-24 16:56:12 -070089#ifdef __ANDROID_RECOVERY__
90constexpr bool kIsRecovery = true;
91#else
92constexpr bool kIsRecovery = false;
93#endif
94
Yifan Hong537802d2018-08-15 13:15:42 -070095DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
Yifan Hongbae27842019-10-24 16:56:12 -070096 Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -070097}
98
Yifan Hong186bb682019-07-23 14:04:39 -070099static FeatureFlag GetFeatureFlag(const char* enable_prop,
100 const char* retrofit_prop) {
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400101 // Default retrofit to false if retrofit_prop is empty.
102 bool retrofit = retrofit_prop && retrofit_prop[0] != '\0' &&
103 GetBoolProperty(retrofit_prop, false);
Yifan Hong186bb682019-07-23 14:04:39 -0700104 bool enabled = GetBoolProperty(enable_prop, false);
105 if (retrofit && !enabled) {
106 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
107 << " is not. These sysprops are inconsistent. Assume that "
108 << enable_prop << " is true from now on.";
109 }
110 if (retrofit) {
111 return FeatureFlag(FeatureFlag::Value::RETROFIT);
112 }
113 if (enabled) {
114 return FeatureFlag(FeatureFlag::Value::LAUNCH);
115 }
116 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700117}
118
Yifan Hongb38e1af2019-10-17 14:59:22 -0700119DynamicPartitionControlAndroid::DynamicPartitionControlAndroid()
120 : dynamic_partitions_(
121 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400122 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)),
123 virtual_ab_compression_(GetFeatureFlag(kVirtualAbCompressionEnabled,
124 kVirtualAbCompressionRetrofit)) {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700125 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800126 snapshot_ = SnapshotManager::New();
Yifan Hongf9cb4492020-04-15 13:00:20 -0700127 } else {
128 snapshot_ = SnapshotManagerStub::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700129 }
Yifan Hongf9cb4492020-04-15 13:00:20 -0700130 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hongb38e1af2019-10-17 14:59:22 -0700131}
132
Yifan Hong186bb682019-07-23 14:04:39 -0700133FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700134 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800135}
136
Yifan Hong413d5722019-07-23 14:21:09 -0700137FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700138 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700139}
140
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400141FeatureFlag
142DynamicPartitionControlAndroid::GetVirtualAbCompressionFeatureFlag() {
143 return virtual_ab_compression_;
144}
145
Yifan Hongf5261562020-03-10 10:28:10 -0700146bool DynamicPartitionControlAndroid::OptimizeOperation(
147 const std::string& partition_name,
148 const InstallOperation& operation,
149 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000150 switch (operation.type()) {
151 case InstallOperation::SOURCE_COPY:
152 return target_supports_snapshot_ &&
153 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800154 mapped_devices_.count(partition_name +
155 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700156 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000157 break;
158 default:
159 break;
160 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000161 return false;
162}
163
Yifan Hong8546a712019-03-28 14:42:53 -0700164bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700165 const std::string& super_device,
166 const std::string& target_partition_name,
167 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700168 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700169 std::string* path) {
David Andersonbb90dfb2019-08-13 14:14:56 -0700170 CreateLogicalPartitionParams params = {
171 .block_device = super_device,
172 .metadata_slot = slot,
173 .partition_name = target_partition_name,
174 .force_writable = force_writable,
David Andersonbb90dfb2019-08-13 14:14:56 -0700175 };
Yifan Hong420db9b2019-07-23 20:50:33 -0700176 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700177 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700178 force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700179 // Only target partitions are mapped with force_writable. On Virtual
180 // A/B devices, target partitions may overlap with source partitions, so
181 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700182 // One exception is when /metadata is not mounted. Fallback to
183 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700184 params.timeout_ms = kMapSnapshotTimeout;
185 success = snapshot_->MapUpdateSnapshot(params, path);
186 } else {
187 params.timeout_ms = kMapTimeout;
188 success = CreateLogicalPartition(params, path);
189 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700190
Yifan Hong420db9b2019-07-23 20:50:33 -0700191 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700192 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
193 << super_device << " on device mapper.";
194 return false;
195 }
196 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700197 << " to device mapper (force_writable = " << force_writable
198 << "); device path at " << *path;
Yifan Hong537802d2018-08-15 13:15:42 -0700199 mapped_devices_.insert(target_partition_name);
200 return true;
201}
202
Yifan Hong8546a712019-03-28 14:42:53 -0700203bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
204 const std::string& super_device,
205 const std::string& target_partition_name,
206 uint32_t slot,
207 bool force_writable,
208 std::string* path) {
209 DmDeviceState state = GetState(target_partition_name);
210 if (state == DmDeviceState::ACTIVE) {
211 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
212 if (GetDmDevicePathByName(target_partition_name, path)) {
213 LOG(INFO) << target_partition_name
214 << " is mapped on device mapper: " << *path;
215 return true;
216 }
217 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
218 return false;
219 }
220 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
221 // the device might be mapped incorrectly before. Attempt to unmap it.
222 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
223 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
224 // should directly call GetDmDevicePathByName.
David Anderson4c891c92019-06-21 17:45:23 -0700225 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700226 LOG(ERROR) << target_partition_name
227 << " is mapped before the update, and it cannot be unmapped.";
228 return false;
229 }
230 state = GetState(target_partition_name);
231 if (state != DmDeviceState::INVALID) {
232 LOG(ERROR) << target_partition_name << " is unmapped but state is "
233 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
234 return false;
235 }
236 }
237 if (state == DmDeviceState::INVALID) {
238 return MapPartitionInternal(
239 super_device, target_partition_name, slot, force_writable, path);
240 }
241
242 LOG(ERROR) << target_partition_name
243 << " is mapped on device mapper but state is unknown: "
244 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
245 return false;
246}
247
Yifan Hong537802d2018-08-15 13:15:42 -0700248bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700249 const std::string& target_partition_name) {
Yifan Hong537802d2018-08-15 13:15:42 -0700250 if (DeviceMapper::Instance().GetState(target_partition_name) !=
251 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700252 // Partitions at target slot on non-Virtual A/B devices are mapped as
253 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
254 // preopt apps as dm-linear.
255 // Call DestroyLogicalPartition to handle these cases.
256 bool success = DestroyLogicalPartition(target_partition_name);
257
258 // On a Virtual A/B device, |target_partition_name| may be a leftover from
259 // a paused update. Clean up any underlying devices.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700260 if (ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700261 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700262 } else {
263 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
264 << ") because metadata is not mounted";
Yifan Hong420db9b2019-07-23 20:50:33 -0700265 }
266
267 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700268 LOG(ERROR) << "Cannot unmap " << target_partition_name
269 << " from device mapper.";
270 return false;
271 }
272 LOG(INFO) << "Successfully unmapped " << target_partition_name
273 << " from device mapper.";
274 }
275 mapped_devices_.erase(target_partition_name);
276 return true;
277}
278
Yifan Hongbae27842019-10-24 16:56:12 -0700279void DynamicPartitionControlAndroid::UnmapAllPartitions() {
Tao Bao8c4d0082019-08-08 08:56:16 -0700280 if (mapped_devices_.empty()) {
281 return;
282 }
Yifan Hong537802d2018-08-15 13:15:42 -0700283 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
284 // a copy is needed for the loop.
285 std::set<std::string> mapped = mapped_devices_;
286 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
287 for (const auto& partition_name : mapped) {
David Anderson4c891c92019-06-21 17:45:23 -0700288 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700289 }
290}
291
292void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700293 UnmapAllPartitions();
294 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700295}
296
297bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
298 return base::PathExists(base::FilePath(path));
299}
300
301android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
302 const std::string& name) {
303 return DeviceMapper::Instance().GetState(name);
304}
305
306bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
307 const std::string& name, std::string* path) {
308 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
309}
310
311std::unique_ptr<MetadataBuilder>
312DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700313 const std::string& super_device, uint32_t slot) {
314 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
315 if (builder == nullptr) {
316 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
317 << " in " << super_device;
318 return nullptr;
319 }
320 LOG(INFO) << "Loaded metadata from slot "
321 << BootControlInterface::SlotName(slot) << " in " << super_device;
322 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700323}
324
325std::unique_ptr<MetadataBuilder>
326DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800327 const std::string& super_device,
328 uint32_t source_slot,
329 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700330 bool always_keep_source_slot = !target_supports_snapshot_;
331 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
332 super_device,
333 source_slot,
334 target_slot,
335 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700336 if (builder == nullptr) {
337 LOG(WARNING) << "No metadata slot "
338 << BootControlInterface::SlotName(source_slot) << " in "
339 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700340 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700341 }
Tianjie24f96092020-06-30 12:26:25 -0700342 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700343 << BootControlInterface::SlotName(source_slot) << " in "
344 << super_device;
345 return builder;
346}
347
348bool DynamicPartitionControlAndroid::StoreMetadata(
349 const std::string& super_device,
350 MetadataBuilder* builder,
351 uint32_t target_slot) {
352 auto metadata = builder->Export();
353 if (metadata == nullptr) {
354 LOG(ERROR) << "Cannot export metadata to slot "
355 << BootControlInterface::SlotName(target_slot) << " in "
356 << super_device;
357 return false;
358 }
359
Yifan Hong186bb682019-07-23 14:04:39 -0700360 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800361 if (!FlashPartitionTable(super_device, *metadata)) {
362 LOG(ERROR) << "Cannot write metadata to " << super_device;
363 return false;
364 }
365 LOG(INFO) << "Written metadata to " << super_device;
366 } else {
367 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
368 LOG(ERROR) << "Cannot write metadata to slot "
369 << BootControlInterface::SlotName(target_slot) << " in "
370 << super_device;
371 return false;
372 }
373 LOG(INFO) << "Copied metadata to slot "
374 << BootControlInterface::SlotName(target_slot) << " in "
375 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700376 }
377
Yifan Hong537802d2018-08-15 13:15:42 -0700378 return true;
379}
380
381bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
382 // We can't use fs_mgr to look up |partition_name| because fstab
383 // doesn't list every slot partition (it uses the slotselect option
384 // to mask the suffix).
385 //
386 // We can however assume that there's an entry for the /misc mount
387 // point and use that to get the device file for the misc
388 // partition. This helps us locate the disk that |partition_name|
389 // resides on. From there we'll assume that a by-name scheme is used
390 // so we can just replace the trailing "misc" by the given
391 // |partition_name| and suffix corresponding to |slot|, e.g.
392 //
393 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
394 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
395 //
396 // If needed, it's possible to relax the by-name assumption in the
397 // future by trawling /sys/block looking for the appropriate sibling
398 // of misc and then finding an entry in /dev matching the sysfs
399 // entry.
400
401 std::string err, misc_device = get_bootloader_message_blk_device(&err);
402 if (misc_device.empty()) {
403 LOG(ERROR) << "Unable to get misc block device: " << err;
404 return false;
405 }
406
407 if (!utils::IsSymlink(misc_device.c_str())) {
408 LOG(ERROR) << "Device file " << misc_device << " for /misc "
409 << "is not a symlink.";
410 return false;
411 }
412 *out = base::FilePath(misc_device).DirName().value();
413 return true;
414}
Yifan Hong012508e2019-07-22 18:30:40 -0700415
416bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
417 uint32_t source_slot,
418 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700419 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800420 bool update,
421 uint64_t* required_size) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800422 source_slot_ = source_slot;
423 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800424 if (required_size != nullptr) {
425 *required_size = 0;
426 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800427
Yifan Hong3a1a5612019-11-05 16:34:32 -0800428 if (fs_mgr_overlayfs_is_setup()) {
429 // Non DAP devices can use overlayfs as well.
430 LOG(WARNING)
431 << "overlayfs overrides are active and can interfere with our "
432 "resources.\n"
433 << "run adb enable-verity to deactivate if required and try again.";
434 }
435
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700436 // If metadata is erased but not formatted, it is possible to not mount
437 // it in recovery. It is acceptable to skip mounting and choose fallback path
438 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
439 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700440
441 if (update) {
442 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
443 }
444
Yifan Hong3a1a5612019-11-05 16:34:32 -0800445 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
446 return true;
447 }
448
449 if (target_slot == source_slot) {
450 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
451 return false;
452 }
453
Yifan Hongf6f75c22020-07-31 15:20:25 -0700454 if (!SetTargetBuildVars(manifest)) {
455 return false;
456 }
457
Yifan Hong3a1a5612019-11-05 16:34:32 -0800458 // Although the current build supports dynamic partitions, the given payload
459 // doesn't use it for target partitions. This could happen when applying a
460 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800461 if (!is_target_dynamic_) {
462 return true;
463 }
464
Yifan Hongf0f4a912019-09-26 17:51:33 -0700465 if (!update)
466 return true;
467
Yifan Hongbae27842019-10-24 16:56:12 -0700468 bool delete_source = false;
469
Yifan Hong6d888562019-10-01 13:00:31 -0700470 if (GetVirtualAbFeatureFlag().IsEnabled()) {
471 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
472 // called before calling UnmapUpdateSnapshot.
473 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
474 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700475 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
476 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700477 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700478 if (PrepareSnapshotPartitionsForUpdate(
479 source_slot, target_slot, manifest, required_size)) {
480 return true;
481 }
482
483 // Virtual A/B device doing Virtual A/B update in Android mode must use
484 // snapshots.
485 if (!IsRecovery()) {
486 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
487 << "mode";
488 return false;
489 }
490
491 delete_source = true;
492 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
493 << "Attempt to overwrite existing partitions if possible";
494 } else {
495 // Downgrading to an non-Virtual A/B build or is secondary OTA.
496 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
497 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700498 }
Yifan Hongbae27842019-10-24 16:56:12 -0700499
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700500 // In recovery, if /metadata is not mounted, it is likely that metadata
501 // partition is erased and not formatted yet. After sideloading, when
502 // rebooting into the new version, init will erase metadata partition,
503 // hence the failure of CancelUpdate() can be ignored here.
504 // However, if metadata is mounted and CancelUpdate fails, sideloading
505 // should not proceed because during next boot, snapshots will overlay on
506 // the devices incorrectly.
507 if (ExpectMetadataMounted()) {
508 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
509 } else {
510 LOG(INFO) << "Skip canceling previous update because metadata is not "
511 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700512 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700513 }
Yifan Hongbae27842019-10-24 16:56:12 -0700514
Tianjie24f96092020-06-30 12:26:25 -0700515 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700516 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
517 source_slot, target_slot, manifest, delete_source));
518
519 if (required_size != nullptr) {
520 *required_size = 0;
521 }
522 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700523}
524
Yifan Hongf6f75c22020-07-31 15:20:25 -0700525bool DynamicPartitionControlAndroid::SetTargetBuildVars(
526 const DeltaArchiveManifest& manifest) {
527 // Precondition: current build supports dynamic partition.
528 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
529
530 bool is_target_dynamic =
531 !manifest.dynamic_partition_metadata().groups().empty();
532 bool target_supports_snapshot =
533 manifest.dynamic_partition_metadata().snapshot_enabled();
534
535 if (manifest.partial_update()) {
536 // Partial updates requires DAP. On partial updates that does not involve
537 // dynamic partitions, groups() can be empty, so also assume
538 // is_target_dynamic in this case. This assumption should be safe because we
539 // also check target_supports_snapshot below, which presumably also implies
540 // target build supports dynamic partition.
541 if (!is_target_dynamic) {
542 LOG(INFO) << "Assuming target build supports dynamic partitions for "
543 "partial updates.";
544 is_target_dynamic = true;
545 }
546
547 // Partial updates requires Virtual A/B. Double check that both current
548 // build and target build supports Virtual A/B.
549 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
550 LOG(ERROR) << "Partial update cannot be applied on a device that does "
551 "not support snapshots.";
552 return false;
553 }
554 if (!target_supports_snapshot) {
555 LOG(ERROR) << "Cannot apply partial update to a build that does not "
556 "support snapshots.";
557 return false;
558 }
559 }
560
561 // Store the flags.
562 is_target_dynamic_ = is_target_dynamic;
563 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
564 // snapshots would not work without dynamic partition.
565 if (is_target_dynamic_) {
566 target_supports_snapshot_ = target_supports_snapshot;
567 }
568 return true;
569}
570
Yifan Hong29692902020-03-26 12:47:05 -0700571namespace {
572// Try our best to erase AVB footer.
573class AvbFooterEraser {
574 public:
575 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
576 bool Erase() {
577 // Try to mark the block device read-only. Ignore any
578 // failure since this won't work when passing regular files.
579 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
580
581 fd_.reset(new EintrSafeFileDescriptor());
582 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
583 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
584
585 // Need to write end-AVB_FOOTER_SIZE to end.
586 static_assert(AVB_FOOTER_SIZE > 0);
587 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
588 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
589 uint64_t write_size = AVB_FOOTER_SIZE;
590 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
591 << (offset + write_size) << "] (" << write_size << " bytes)";
592 brillo::Blob zeros(write_size);
593 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
594 return true;
595 }
596 ~AvbFooterEraser() {
597 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
598 if (!fd_->Close()) {
599 LOG(WARNING) << "Failed to close fd for " << path_;
600 }
601 }
602
603 private:
604 std::string path_;
605 FileDescriptorPtr fd_;
606};
607
608} // namespace
609
610std::optional<bool>
611DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
612 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
613 if (prefix.empty()) {
614 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
615 return std::nullopt;
616 }
617 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
618 return IsAvbEnabledInFstab(path);
619}
620
621std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
622 const std::string& path) {
623 Fstab fstab;
624 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700625 PLOG(WARNING) << "Cannot read fstab from " << path;
626 if (errno == ENOENT) {
627 return false;
628 }
Yifan Hong29692902020-03-26 12:47:05 -0700629 return std::nullopt;
630 }
631 for (const auto& entry : fstab) {
632 if (!entry.avb_keys.empty()) {
633 return true;
634 }
635 }
636 return false;
637}
638
639bool DynamicPartitionControlAndroid::GetSystemOtherPath(
640 uint32_t source_slot,
641 uint32_t target_slot,
642 const std::string& partition_name_suffix,
643 std::string* path,
644 bool* should_unmap) {
645 path->clear();
646 *should_unmap = false;
647
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530648 // Check that AVB is enabled on system_other before erasing.
649 auto has_avb = IsAvbEnabledOnSystemOther();
650 TEST_AND_RETURN_FALSE(has_avb.has_value());
651 if (!has_avb.value()) {
652 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
653 return true;
654 }
Yifan Hong29692902020-03-26 12:47:05 -0700655
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530656 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700657 // Found unexpected avb_keys for system_other on devices retrofitting
658 // dynamic partitions. Previous crash in update_engine may leave logical
659 // partitions mapped on physical system_other partition. It is difficult to
660 // handle these cases. Just fail.
661 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
662 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
663 << "retrofit dynamic partitions. They should not have AVB "
664 << "enabled on system_other.";
665 return false;
666 }
667 }
668
669 std::string device_dir_str;
670 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
671 base::FilePath device_dir(device_dir_str);
672
673 // On devices without dynamic partition, search for static partitions.
674 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
675 *path = device_dir.Append(partition_name_suffix).value();
676 TEST_AND_RETURN_FALSE(DeviceExists(*path));
677 return true;
678 }
679
680 auto source_super_device =
681 device_dir.Append(GetSuperPartitionName(source_slot)).value();
682
683 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
684 if (builder == nullptr) {
685 if (IsRecovery()) {
686 // It might be corrupted for some reason. It should still be able to
687 // sideload.
688 LOG(WARNING) << "Super partition metadata cannot be read from the source "
689 << "slot, skip erasing.";
690 return true;
691 } else {
692 // Device has booted into Android mode, indicating that the super
693 // partition metadata should be there.
694 LOG(ERROR) << "Super partition metadata cannot be read from the source "
695 << "slot. This is unexpected on devices with dynamic "
696 << "partitions enabled.";
697 return false;
698 }
699 }
700 auto p = builder->FindPartition(partition_name_suffix);
701 if (p == nullptr) {
702 // If the source slot is flashed without system_other, it does not exist
703 // in super partition metadata at source slot. It is safe to skip it.
704 LOG(INFO) << "Can't find " << partition_name_suffix
705 << " in metadata source slot, skip erasing.";
706 return true;
707 }
708 // System_other created by flashing tools should be erased.
709 // If partition is created by update_engine (via NewForUpdate), it is a
710 // left-over partition from the previous update and does not contain
711 // system_other, hence there is no need to erase.
712 // Note the reverse is not necessary true. If the flag is not set, we don't
713 // know if the partition is created by update_engine or by flashing tools
714 // because older versions of super partition metadata does not contain this
715 // flag. It is okay to erase the AVB footer anyways.
716 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
717 LOG(INFO) << partition_name_suffix
718 << " does not contain system_other, skip erasing.";
719 return true;
720 }
721
Yifan Hong64331b32020-05-13 16:50:40 -0700722 if (p->size() < AVB_FOOTER_SIZE) {
723 LOG(INFO) << partition_name_suffix << " has length " << p->size()
724 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
725 << "), skip erasing.";
726 return true;
727 }
728
Yifan Hong29692902020-03-26 12:47:05 -0700729 // Delete any pre-existing device with name |partition_name_suffix| and
730 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700731 // In recovery, metadata might not be mounted, and
732 // UnmapPartitionOnDeviceMapper might fail. However,
733 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700734 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
735 // Use CreateLogicalPartition directly to avoid mapping with existing
736 // snapshots.
737 CreateLogicalPartitionParams params = {
738 .block_device = source_super_device,
739 .metadata_slot = source_slot,
740 .partition_name = partition_name_suffix,
741 .force_writable = true,
742 .timeout_ms = kMapTimeout,
743 };
744 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
745 *should_unmap = true;
746 return true;
747}
748
749bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
750 uint32_t source_slot, uint32_t target_slot) {
751 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
752
753 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
754 const std::string partition_name_suffix = "system" + target_suffix;
755
756 std::string path;
757 bool should_unmap = false;
758
759 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
760 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
761
762 if (path.empty()) {
763 return true;
764 }
765
766 bool ret = AvbFooterEraser(path).Erase();
767
768 // Delete |partition_name_suffix| from device mapper and from
769 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700770 // In recovery, metadata might not be mounted, and
771 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
772 // should be called. If DestroyLogicalPartition does fail, it is still okay
773 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700774 if (should_unmap) {
775 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
776 }
777
778 return ret;
779}
780
Yifan Hong420db9b2019-07-23 20:50:33 -0700781bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
782 uint32_t source_slot,
783 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700784 const DeltaArchiveManifest& manifest,
785 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700786 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
787
788 // Unmap all the target dynamic partitions because they would become
789 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700790 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
791 for (const auto& partition_name : group.partition_names()) {
792 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700793 return false;
794 }
795 }
796 }
797
798 std::string device_dir_str;
799 if (!GetDeviceDir(&device_dir_str)) {
800 return false;
801 }
802 base::FilePath device_dir(device_dir_str);
803 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700804 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700805
806 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
807 if (builder == nullptr) {
808 LOG(ERROR) << "No metadata at "
809 << BootControlInterface::SlotName(source_slot);
810 return false;
811 }
812
Yifan Hongbae27842019-10-24 16:56:12 -0700813 if (delete_source) {
814 TEST_AND_RETURN_FALSE(
815 DeleteSourcePartitions(builder.get(), source_slot, manifest));
816 }
817
Yifan Hong13d41cb2019-09-16 13:18:22 -0700818 if (!UpdatePartitionMetadata(builder.get(), target_slot, manifest)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700819 return false;
820 }
821
822 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700823 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700824 return StoreMetadata(target_device, builder.get(), target_slot);
825}
826
Yifan Hong420db9b2019-07-23 20:50:33 -0700827bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
828 uint32_t source_slot,
829 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800830 const DeltaArchiveManifest& manifest,
831 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700832 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Yifan Hong420db9b2019-07-23 20:50:33 -0700833 if (!snapshot_->BeginUpdate()) {
834 LOG(ERROR) << "Cannot begin new update.";
835 return false;
836 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800837 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
838 if (!ret) {
839 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
840 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800841 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800842 *required_size = ret.required_size();
843 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700844 return false;
845 }
846 return true;
847}
848
Yifan Hong700d7c12019-07-23 20:49:16 -0700849std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
850 uint32_t slot) {
851 return fs_mgr_get_super_partition_name(slot);
852}
853
Yifan Hong012508e2019-07-22 18:30:40 -0700854bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
855 MetadataBuilder* builder,
856 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700857 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700858 // Check preconditions.
859 CHECK(!GetVirtualAbFeatureFlag().IsEnabled() || IsRecovery())
860 << "UpdatePartitionMetadata is called on a Virtual A/B device "
861 "but source partitions is not deleted. This is not allowed.";
862
Yifan Honga4e7da32019-09-30 18:25:03 -0700863 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
864 // COW group needs to be deleted to ensure there are enough space to create
865 // target partitions.
866 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
867
Yifan Hong012508e2019-07-22 18:30:40 -0700868 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
869 DeleteGroupsWithSuffix(builder, target_suffix);
870
871 uint64_t total_size = 0;
Yifan Hong13d41cb2019-09-16 13:18:22 -0700872 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
873 total_size += group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700874 }
875
876 std::string expr;
877 uint64_t allocatable_space = builder->AllocatableSpace();
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700878 // On device retrofitting dynamic partitions, allocatable_space = super.
879 // On device launching dynamic partitions w/o VAB,
880 // allocatable_space = super / 2.
881 // On device launching dynamic partitions with VAB, allocatable_space = super.
882 if (!GetDynamicPartitionsFeatureFlag().IsRetrofit() &&
883 !GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hong012508e2019-07-22 18:30:40 -0700884 allocatable_space /= 2;
885 expr = "half of ";
886 }
887 if (total_size > allocatable_space) {
888 LOG(ERROR) << "The maximum size of all groups with suffix " << target_suffix
889 << " (" << total_size << ") has exceeded " << expr
890 << "allocatable space for dynamic partitions "
891 << allocatable_space << ".";
892 return false;
893 }
894
Yifan Hong13d41cb2019-09-16 13:18:22 -0700895 // name of partition(e.g. "system") -> size in bytes
896 std::map<std::string, uint64_t> partition_sizes;
897 for (const auto& partition : manifest.partitions()) {
898 partition_sizes.emplace(partition.partition_name(),
899 partition.new_partition_info().size());
900 }
901
902 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
903 auto group_name_suffix = group.name() + target_suffix;
904 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -0700905 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700906 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700907 return false;
908 }
909 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700910 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700911
Yifan Hong13d41cb2019-09-16 13:18:22 -0700912 for (const auto& partition_name : group.partition_names()) {
913 auto partition_sizes_it = partition_sizes.find(partition_name);
914 if (partition_sizes_it == partition_sizes.end()) {
915 // TODO(tbao): Support auto-filling partition info for framework-only
916 // OTA.
917 LOG(ERROR) << "dynamic_partition_metadata contains partition "
918 << partition_name << " but it is not part of the manifest. "
919 << "This is not supported.";
920 return false;
921 }
922 uint64_t partition_size = partition_sizes_it->second;
923
924 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -0700925 Partition* p = builder->AddPartition(
926 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
927 if (!p) {
928 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
929 << " to group " << group_name_suffix;
930 return false;
931 }
Yifan Hong13d41cb2019-09-16 13:18:22 -0700932 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700933 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -0700934 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -0700935 return false;
936 }
937 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700938 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -0700939 }
940 }
941
942 return true;
943}
944
Yifan Hong7b3910a2020-03-24 17:47:32 -0700945bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700946 if (ExpectMetadataMounted()) {
947 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
948 LOG(INFO) << "Snapshot writes are done.";
949 return snapshot_->FinishedSnapshotWrites(powerwash_required);
950 }
951 } else {
952 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
953 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -0700954 }
955 return true;
Yifan Honga33bca42019-09-03 20:29:45 -0700956}
957
Yifan Hong3a1a5612019-11-05 16:34:32 -0800958bool DynamicPartitionControlAndroid::GetPartitionDevice(
959 const std::string& partition_name,
960 uint32_t slot,
961 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -0700962 bool not_in_payload,
963 std::string* device,
964 bool* is_dynamic) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800965 const auto& partition_name_suffix =
966 partition_name + SlotSuffixForSlotNumber(slot);
967 std::string device_dir_str;
968 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
969 base::FilePath device_dir(device_dir_str);
970
Tianjie51a5a392020-06-03 14:39:32 -0700971 if (is_dynamic) {
972 *is_dynamic = false;
973 }
974
Yifan Hong3a1a5612019-11-05 16:34:32 -0800975 // When looking up target partition devices, treat them as static if the
976 // current payload doesn't encode them as dynamic partitions. This may happen
977 // when applying a retrofit update on top of a dynamic-partitions-enabled
978 // build.
979 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
980 (slot == current_slot || is_target_dynamic_)) {
Tianjie51a5a392020-06-03 14:39:32 -0700981 switch (GetDynamicPartitionDevice(device_dir,
982 partition_name_suffix,
983 slot,
984 current_slot,
985 not_in_payload,
986 device)) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800987 case DynamicPartitionDeviceStatus::SUCCESS:
Tianjie51a5a392020-06-03 14:39:32 -0700988 if (is_dynamic) {
989 *is_dynamic = true;
990 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800991 return true;
992 case DynamicPartitionDeviceStatus::TRY_STATIC:
993 break;
994 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
995 default:
996 return false;
997 }
998 }
999 base::FilePath path = device_dir.Append(partition_name_suffix);
1000 if (!DeviceExists(path.value())) {
1001 LOG(ERROR) << "Device file " << path.value() << " does not exist.";
1002 return false;
1003 }
1004
1005 *device = path.value();
1006 return true;
1007}
1008
Tianjie51a5a392020-06-03 14:39:32 -07001009bool DynamicPartitionControlAndroid::GetPartitionDevice(
1010 const std::string& partition_name,
1011 uint32_t slot,
1012 uint32_t current_slot,
1013 std::string* device) {
1014 return GetPartitionDevice(
1015 partition_name, slot, current_slot, false, device, nullptr);
1016}
1017
Yifan Hong3a1a5612019-11-05 16:34:32 -08001018bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1019 const base::FilePath& device_dir,
1020 uint32_t current_slot,
1021 const std::string& partition_name_suffix) {
1022 std::string source_device =
1023 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1024 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1025 return source_metadata->HasBlockDevice(partition_name_suffix);
1026}
1027
1028DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1029DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1030 const base::FilePath& device_dir,
1031 const std::string& partition_name_suffix,
1032 uint32_t slot,
1033 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001034 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001035 std::string* device) {
1036 std::string super_device =
1037 device_dir.Append(GetSuperPartitionName(slot)).value();
1038
1039 auto builder = LoadMetadataBuilder(super_device, slot);
1040 if (builder == nullptr) {
1041 LOG(ERROR) << "No metadata in slot "
1042 << BootControlInterface::SlotName(slot);
1043 return DynamicPartitionDeviceStatus::ERROR;
1044 }
1045 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1046 LOG(INFO) << partition_name_suffix
1047 << " is not in super partition metadata.";
1048
1049 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1050 LOG(ERROR) << "The static partition " << partition_name_suffix
1051 << " is a block device for current metadata."
1052 << "It cannot be used as a logical partition.";
1053 return DynamicPartitionDeviceStatus::ERROR;
1054 }
1055
1056 return DynamicPartitionDeviceStatus::TRY_STATIC;
1057 }
1058
1059 if (slot == current_slot) {
1060 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1061 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1062 << "not mapped. Now try to map it.";
1063 } else {
1064 if (GetDmDevicePathByName(partition_name_suffix, device)) {
1065 LOG(INFO) << partition_name_suffix
1066 << " is mapped on device mapper: " << *device;
1067 return DynamicPartitionDeviceStatus::SUCCESS;
1068 }
1069 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1070 return DynamicPartitionDeviceStatus::ERROR;
1071 }
1072 }
1073
Tianjie51a5a392020-06-03 14:39:32 -07001074 bool force_writable = (slot != current_slot) && !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001075 if (MapPartitionOnDeviceMapper(
1076 super_device, partition_name_suffix, slot, force_writable, device)) {
1077 return DynamicPartitionDeviceStatus::SUCCESS;
1078 }
1079 return DynamicPartitionDeviceStatus::ERROR;
1080}
1081
Yifan Hong6eec9952019-12-04 13:12:01 -08001082void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1083 const std::set<std::string>& fake) {
1084 mapped_devices_ = fake;
1085}
1086
Yifan Hongbae27842019-10-24 16:56:12 -07001087bool DynamicPartitionControlAndroid::IsRecovery() {
1088 return kIsRecovery;
1089}
1090
1091static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1092 const auto& partitions = manifest.partitions();
1093 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1094 return p.has_old_partition_info();
1095 });
1096}
1097
1098bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1099 MetadataBuilder* builder,
1100 uint32_t source_slot,
1101 const DeltaArchiveManifest& manifest) {
1102 TEST_AND_RETURN_FALSE(IsRecovery());
1103
1104 if (IsIncrementalUpdate(manifest)) {
1105 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1106 << "be created.";
1107 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1108 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1109 << " Virtual A/B is not supported.";
1110 }
1111 return false;
1112 }
1113
1114 LOG(INFO) << "Will overwrite existing partitions. Slot "
1115 << BootControlInterface::SlotName(source_slot)
1116 << "may be unbootable until update finishes!";
1117 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1118 DeleteGroupsWithSuffix(builder, source_suffix);
1119
1120 return true;
1121}
1122
Yifan Hong90965502020-02-19 15:22:47 -08001123std::unique_ptr<AbstractAction>
1124DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1125 BootControlInterface* boot_control,
1126 PrefsInterface* prefs,
1127 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1128 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1129 return std::make_unique<NoOpAction>();
1130 }
1131 return std::make_unique<CleanupPreviousUpdateAction>(
1132 prefs, boot_control, snapshot_.get(), delegate);
1133}
1134
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001135bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1136 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1137 return true;
1138 }
1139
1140 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1141 TEST_AND_RETURN_FALSE(prefs != nullptr);
1142
1143 // If the device has already booted into the target slot,
1144 // ResetUpdateProgress may pass but CancelUpdate fails.
1145 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1146 // space when it is done.
1147 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1148 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1149
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001150 if (ExpectMetadataMounted()) {
1151 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1152 } else {
1153 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1154 << "not mounted";
1155 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001156
1157 return true;
1158}
1159
Tianjie99d570d2020-06-04 14:57:19 -07001160bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
1161 uint32_t current_slot, std::vector<std::string>* partitions) {
1162 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
1163 LOG(ERROR) << "Dynamic partition is not enabled";
1164 return false;
1165 }
1166
1167 std::string device_dir_str;
1168 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1169 base::FilePath device_dir(device_dir_str);
1170 auto super_device =
1171 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1172 auto builder = LoadMetadataBuilder(super_device, current_slot);
1173 TEST_AND_RETURN_FALSE(builder != nullptr);
1174
1175 std::vector<std::string> result;
1176 auto suffix = SlotSuffixForSlotNumber(current_slot);
1177 for (const auto& group : builder->ListGroups()) {
1178 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1179 std::string_view partition_name = partition->name();
1180 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1181 continue;
1182 }
1183 result.emplace_back(partition_name);
1184 }
1185 }
1186 *partitions = std::move(result);
1187 return true;
1188}
1189
Tianjie24f96092020-06-30 12:26:25 -07001190bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1191 uint32_t source_slot,
1192 uint32_t target_slot,
1193 const std::vector<std::string>& partitions) {
1194 std::string device_dir_str;
1195 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1196 base::FilePath device_dir(device_dir_str);
1197
1198 auto source_super_device =
1199 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1200 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1201 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1202
1203 auto target_super_device =
1204 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1205 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1206 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1207
1208 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1209 *source_builder, source_slot, *target_builder, target_slot, partitions);
1210}
1211
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001212bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1213 // No need to mount metadata for non-Virtual A/B devices.
1214 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1215 return false;
1216 }
1217 // Intentionally not checking |metadata_device_| in Android mode.
1218 // /metadata should always be mounted in Android mode. If it isn't, let caller
1219 // fails when calling into SnapshotManager.
1220 if (!IsRecovery()) {
1221 return true;
1222 }
1223 // In recovery mode, explicitly check |metadata_device_|.
1224 return metadata_device_ != nullptr;
1225}
1226
1227bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1228 // No need to mount metadata for non-Virtual A/B devices.
1229 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1230 return true;
1231 }
1232
1233 if (metadata_device_ == nullptr) {
1234 metadata_device_ = snapshot_->EnsureMetadataMounted();
1235 }
1236 return metadata_device_ != nullptr;
1237}
1238
Yifan Hong537802d2018-08-15 13:15:42 -07001239} // namespace chromeos_update_engine