blob: 1fb2c2534fc4bd89fc64d9880d68a5f788fe1ed9 [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 Hong537802d2018-08-15 13:15:42 -070089DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
Yifan Hongbae27842019-10-24 16:56:12 -070090 Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -070091}
92
Yifan Hong186bb682019-07-23 14:04:39 -070093static FeatureFlag GetFeatureFlag(const char* enable_prop,
94 const char* retrofit_prop) {
Kelvin Zhangda1b3142020-09-24 17:09:02 -040095 // Default retrofit to false if retrofit_prop is empty.
96 bool retrofit = retrofit_prop && retrofit_prop[0] != '\0' &&
97 GetBoolProperty(retrofit_prop, false);
Yifan Hong186bb682019-07-23 14:04:39 -070098 bool enabled = GetBoolProperty(enable_prop, false);
99 if (retrofit && !enabled) {
100 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
101 << " is not. These sysprops are inconsistent. Assume that "
102 << enable_prop << " is true from now on.";
103 }
104 if (retrofit) {
105 return FeatureFlag(FeatureFlag::Value::RETROFIT);
106 }
107 if (enabled) {
108 return FeatureFlag(FeatureFlag::Value::LAUNCH);
109 }
110 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700111}
112
Yifan Hongb38e1af2019-10-17 14:59:22 -0700113DynamicPartitionControlAndroid::DynamicPartitionControlAndroid()
114 : dynamic_partitions_(
115 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400116 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)),
117 virtual_ab_compression_(GetFeatureFlag(kVirtualAbCompressionEnabled,
118 kVirtualAbCompressionRetrofit)) {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700119 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800120 snapshot_ = SnapshotManager::New();
Yifan Hongf9cb4492020-04-15 13:00:20 -0700121 } else {
122 snapshot_ = SnapshotManagerStub::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700123 }
Yifan Hongf9cb4492020-04-15 13:00:20 -0700124 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hongb38e1af2019-10-17 14:59:22 -0700125}
126
Yifan Hong186bb682019-07-23 14:04:39 -0700127FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700128 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800129}
130
Yifan Hong413d5722019-07-23 14:21:09 -0700131FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700132 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700133}
134
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400135FeatureFlag
136DynamicPartitionControlAndroid::GetVirtualAbCompressionFeatureFlag() {
137 return virtual_ab_compression_;
138}
139
Yifan Hongf5261562020-03-10 10:28:10 -0700140bool DynamicPartitionControlAndroid::OptimizeOperation(
141 const std::string& partition_name,
142 const InstallOperation& operation,
143 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000144 switch (operation.type()) {
145 case InstallOperation::SOURCE_COPY:
146 return target_supports_snapshot_ &&
147 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800148 mapped_devices_.count(partition_name +
149 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700150 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000151 break;
152 default:
153 break;
154 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000155 return false;
156}
157
Yifan Hong8546a712019-03-28 14:42:53 -0700158bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700159 const std::string& super_device,
160 const std::string& target_partition_name,
161 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700162 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700163 std::string* path) {
David Andersonbb90dfb2019-08-13 14:14:56 -0700164 CreateLogicalPartitionParams params = {
165 .block_device = super_device,
166 .metadata_slot = slot,
167 .partition_name = target_partition_name,
168 .force_writable = force_writable,
David Andersonbb90dfb2019-08-13 14:14:56 -0700169 };
Yifan Hong420db9b2019-07-23 20:50:33 -0700170 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700171 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700172 force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700173 // Only target partitions are mapped with force_writable. On Virtual
174 // A/B devices, target partitions may overlap with source partitions, so
175 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700176 // One exception is when /metadata is not mounted. Fallback to
177 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700178 params.timeout_ms = kMapSnapshotTimeout;
179 success = snapshot_->MapUpdateSnapshot(params, path);
180 } else {
181 params.timeout_ms = kMapTimeout;
182 success = CreateLogicalPartition(params, path);
183 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700184
Yifan Hong420db9b2019-07-23 20:50:33 -0700185 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700186 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
187 << super_device << " on device mapper.";
188 return false;
189 }
190 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700191 << " to device mapper (force_writable = " << force_writable
192 << "); device path at " << *path;
Yifan Hong537802d2018-08-15 13:15:42 -0700193 mapped_devices_.insert(target_partition_name);
194 return true;
195}
196
Yifan Hong8546a712019-03-28 14:42:53 -0700197bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
198 const std::string& super_device,
199 const std::string& target_partition_name,
200 uint32_t slot,
201 bool force_writable,
202 std::string* path) {
203 DmDeviceState state = GetState(target_partition_name);
204 if (state == DmDeviceState::ACTIVE) {
205 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
206 if (GetDmDevicePathByName(target_partition_name, path)) {
207 LOG(INFO) << target_partition_name
208 << " is mapped on device mapper: " << *path;
209 return true;
210 }
211 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
212 return false;
213 }
214 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
215 // the device might be mapped incorrectly before. Attempt to unmap it.
216 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
217 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
218 // should directly call GetDmDevicePathByName.
David Anderson4c891c92019-06-21 17:45:23 -0700219 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700220 LOG(ERROR) << target_partition_name
221 << " is mapped before the update, and it cannot be unmapped.";
222 return false;
223 }
224 state = GetState(target_partition_name);
225 if (state != DmDeviceState::INVALID) {
226 LOG(ERROR) << target_partition_name << " is unmapped but state is "
227 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
228 return false;
229 }
230 }
231 if (state == DmDeviceState::INVALID) {
232 return MapPartitionInternal(
233 super_device, target_partition_name, slot, force_writable, path);
234 }
235
236 LOG(ERROR) << target_partition_name
237 << " is mapped on device mapper but state is unknown: "
238 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
239 return false;
240}
241
Yifan Hong537802d2018-08-15 13:15:42 -0700242bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700243 const std::string& target_partition_name) {
Yifan Hong537802d2018-08-15 13:15:42 -0700244 if (DeviceMapper::Instance().GetState(target_partition_name) !=
245 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700246 // Partitions at target slot on non-Virtual A/B devices are mapped as
247 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
248 // preopt apps as dm-linear.
249 // Call DestroyLogicalPartition to handle these cases.
250 bool success = DestroyLogicalPartition(target_partition_name);
251
252 // On a Virtual A/B device, |target_partition_name| may be a leftover from
253 // a paused update. Clean up any underlying devices.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700254 if (ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700255 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700256 } else {
257 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
258 << ") because metadata is not mounted";
Yifan Hong420db9b2019-07-23 20:50:33 -0700259 }
260
261 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700262 LOG(ERROR) << "Cannot unmap " << target_partition_name
263 << " from device mapper.";
264 return false;
265 }
266 LOG(INFO) << "Successfully unmapped " << target_partition_name
267 << " from device mapper.";
268 }
269 mapped_devices_.erase(target_partition_name);
270 return true;
271}
272
Yifan Hongbae27842019-10-24 16:56:12 -0700273void DynamicPartitionControlAndroid::UnmapAllPartitions() {
Tao Bao8c4d0082019-08-08 08:56:16 -0700274 if (mapped_devices_.empty()) {
275 return;
276 }
Yifan Hong537802d2018-08-15 13:15:42 -0700277 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
278 // a copy is needed for the loop.
279 std::set<std::string> mapped = mapped_devices_;
280 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
281 for (const auto& partition_name : mapped) {
David Anderson4c891c92019-06-21 17:45:23 -0700282 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700283 }
284}
285
286void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700287 UnmapAllPartitions();
288 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700289}
290
291bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
292 return base::PathExists(base::FilePath(path));
293}
294
295android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
296 const std::string& name) {
297 return DeviceMapper::Instance().GetState(name);
298}
299
300bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
301 const std::string& name, std::string* path) {
302 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
303}
304
305std::unique_ptr<MetadataBuilder>
306DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700307 const std::string& super_device, uint32_t slot) {
308 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
309 if (builder == nullptr) {
310 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
311 << " in " << super_device;
312 return nullptr;
313 }
314 LOG(INFO) << "Loaded metadata from slot "
315 << BootControlInterface::SlotName(slot) << " in " << super_device;
316 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700317}
318
319std::unique_ptr<MetadataBuilder>
320DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800321 const std::string& super_device,
322 uint32_t source_slot,
323 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700324 bool always_keep_source_slot = !target_supports_snapshot_;
325 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
326 super_device,
327 source_slot,
328 target_slot,
329 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700330 if (builder == nullptr) {
331 LOG(WARNING) << "No metadata slot "
332 << BootControlInterface::SlotName(source_slot) << " in "
333 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700334 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700335 }
Tianjie24f96092020-06-30 12:26:25 -0700336 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700337 << BootControlInterface::SlotName(source_slot) << " in "
338 << super_device;
339 return builder;
340}
341
342bool DynamicPartitionControlAndroid::StoreMetadata(
343 const std::string& super_device,
344 MetadataBuilder* builder,
345 uint32_t target_slot) {
346 auto metadata = builder->Export();
347 if (metadata == nullptr) {
348 LOG(ERROR) << "Cannot export metadata to slot "
349 << BootControlInterface::SlotName(target_slot) << " in "
350 << super_device;
351 return false;
352 }
353
Yifan Hong186bb682019-07-23 14:04:39 -0700354 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800355 if (!FlashPartitionTable(super_device, *metadata)) {
356 LOG(ERROR) << "Cannot write metadata to " << super_device;
357 return false;
358 }
359 LOG(INFO) << "Written metadata to " << super_device;
360 } else {
361 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
362 LOG(ERROR) << "Cannot write metadata to slot "
363 << BootControlInterface::SlotName(target_slot) << " in "
364 << super_device;
365 return false;
366 }
367 LOG(INFO) << "Copied metadata to slot "
368 << BootControlInterface::SlotName(target_slot) << " in "
369 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700370 }
371
Yifan Hong537802d2018-08-15 13:15:42 -0700372 return true;
373}
374
375bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
376 // We can't use fs_mgr to look up |partition_name| because fstab
377 // doesn't list every slot partition (it uses the slotselect option
378 // to mask the suffix).
379 //
380 // We can however assume that there's an entry for the /misc mount
381 // point and use that to get the device file for the misc
382 // partition. This helps us locate the disk that |partition_name|
383 // resides on. From there we'll assume that a by-name scheme is used
384 // so we can just replace the trailing "misc" by the given
385 // |partition_name| and suffix corresponding to |slot|, e.g.
386 //
387 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
388 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
389 //
390 // If needed, it's possible to relax the by-name assumption in the
391 // future by trawling /sys/block looking for the appropriate sibling
392 // of misc and then finding an entry in /dev matching the sysfs
393 // entry.
394
395 std::string err, misc_device = get_bootloader_message_blk_device(&err);
396 if (misc_device.empty()) {
397 LOG(ERROR) << "Unable to get misc block device: " << err;
398 return false;
399 }
400
401 if (!utils::IsSymlink(misc_device.c_str())) {
402 LOG(ERROR) << "Device file " << misc_device << " for /misc "
403 << "is not a symlink.";
404 return false;
405 }
406 *out = base::FilePath(misc_device).DirName().value();
407 return true;
408}
Yifan Hong012508e2019-07-22 18:30:40 -0700409
410bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
411 uint32_t source_slot,
412 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700413 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800414 bool update,
415 uint64_t* required_size) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800416 source_slot_ = source_slot;
417 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800418 if (required_size != nullptr) {
419 *required_size = 0;
420 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800421
Yifan Hong3a1a5612019-11-05 16:34:32 -0800422 if (fs_mgr_overlayfs_is_setup()) {
423 // Non DAP devices can use overlayfs as well.
424 LOG(WARNING)
425 << "overlayfs overrides are active and can interfere with our "
426 "resources.\n"
427 << "run adb enable-verity to deactivate if required and try again.";
428 }
429
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700430 // If metadata is erased but not formatted, it is possible to not mount
431 // it in recovery. It is acceptable to skip mounting and choose fallback path
432 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
433 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700434
435 if (update) {
436 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
437 }
438
Yifan Hong3a1a5612019-11-05 16:34:32 -0800439 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
440 return true;
441 }
442
443 if (target_slot == source_slot) {
444 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
445 return false;
446 }
447
Yifan Hongf6f75c22020-07-31 15:20:25 -0700448 if (!SetTargetBuildVars(manifest)) {
449 return false;
450 }
451
Yifan Hong3a1a5612019-11-05 16:34:32 -0800452 // Although the current build supports dynamic partitions, the given payload
453 // doesn't use it for target partitions. This could happen when applying a
454 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800455 if (!is_target_dynamic_) {
456 return true;
457 }
458
Yifan Hongf0f4a912019-09-26 17:51:33 -0700459 if (!update)
460 return true;
461
Yifan Hongbae27842019-10-24 16:56:12 -0700462 bool delete_source = false;
463
Yifan Hong6d888562019-10-01 13:00:31 -0700464 if (GetVirtualAbFeatureFlag().IsEnabled()) {
465 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
466 // called before calling UnmapUpdateSnapshot.
467 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
468 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700469 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
470 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700471 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700472 if (PrepareSnapshotPartitionsForUpdate(
473 source_slot, target_slot, manifest, required_size)) {
474 return true;
475 }
476
477 // Virtual A/B device doing Virtual A/B update in Android mode must use
478 // snapshots.
479 if (!IsRecovery()) {
480 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
481 << "mode";
482 return false;
483 }
484
485 delete_source = true;
486 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
487 << "Attempt to overwrite existing partitions if possible";
488 } else {
489 // Downgrading to an non-Virtual A/B build or is secondary OTA.
490 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
491 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700492 }
Yifan Hongbae27842019-10-24 16:56:12 -0700493
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700494 // In recovery, if /metadata is not mounted, it is likely that metadata
495 // partition is erased and not formatted yet. After sideloading, when
496 // rebooting into the new version, init will erase metadata partition,
497 // hence the failure of CancelUpdate() can be ignored here.
498 // However, if metadata is mounted and CancelUpdate fails, sideloading
499 // should not proceed because during next boot, snapshots will overlay on
500 // the devices incorrectly.
501 if (ExpectMetadataMounted()) {
502 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
503 } else {
504 LOG(INFO) << "Skip canceling previous update because metadata is not "
505 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700506 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700507 }
Yifan Hongbae27842019-10-24 16:56:12 -0700508
Tianjie24f96092020-06-30 12:26:25 -0700509 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700510 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
511 source_slot, target_slot, manifest, delete_source));
512
513 if (required_size != nullptr) {
514 *required_size = 0;
515 }
516 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700517}
518
Yifan Hongf6f75c22020-07-31 15:20:25 -0700519bool DynamicPartitionControlAndroid::SetTargetBuildVars(
520 const DeltaArchiveManifest& manifest) {
521 // Precondition: current build supports dynamic partition.
522 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
523
524 bool is_target_dynamic =
525 !manifest.dynamic_partition_metadata().groups().empty();
526 bool target_supports_snapshot =
527 manifest.dynamic_partition_metadata().snapshot_enabled();
528
529 if (manifest.partial_update()) {
530 // Partial updates requires DAP. On partial updates that does not involve
531 // dynamic partitions, groups() can be empty, so also assume
532 // is_target_dynamic in this case. This assumption should be safe because we
533 // also check target_supports_snapshot below, which presumably also implies
534 // target build supports dynamic partition.
535 if (!is_target_dynamic) {
536 LOG(INFO) << "Assuming target build supports dynamic partitions for "
537 "partial updates.";
538 is_target_dynamic = true;
539 }
540
541 // Partial updates requires Virtual A/B. Double check that both current
542 // build and target build supports Virtual A/B.
543 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
544 LOG(ERROR) << "Partial update cannot be applied on a device that does "
545 "not support snapshots.";
546 return false;
547 }
548 if (!target_supports_snapshot) {
549 LOG(ERROR) << "Cannot apply partial update to a build that does not "
550 "support snapshots.";
551 return false;
552 }
553 }
554
555 // Store the flags.
556 is_target_dynamic_ = is_target_dynamic;
557 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
558 // snapshots would not work without dynamic partition.
559 if (is_target_dynamic_) {
560 target_supports_snapshot_ = target_supports_snapshot;
561 }
562 return true;
563}
564
Yifan Hong29692902020-03-26 12:47:05 -0700565namespace {
566// Try our best to erase AVB footer.
567class AvbFooterEraser {
568 public:
569 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
570 bool Erase() {
571 // Try to mark the block device read-only. Ignore any
572 // failure since this won't work when passing regular files.
573 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
574
575 fd_.reset(new EintrSafeFileDescriptor());
576 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
577 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
578
579 // Need to write end-AVB_FOOTER_SIZE to end.
580 static_assert(AVB_FOOTER_SIZE > 0);
581 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
582 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
583 uint64_t write_size = AVB_FOOTER_SIZE;
584 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
585 << (offset + write_size) << "] (" << write_size << " bytes)";
586 brillo::Blob zeros(write_size);
587 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
588 return true;
589 }
590 ~AvbFooterEraser() {
591 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
592 if (!fd_->Close()) {
593 LOG(WARNING) << "Failed to close fd for " << path_;
594 }
595 }
596
597 private:
598 std::string path_;
599 FileDescriptorPtr fd_;
600};
601
602} // namespace
603
604std::optional<bool>
605DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
606 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
607 if (prefix.empty()) {
608 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
609 return std::nullopt;
610 }
611 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
612 return IsAvbEnabledInFstab(path);
613}
614
615std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
616 const std::string& path) {
617 Fstab fstab;
618 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700619 PLOG(WARNING) << "Cannot read fstab from " << path;
620 if (errno == ENOENT) {
621 return false;
622 }
Yifan Hong29692902020-03-26 12:47:05 -0700623 return std::nullopt;
624 }
625 for (const auto& entry : fstab) {
626 if (!entry.avb_keys.empty()) {
627 return true;
628 }
629 }
630 return false;
631}
632
633bool DynamicPartitionControlAndroid::GetSystemOtherPath(
634 uint32_t source_slot,
635 uint32_t target_slot,
636 const std::string& partition_name_suffix,
637 std::string* path,
638 bool* should_unmap) {
639 path->clear();
640 *should_unmap = false;
641
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530642 // Check that AVB is enabled on system_other before erasing.
643 auto has_avb = IsAvbEnabledOnSystemOther();
644 TEST_AND_RETURN_FALSE(has_avb.has_value());
645 if (!has_avb.value()) {
646 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
647 return true;
648 }
Yifan Hong29692902020-03-26 12:47:05 -0700649
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530650 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700651 // Found unexpected avb_keys for system_other on devices retrofitting
652 // dynamic partitions. Previous crash in update_engine may leave logical
653 // partitions mapped on physical system_other partition. It is difficult to
654 // handle these cases. Just fail.
655 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
656 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
657 << "retrofit dynamic partitions. They should not have AVB "
658 << "enabled on system_other.";
659 return false;
660 }
661 }
662
663 std::string device_dir_str;
664 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
665 base::FilePath device_dir(device_dir_str);
666
667 // On devices without dynamic partition, search for static partitions.
668 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
669 *path = device_dir.Append(partition_name_suffix).value();
670 TEST_AND_RETURN_FALSE(DeviceExists(*path));
671 return true;
672 }
673
674 auto source_super_device =
675 device_dir.Append(GetSuperPartitionName(source_slot)).value();
676
677 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
678 if (builder == nullptr) {
679 if (IsRecovery()) {
680 // It might be corrupted for some reason. It should still be able to
681 // sideload.
682 LOG(WARNING) << "Super partition metadata cannot be read from the source "
683 << "slot, skip erasing.";
684 return true;
685 } else {
686 // Device has booted into Android mode, indicating that the super
687 // partition metadata should be there.
688 LOG(ERROR) << "Super partition metadata cannot be read from the source "
689 << "slot. This is unexpected on devices with dynamic "
690 << "partitions enabled.";
691 return false;
692 }
693 }
694 auto p = builder->FindPartition(partition_name_suffix);
695 if (p == nullptr) {
696 // If the source slot is flashed without system_other, it does not exist
697 // in super partition metadata at source slot. It is safe to skip it.
698 LOG(INFO) << "Can't find " << partition_name_suffix
699 << " in metadata source slot, skip erasing.";
700 return true;
701 }
702 // System_other created by flashing tools should be erased.
703 // If partition is created by update_engine (via NewForUpdate), it is a
704 // left-over partition from the previous update and does not contain
705 // system_other, hence there is no need to erase.
706 // Note the reverse is not necessary true. If the flag is not set, we don't
707 // know if the partition is created by update_engine or by flashing tools
708 // because older versions of super partition metadata does not contain this
709 // flag. It is okay to erase the AVB footer anyways.
710 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
711 LOG(INFO) << partition_name_suffix
712 << " does not contain system_other, skip erasing.";
713 return true;
714 }
715
Yifan Hong64331b32020-05-13 16:50:40 -0700716 if (p->size() < AVB_FOOTER_SIZE) {
717 LOG(INFO) << partition_name_suffix << " has length " << p->size()
718 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
719 << "), skip erasing.";
720 return true;
721 }
722
Yifan Hong29692902020-03-26 12:47:05 -0700723 // Delete any pre-existing device with name |partition_name_suffix| and
724 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700725 // In recovery, metadata might not be mounted, and
726 // UnmapPartitionOnDeviceMapper might fail. However,
727 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700728 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
729 // Use CreateLogicalPartition directly to avoid mapping with existing
730 // snapshots.
731 CreateLogicalPartitionParams params = {
732 .block_device = source_super_device,
733 .metadata_slot = source_slot,
734 .partition_name = partition_name_suffix,
735 .force_writable = true,
736 .timeout_ms = kMapTimeout,
737 };
738 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
739 *should_unmap = true;
740 return true;
741}
742
743bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
744 uint32_t source_slot, uint32_t target_slot) {
745 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
746
747 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
748 const std::string partition_name_suffix = "system" + target_suffix;
749
750 std::string path;
751 bool should_unmap = false;
752
753 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
754 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
755
756 if (path.empty()) {
757 return true;
758 }
759
760 bool ret = AvbFooterEraser(path).Erase();
761
762 // Delete |partition_name_suffix| from device mapper and from
763 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700764 // In recovery, metadata might not be mounted, and
765 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
766 // should be called. If DestroyLogicalPartition does fail, it is still okay
767 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700768 if (should_unmap) {
769 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
770 }
771
772 return ret;
773}
774
Yifan Hong420db9b2019-07-23 20:50:33 -0700775bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
776 uint32_t source_slot,
777 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700778 const DeltaArchiveManifest& manifest,
779 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700780 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
781
782 // Unmap all the target dynamic partitions because they would become
783 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700784 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
785 for (const auto& partition_name : group.partition_names()) {
786 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700787 return false;
788 }
789 }
790 }
791
792 std::string device_dir_str;
793 if (!GetDeviceDir(&device_dir_str)) {
794 return false;
795 }
796 base::FilePath device_dir(device_dir_str);
797 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700798 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700799
800 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
801 if (builder == nullptr) {
802 LOG(ERROR) << "No metadata at "
803 << BootControlInterface::SlotName(source_slot);
804 return false;
805 }
806
Yifan Hongbae27842019-10-24 16:56:12 -0700807 if (delete_source) {
808 TEST_AND_RETURN_FALSE(
809 DeleteSourcePartitions(builder.get(), source_slot, manifest));
810 }
811
Yifan Hong13d41cb2019-09-16 13:18:22 -0700812 if (!UpdatePartitionMetadata(builder.get(), target_slot, manifest)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700813 return false;
814 }
815
816 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700817 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700818 return StoreMetadata(target_device, builder.get(), target_slot);
819}
820
Yifan Hong420db9b2019-07-23 20:50:33 -0700821bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
822 uint32_t source_slot,
823 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800824 const DeltaArchiveManifest& manifest,
825 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700826 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Yifan Hong420db9b2019-07-23 20:50:33 -0700827 if (!snapshot_->BeginUpdate()) {
828 LOG(ERROR) << "Cannot begin new update.";
829 return false;
830 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800831 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
832 if (!ret) {
833 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
834 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800835 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800836 *required_size = ret.required_size();
837 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700838 return false;
839 }
840 return true;
841}
842
Yifan Hong700d7c12019-07-23 20:49:16 -0700843std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
844 uint32_t slot) {
845 return fs_mgr_get_super_partition_name(slot);
846}
847
Yifan Hong012508e2019-07-22 18:30:40 -0700848bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
849 MetadataBuilder* builder,
850 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700851 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700852 // Check preconditions.
853 CHECK(!GetVirtualAbFeatureFlag().IsEnabled() || IsRecovery())
854 << "UpdatePartitionMetadata is called on a Virtual A/B device "
855 "but source partitions is not deleted. This is not allowed.";
856
Yifan Honga4e7da32019-09-30 18:25:03 -0700857 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
858 // COW group needs to be deleted to ensure there are enough space to create
859 // target partitions.
860 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
861
Yifan Hong012508e2019-07-22 18:30:40 -0700862 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
863 DeleteGroupsWithSuffix(builder, target_suffix);
864
865 uint64_t total_size = 0;
Yifan Hong13d41cb2019-09-16 13:18:22 -0700866 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
867 total_size += group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700868 }
869
870 std::string expr;
871 uint64_t allocatable_space = builder->AllocatableSpace();
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700872 // On device retrofitting dynamic partitions, allocatable_space = super.
873 // On device launching dynamic partitions w/o VAB,
874 // allocatable_space = super / 2.
875 // On device launching dynamic partitions with VAB, allocatable_space = super.
876 if (!GetDynamicPartitionsFeatureFlag().IsRetrofit() &&
877 !GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hong012508e2019-07-22 18:30:40 -0700878 allocatable_space /= 2;
879 expr = "half of ";
880 }
881 if (total_size > allocatable_space) {
882 LOG(ERROR) << "The maximum size of all groups with suffix " << target_suffix
883 << " (" << total_size << ") has exceeded " << expr
884 << "allocatable space for dynamic partitions "
885 << allocatable_space << ".";
886 return false;
887 }
888
Yifan Hong13d41cb2019-09-16 13:18:22 -0700889 // name of partition(e.g. "system") -> size in bytes
890 std::map<std::string, uint64_t> partition_sizes;
891 for (const auto& partition : manifest.partitions()) {
892 partition_sizes.emplace(partition.partition_name(),
893 partition.new_partition_info().size());
894 }
895
896 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
897 auto group_name_suffix = group.name() + target_suffix;
898 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -0700899 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700900 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700901 return false;
902 }
903 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700904 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700905
Yifan Hong13d41cb2019-09-16 13:18:22 -0700906 for (const auto& partition_name : group.partition_names()) {
907 auto partition_sizes_it = partition_sizes.find(partition_name);
908 if (partition_sizes_it == partition_sizes.end()) {
909 // TODO(tbao): Support auto-filling partition info for framework-only
910 // OTA.
911 LOG(ERROR) << "dynamic_partition_metadata contains partition "
912 << partition_name << " but it is not part of the manifest. "
913 << "This is not supported.";
914 return false;
915 }
916 uint64_t partition_size = partition_sizes_it->second;
917
918 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -0700919 Partition* p = builder->AddPartition(
920 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
921 if (!p) {
922 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
923 << " to group " << group_name_suffix;
924 return false;
925 }
Yifan Hong13d41cb2019-09-16 13:18:22 -0700926 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700927 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -0700928 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -0700929 return false;
930 }
931 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700932 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -0700933 }
934 }
935
936 return true;
937}
938
Yifan Hong7b3910a2020-03-24 17:47:32 -0700939bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700940 if (ExpectMetadataMounted()) {
941 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
942 LOG(INFO) << "Snapshot writes are done.";
943 return snapshot_->FinishedSnapshotWrites(powerwash_required);
944 }
945 } else {
946 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
947 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -0700948 }
949 return true;
Yifan Honga33bca42019-09-03 20:29:45 -0700950}
951
Yifan Hong3a1a5612019-11-05 16:34:32 -0800952bool DynamicPartitionControlAndroid::GetPartitionDevice(
953 const std::string& partition_name,
954 uint32_t slot,
955 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -0700956 bool not_in_payload,
957 std::string* device,
958 bool* is_dynamic) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800959 const auto& partition_name_suffix =
960 partition_name + SlotSuffixForSlotNumber(slot);
961 std::string device_dir_str;
962 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
963 base::FilePath device_dir(device_dir_str);
964
Tianjie51a5a392020-06-03 14:39:32 -0700965 if (is_dynamic) {
966 *is_dynamic = false;
967 }
968
Yifan Hong3a1a5612019-11-05 16:34:32 -0800969 // When looking up target partition devices, treat them as static if the
970 // current payload doesn't encode them as dynamic partitions. This may happen
971 // when applying a retrofit update on top of a dynamic-partitions-enabled
972 // build.
973 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
974 (slot == current_slot || is_target_dynamic_)) {
Tianjie51a5a392020-06-03 14:39:32 -0700975 switch (GetDynamicPartitionDevice(device_dir,
976 partition_name_suffix,
977 slot,
978 current_slot,
979 not_in_payload,
980 device)) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800981 case DynamicPartitionDeviceStatus::SUCCESS:
Tianjie51a5a392020-06-03 14:39:32 -0700982 if (is_dynamic) {
983 *is_dynamic = true;
984 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800985 return true;
986 case DynamicPartitionDeviceStatus::TRY_STATIC:
987 break;
988 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
989 default:
990 return false;
991 }
992 }
993 base::FilePath path = device_dir.Append(partition_name_suffix);
994 if (!DeviceExists(path.value())) {
995 LOG(ERROR) << "Device file " << path.value() << " does not exist.";
996 return false;
997 }
998
999 *device = path.value();
1000 return true;
1001}
1002
Tianjie51a5a392020-06-03 14:39:32 -07001003bool DynamicPartitionControlAndroid::GetPartitionDevice(
1004 const std::string& partition_name,
1005 uint32_t slot,
1006 uint32_t current_slot,
1007 std::string* device) {
1008 return GetPartitionDevice(
1009 partition_name, slot, current_slot, false, device, nullptr);
1010}
1011
Yifan Hong3a1a5612019-11-05 16:34:32 -08001012bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1013 const base::FilePath& device_dir,
1014 uint32_t current_slot,
1015 const std::string& partition_name_suffix) {
1016 std::string source_device =
1017 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1018 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1019 return source_metadata->HasBlockDevice(partition_name_suffix);
1020}
1021
1022DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1023DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1024 const base::FilePath& device_dir,
1025 const std::string& partition_name_suffix,
1026 uint32_t slot,
1027 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001028 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001029 std::string* device) {
1030 std::string super_device =
1031 device_dir.Append(GetSuperPartitionName(slot)).value();
1032
1033 auto builder = LoadMetadataBuilder(super_device, slot);
1034 if (builder == nullptr) {
1035 LOG(ERROR) << "No metadata in slot "
1036 << BootControlInterface::SlotName(slot);
1037 return DynamicPartitionDeviceStatus::ERROR;
1038 }
1039 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1040 LOG(INFO) << partition_name_suffix
1041 << " is not in super partition metadata.";
1042
1043 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1044 LOG(ERROR) << "The static partition " << partition_name_suffix
1045 << " is a block device for current metadata."
1046 << "It cannot be used as a logical partition.";
1047 return DynamicPartitionDeviceStatus::ERROR;
1048 }
1049
1050 return DynamicPartitionDeviceStatus::TRY_STATIC;
1051 }
1052
1053 if (slot == current_slot) {
1054 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1055 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1056 << "not mapped. Now try to map it.";
1057 } else {
1058 if (GetDmDevicePathByName(partition_name_suffix, device)) {
1059 LOG(INFO) << partition_name_suffix
1060 << " is mapped on device mapper: " << *device;
1061 return DynamicPartitionDeviceStatus::SUCCESS;
1062 }
1063 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1064 return DynamicPartitionDeviceStatus::ERROR;
1065 }
1066 }
1067
Tianjie51a5a392020-06-03 14:39:32 -07001068 bool force_writable = (slot != current_slot) && !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001069 if (MapPartitionOnDeviceMapper(
1070 super_device, partition_name_suffix, slot, force_writable, device)) {
1071 return DynamicPartitionDeviceStatus::SUCCESS;
1072 }
1073 return DynamicPartitionDeviceStatus::ERROR;
1074}
1075
Yifan Hong6eec9952019-12-04 13:12:01 -08001076void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1077 const std::set<std::string>& fake) {
1078 mapped_devices_ = fake;
1079}
1080
Yifan Hongbae27842019-10-24 16:56:12 -07001081bool DynamicPartitionControlAndroid::IsRecovery() {
Kelvin Zhanga22ef552020-10-12 19:03:52 -04001082 return constants::kIsRecovery;
Yifan Hongbae27842019-10-24 16:56:12 -07001083}
1084
1085static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1086 const auto& partitions = manifest.partitions();
1087 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1088 return p.has_old_partition_info();
1089 });
1090}
1091
1092bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1093 MetadataBuilder* builder,
1094 uint32_t source_slot,
1095 const DeltaArchiveManifest& manifest) {
1096 TEST_AND_RETURN_FALSE(IsRecovery());
1097
1098 if (IsIncrementalUpdate(manifest)) {
1099 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1100 << "be created.";
1101 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1102 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1103 << " Virtual A/B is not supported.";
1104 }
1105 return false;
1106 }
1107
1108 LOG(INFO) << "Will overwrite existing partitions. Slot "
1109 << BootControlInterface::SlotName(source_slot)
1110 << "may be unbootable until update finishes!";
1111 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1112 DeleteGroupsWithSuffix(builder, source_suffix);
1113
1114 return true;
1115}
1116
Yifan Hong90965502020-02-19 15:22:47 -08001117std::unique_ptr<AbstractAction>
1118DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1119 BootControlInterface* boot_control,
1120 PrefsInterface* prefs,
1121 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1122 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1123 return std::make_unique<NoOpAction>();
1124 }
1125 return std::make_unique<CleanupPreviousUpdateAction>(
1126 prefs, boot_control, snapshot_.get(), delegate);
1127}
1128
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001129bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1130 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1131 return true;
1132 }
1133
1134 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1135 TEST_AND_RETURN_FALSE(prefs != nullptr);
1136
1137 // If the device has already booted into the target slot,
1138 // ResetUpdateProgress may pass but CancelUpdate fails.
1139 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1140 // space when it is done.
1141 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1142 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1143
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001144 if (ExpectMetadataMounted()) {
1145 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1146 } else {
1147 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1148 << "not mounted";
1149 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001150
1151 return true;
1152}
1153
Tianjie99d570d2020-06-04 14:57:19 -07001154bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
1155 uint32_t current_slot, std::vector<std::string>* partitions) {
1156 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
1157 LOG(ERROR) << "Dynamic partition is not enabled";
1158 return false;
1159 }
1160
1161 std::string device_dir_str;
1162 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1163 base::FilePath device_dir(device_dir_str);
1164 auto super_device =
1165 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1166 auto builder = LoadMetadataBuilder(super_device, current_slot);
1167 TEST_AND_RETURN_FALSE(builder != nullptr);
1168
1169 std::vector<std::string> result;
1170 auto suffix = SlotSuffixForSlotNumber(current_slot);
1171 for (const auto& group : builder->ListGroups()) {
1172 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1173 std::string_view partition_name = partition->name();
1174 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1175 continue;
1176 }
1177 result.emplace_back(partition_name);
1178 }
1179 }
1180 *partitions = std::move(result);
1181 return true;
1182}
1183
Tianjie24f96092020-06-30 12:26:25 -07001184bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1185 uint32_t source_slot,
1186 uint32_t target_slot,
1187 const std::vector<std::string>& partitions) {
1188 std::string device_dir_str;
1189 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1190 base::FilePath device_dir(device_dir_str);
1191
1192 auto source_super_device =
1193 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1194 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1195 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1196
1197 auto target_super_device =
1198 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1199 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1200 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1201
1202 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1203 *source_builder, source_slot, *target_builder, target_slot, partitions);
1204}
1205
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001206bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1207 // No need to mount metadata for non-Virtual A/B devices.
1208 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1209 return false;
1210 }
1211 // Intentionally not checking |metadata_device_| in Android mode.
1212 // /metadata should always be mounted in Android mode. If it isn't, let caller
1213 // fails when calling into SnapshotManager.
1214 if (!IsRecovery()) {
1215 return true;
1216 }
1217 // In recovery mode, explicitly check |metadata_device_|.
1218 return metadata_device_ != nullptr;
1219}
1220
1221bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1222 // No need to mount metadata for non-Virtual A/B devices.
1223 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1224 return true;
1225 }
1226
1227 if (metadata_device_ == nullptr) {
1228 metadata_device_ = snapshot_->EnsureMetadataMounted();
1229 }
1230 return metadata_device_ != nullptr;
1231}
1232
Yifan Hong537802d2018-08-15 13:15:42 -07001233} // namespace chromeos_update_engine