1 // Copyright (C) 2019 The Android Open Source Project 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #pragma once 16 17 #include <stdint.h> 18 19 #include <chrono> 20 #include <map> 21 #include <memory> 22 #include <optional> 23 #include <ostream> 24 #include <string> 25 #include <string_view> 26 #include <vector> 27 28 #include <android-base/unique_fd.h> 29 #include <android/snapshot/snapshot.pb.h> 30 #include <fs_mgr_dm_linear.h> 31 #include <libdm/dm.h> 32 #include <libfiemap/image_manager.h> 33 #include <liblp/builder.h> 34 #include <liblp/liblp.h> 35 #include <update_engine/update_metadata.pb.h> 36 37 #include <libsnapshot/auto_device.h> 38 #include <libsnapshot/return.h> 39 40 #ifndef FRIEND_TEST 41 #define FRIEND_TEST(test_set_name, individual_test) \ 42 friend class test_set_name##_##individual_test##_Test 43 #define DEFINED_FRIEND_TEST 44 #endif 45 46 namespace android { 47 48 namespace fiemap { 49 class IImageManager; 50 } // namespace fiemap 51 52 namespace fs_mgr { 53 struct CreateLogicalPartitionParams; 54 class IPartitionOpener; 55 } // namespace fs_mgr 56 57 // Forward declare IBootControl types since we cannot include only the headers 58 // with Soong. Note: keep the enum width in sync. 59 namespace hardware { 60 namespace boot { 61 namespace V1_1 { 62 enum class MergeStatus : int32_t; 63 } // namespace V1_1 64 } // namespace boot 65 } // namespace hardware 66 67 namespace snapshot { 68 69 struct AutoDeleteCowImage; 70 struct AutoDeleteSnapshot; 71 struct AutoDeviceList; 72 struct PartitionCowCreator; 73 class ISnapshotMergeStats; 74 class SnapshotMergeStats; 75 class SnapshotStatus; 76 77 static constexpr const std::string_view kCowGroupName = "cow"; 78 79 bool OptimizeSourceCopyOperation(const chromeos_update_engine::InstallOperation& operation, 80 chromeos_update_engine::InstallOperation* optimized); 81 82 enum class CreateResult : unsigned int { 83 ERROR, 84 CREATED, 85 NOT_CREATED, 86 }; 87 88 class ISnapshotManager { 89 public: 90 // Dependency injection for testing. 91 class IDeviceInfo { 92 public: ~IDeviceInfo()93 virtual ~IDeviceInfo() {} 94 virtual std::string GetGsidDir() const = 0; 95 virtual std::string GetMetadataDir() const = 0; 96 virtual std::string GetSlotSuffix() const = 0; 97 virtual std::string GetOtherSlotSuffix() const = 0; 98 virtual std::string GetSuperDevice(uint32_t slot) const = 0; 99 virtual const android::fs_mgr::IPartitionOpener& GetPartitionOpener() const = 0; 100 virtual bool IsOverlayfsSetup() const = 0; 101 virtual bool SetBootControlMergeStatus( 102 android::hardware::boot::V1_1::MergeStatus status) = 0; 103 virtual bool SetSlotAsUnbootable(unsigned int slot) = 0; 104 virtual bool IsRecovery() const = 0; 105 }; 106 virtual ~ISnapshotManager() = default; 107 108 // Begin an update. This must be called before creating any snapshots. It 109 // will fail if GetUpdateState() != None. 110 virtual bool BeginUpdate() = 0; 111 112 // Cancel an update; any snapshots will be deleted. This is allowed if the 113 // state == Initiated, None, or Unverified (before rebooting to the new 114 // slot). 115 virtual bool CancelUpdate() = 0; 116 117 // Mark snapshot writes as having completed. After this, new snapshots cannot 118 // be created, and the device must either cancel the OTA (either before 119 // rebooting or after rolling back), or merge the OTA. 120 // Before calling this function, all snapshots must be mapped. 121 // If |wipe| is set to true, wipe is scheduled after reboot, and snapshots 122 // may need to be merged before wiping. 123 virtual bool FinishedSnapshotWrites(bool wipe) = 0; 124 125 // Initiate a merge on all snapshot devices. This should only be used after an 126 // update has been marked successful after booting. 127 virtual bool InitiateMerge(uint64_t* cow_file_size = nullptr) = 0; 128 129 // Perform any necessary post-boot actions. This should be run soon after 130 // /data is mounted. 131 // 132 // If a merge is in progress, this function will block until the merge is 133 // completed. 134 // - Callback is called periodically during the merge. If callback() 135 // returns false during the merge, ProcessUpdateState() will pause 136 // and returns Merging. 137 // If a merge or update was cancelled, this will clean up any 138 // update artifacts and return. 139 // 140 // Note that after calling this, GetUpdateState() may still return that a 141 // merge is in progress: 142 // MergeFailed indicates that a fatal error occurred. WaitForMerge() may 143 // called any number of times again to attempt to make more progress, but 144 // we do not expect it to succeed if a catastrophic error occurred. 145 // 146 // MergeNeedsReboot indicates that the merge has completed, but cleanup 147 // failed. This can happen if for some reason resources were not closed 148 // properly. In this case another reboot is needed before we can take 149 // another OTA. However, WaitForMerge() can be called again without 150 // rebooting, to attempt to finish cleanup anyway. 151 // 152 // MergeCompleted indicates that the update has fully completed. 153 // GetUpdateState will return None, and a new update can begin. 154 // 155 // The optional callback allows the caller to periodically check the 156 // progress with GetUpdateState(). 157 virtual UpdateState ProcessUpdateState(const std::function<bool()>& callback = {}, 158 const std::function<bool()>& before_cancel = {}) = 0; 159 160 // Find the status of the current update, if any. 161 // 162 // |progress| depends on the returned status: 163 // Merging: Value in the range [0, 100] 164 // MergeCompleted: 100 165 // Other: 0 166 virtual UpdateState GetUpdateState(double* progress = nullptr) = 0; 167 168 // Create necessary COW device / files for OTA clients. New logical partitions will be added to 169 // group "cow" in target_metadata. Regions of partitions of current_metadata will be 170 // "write-protected" and snapshotted. 171 virtual Return CreateUpdateSnapshots( 172 const chromeos_update_engine::DeltaArchiveManifest& manifest) = 0; 173 174 // Map a snapshotted partition for OTA clients to write to. Write-protected regions are 175 // determined previously in CreateSnapshots. 176 // |snapshot_path| must not be nullptr. 177 virtual bool MapUpdateSnapshot(const android::fs_mgr::CreateLogicalPartitionParams& params, 178 std::string* snapshot_path) = 0; 179 180 // Unmap a snapshot device that's previously mapped with MapUpdateSnapshot. 181 virtual bool UnmapUpdateSnapshot(const std::string& target_partition_name) = 0; 182 183 // If this returns true, first-stage mount must call 184 // CreateLogicalAndSnapshotPartitions rather than CreateLogicalPartitions. 185 virtual bool NeedSnapshotsInFirstStageMount() = 0; 186 187 // Perform first-stage mapping of snapshot targets. This replaces init's 188 // call to CreateLogicalPartitions when snapshots are present. 189 virtual bool CreateLogicalAndSnapshotPartitions( 190 const std::string& super_device, const std::chrono::milliseconds& timeout_ms = {}) = 0; 191 192 // This method should be called preceding any wipe or flash of metadata or 193 // userdata. It is only valid in recovery or fastbootd, and it ensures that 194 // a merge has been completed. 195 // 196 // When userdata will be wiped or flashed, it is necessary to clean up any 197 // snapshot state. If a merge is in progress, the merge must be finished. 198 // If a snapshot is present but not yet merged, the slot must be marked as 199 // unbootable. 200 // 201 // Returns true on success (or nothing to do), false on failure. The 202 // optional callback fires periodically to query progress via GetUpdateState. 203 virtual bool HandleImminentDataWipe(const std::function<void()>& callback = {}) = 0; 204 205 // Force a merge to complete in recovery. This is similar to HandleImminentDataWipe 206 // but does not expect a data wipe after. 207 virtual bool FinishMergeInRecovery() = 0; 208 209 // This method is only allowed in recovery and is used as a helper to 210 // initialize the snapshot devices as a requirement to mount a snapshotted 211 // /system in recovery. 212 // This function returns: 213 // - CreateResult::CREATED if snapshot devices were successfully created; 214 // - CreateResult::NOT_CREATED if it was not necessary to create snapshot 215 // devices; 216 // - CreateResult::ERROR if a fatal error occurred, mounting /system should 217 // be aborted. 218 // This function mounts /metadata when called, and unmounts /metadata upon 219 // return. 220 virtual CreateResult RecoveryCreateSnapshotDevices() = 0; 221 222 // Same as RecoveryCreateSnapshotDevices(), but does not auto mount/umount 223 // /metadata. 224 virtual CreateResult RecoveryCreateSnapshotDevices( 225 const std::unique_ptr<AutoDevice>& metadata_device) = 0; 226 227 // Dump debug information. 228 virtual bool Dump(std::ostream& os) = 0; 229 230 // Ensure metadata directory is mounted in recovery. When the returned 231 // AutoDevice is destroyed, the metadata directory is automatically 232 // unmounted. 233 // Return nullptr if any failure. 234 // In Android mode, Return an AutoDevice that does nothing 235 // In recovery, return an AutoDevice that does nothing if metadata entry 236 // is not found in fstab. 237 // Note: if this function is called the second time before the AutoDevice returned from the 238 // first call is destroyed, the device will be unmounted when any of these AutoDevices is 239 // destroyed. For example: 240 // auto a = mgr->EnsureMetadataMounted(); // mounts 241 // auto b = mgr->EnsureMetadataMounted(); // does nothing 242 // b.reset() // unmounts 243 // a.reset() // does nothing 244 virtual std::unique_ptr<AutoDevice> EnsureMetadataMounted() = 0; 245 246 // Return the associated ISnapshotMergeStats instance. Never null. 247 virtual ISnapshotMergeStats* GetSnapshotMergeStatsInstance() = 0; 248 }; 249 250 class SnapshotManager final : public ISnapshotManager { 251 using CreateLogicalPartitionParams = android::fs_mgr::CreateLogicalPartitionParams; 252 using IPartitionOpener = android::fs_mgr::IPartitionOpener; 253 using LpMetadata = android::fs_mgr::LpMetadata; 254 using MetadataBuilder = android::fs_mgr::MetadataBuilder; 255 using DeltaArchiveManifest = chromeos_update_engine::DeltaArchiveManifest; 256 using MergeStatus = android::hardware::boot::V1_1::MergeStatus; 257 using FiemapStatus = android::fiemap::FiemapStatus; 258 259 friend class SnapshotMergeStats; 260 261 public: 262 ~SnapshotManager(); 263 264 // Return a new SnapshotManager instance, or null on error. The device 265 // pointer is owned for the lifetime of SnapshotManager. If null, a default 266 // instance will be created. 267 static std::unique_ptr<SnapshotManager> New(IDeviceInfo* device = nullptr); 268 269 // This is similar to New(), except designed specifically for first-stage 270 // init or recovery. 271 static std::unique_ptr<SnapshotManager> NewForFirstStageMount(IDeviceInfo* device = nullptr); 272 273 // Helper function for first-stage init to check whether a SnapshotManager 274 // might be needed to perform first-stage mounts. 275 static bool IsSnapshotManagerNeeded(); 276 277 // Helper function for second stage init to restorecon on the rollback indicator. 278 static std::string GetGlobalRollbackIndicatorPath(); 279 280 // ISnapshotManager overrides. 281 bool BeginUpdate() override; 282 bool CancelUpdate() override; 283 bool FinishedSnapshotWrites(bool wipe) override; 284 bool InitiateMerge(uint64_t* cow_file_size = nullptr) override; 285 UpdateState ProcessUpdateState(const std::function<bool()>& callback = {}, 286 const std::function<bool()>& before_cancel = {}) override; 287 UpdateState GetUpdateState(double* progress = nullptr) override; 288 Return CreateUpdateSnapshots(const DeltaArchiveManifest& manifest) override; 289 bool MapUpdateSnapshot(const CreateLogicalPartitionParams& params, 290 std::string* snapshot_path) override; 291 bool UnmapUpdateSnapshot(const std::string& target_partition_name) override; 292 bool NeedSnapshotsInFirstStageMount() override; 293 bool CreateLogicalAndSnapshotPartitions( 294 const std::string& super_device, 295 const std::chrono::milliseconds& timeout_ms = {}) override; 296 bool HandleImminentDataWipe(const std::function<void()>& callback = {}) override; 297 bool FinishMergeInRecovery() override; 298 CreateResult RecoveryCreateSnapshotDevices() override; 299 CreateResult RecoveryCreateSnapshotDevices( 300 const std::unique_ptr<AutoDevice>& metadata_device) override; 301 bool Dump(std::ostream& os) override; 302 std::unique_ptr<AutoDevice> EnsureMetadataMounted() override; 303 ISnapshotMergeStats* GetSnapshotMergeStatsInstance() override; 304 305 private: 306 FRIEND_TEST(SnapshotTest, CleanFirstStageMount); 307 FRIEND_TEST(SnapshotTest, CreateSnapshot); 308 FRIEND_TEST(SnapshotTest, FirstStageMountAfterRollback); 309 FRIEND_TEST(SnapshotTest, FirstStageMountAndMerge); 310 FRIEND_TEST(SnapshotTest, FlashSuperDuringMerge); 311 FRIEND_TEST(SnapshotTest, FlashSuperDuringUpdate); 312 FRIEND_TEST(SnapshotTest, MapPartialSnapshot); 313 FRIEND_TEST(SnapshotTest, MapSnapshot); 314 FRIEND_TEST(SnapshotTest, Merge); 315 FRIEND_TEST(SnapshotTest, NoMergeBeforeReboot); 316 FRIEND_TEST(SnapshotTest, UpdateBootControlHal); 317 FRIEND_TEST(SnapshotUpdateTest, DataWipeAfterRollback); 318 FRIEND_TEST(SnapshotUpdateTest, DataWipeRollbackInRecovery); 319 FRIEND_TEST(SnapshotUpdateTest, FullUpdateFlow); 320 FRIEND_TEST(SnapshotUpdateTest, MergeCannotRemoveCow); 321 FRIEND_TEST(SnapshotUpdateTest, MergeInRecovery); 322 FRIEND_TEST(SnapshotUpdateTest, SnapshotStatusFileWithoutCow); 323 friend class SnapshotTest; 324 friend class SnapshotUpdateTest; 325 friend class FlashAfterUpdateTest; 326 friend class LockTestConsumer; 327 friend class SnapshotFuzzEnv; 328 friend struct AutoDeleteCowImage; 329 friend struct AutoDeleteSnapshot; 330 friend struct PartitionCowCreator; 331 332 using DmTargetSnapshot = android::dm::DmTargetSnapshot; 333 using IImageManager = android::fiemap::IImageManager; 334 using TargetInfo = android::dm::DeviceMapper::TargetInfo; 335 336 explicit SnapshotManager(IDeviceInfo* info); 337 338 // This is created lazily since it can connect via binder. 339 bool EnsureImageManager(); 340 341 // Helper for first-stage init. 342 bool ForceLocalImageManager(); 343 344 // Helper function for tests. image_manager()345 IImageManager* image_manager() const { return images_.get(); } 346 347 // Since libsnapshot is included into multiple processes, we flock() our 348 // files for simple synchronization. LockedFile is a helper to assist with 349 // this. It also serves as a proof-of-lock for some functions. 350 class LockedFile final { 351 public: LockedFile(const std::string & path,android::base::unique_fd && fd,int lock_mode)352 LockedFile(const std::string& path, android::base::unique_fd&& fd, int lock_mode) 353 : path_(path), fd_(std::move(fd)), lock_mode_(lock_mode) {} 354 ~LockedFile(); lock_mode()355 int lock_mode() const { return lock_mode_; } 356 357 private: 358 std::string path_; 359 android::base::unique_fd fd_; 360 int lock_mode_; 361 }; 362 static std::unique_ptr<LockedFile> OpenFile(const std::string& file, int lock_flags); 363 364 // Create a new snapshot record. This creates the backing COW store and 365 // persists information needed to map the device. The device can be mapped 366 // with MapSnapshot(). 367 // 368 // |status|.device_size should be the size of the base_device that will be passed 369 // via MapDevice(). |status|.snapshot_size should be the number of bytes in the 370 // base device, starting from 0, that will be snapshotted. |status|.cow_file_size 371 // should be the amount of space that will be allocated to store snapshot 372 // deltas. 373 // 374 // If |status|.snapshot_size < |status|.device_size, then the device will always 375 // be mapped with two table entries: a dm-snapshot range covering 376 // snapshot_size, and a dm-linear range covering the remainder. 377 // 378 // All sizes are specified in bytes, and the device, snapshot, COW partition and COW file sizes 379 // must be a multiple of the sector size (512 bytes). 380 bool CreateSnapshot(LockedFile* lock, SnapshotStatus* status); 381 382 // |name| should be the base partition name (e.g. "system_a"). Create the 383 // backing COW image using the size previously passed to CreateSnapshot(). 384 Return CreateCowImage(LockedFile* lock, const std::string& name); 385 386 // Map a snapshot device that was previously created with CreateSnapshot. 387 // If a merge was previously initiated, the device-mapper table will have a 388 // snapshot-merge target instead of a snapshot target. If the timeout 389 // parameter greater than zero, this function will wait the given amount 390 // of time for |dev_path| to become available, and fail otherwise. If 391 // timeout_ms is 0, then no wait will occur and |dev_path| may not yet 392 // exist on return. 393 bool MapSnapshot(LockedFile* lock, const std::string& name, const std::string& base_device, 394 const std::string& cow_device, const std::chrono::milliseconds& timeout_ms, 395 std::string* dev_path); 396 397 // Map a COW image that was previous created with CreateCowImage. 398 std::optional<std::string> MapCowImage(const std::string& name, 399 const std::chrono::milliseconds& timeout_ms); 400 401 // Remove the backing copy-on-write image and snapshot states for the named snapshot. The 402 // caller is responsible for ensuring that the snapshot is unmapped. 403 bool DeleteSnapshot(LockedFile* lock, const std::string& name); 404 405 // Unmap a snapshot device previously mapped with MapSnapshotDevice(). 406 bool UnmapSnapshot(LockedFile* lock, const std::string& name); 407 408 // Unmap a COW image device previously mapped with MapCowImage(). 409 bool UnmapCowImage(const std::string& name); 410 411 // Unmap and remove all known snapshots. 412 bool RemoveAllSnapshots(LockedFile* lock); 413 414 // List the known snapshot names. 415 bool ListSnapshots(LockedFile* lock, std::vector<std::string>* snapshots); 416 417 // Check for a cancelled or rolled back merge, returning true if such a 418 // condition was detected and handled. 419 bool HandleCancelledUpdate(LockedFile* lock, const std::function<bool()>& before_cancel); 420 421 // Helper for HandleCancelledUpdate. Assumes booting from new slot. 422 bool AreAllSnapshotsCancelled(LockedFile* lock); 423 424 // Determine whether partition names in |snapshots| have been flashed and 425 // store result to |out|. 426 // Return true if values are successfully retrieved and false on error 427 // (e.g. super partition metadata cannot be read). When it returns true, 428 // |out| stores true for partitions that have been flashed and false for 429 // partitions that have not been flashed. 430 bool GetSnapshotFlashingStatus(LockedFile* lock, const std::vector<std::string>& snapshots, 431 std::map<std::string, bool>* out); 432 433 // Remove artifacts created by the update process, such as snapshots, and 434 // set the update state to None. 435 bool RemoveAllUpdateState(LockedFile* lock, const std::function<bool()>& prolog = {}); 436 437 // Interact with /metadata/ota. 438 std::unique_ptr<LockedFile> OpenLock(int lock_flags); 439 std::unique_ptr<LockedFile> LockShared(); 440 std::unique_ptr<LockedFile> LockExclusive(); 441 std::string GetLockPath() const; 442 443 // Interact with /metadata/ota/state. 444 UpdateState ReadUpdateState(LockedFile* file); 445 SnapshotUpdateStatus ReadSnapshotUpdateStatus(LockedFile* file); 446 bool WriteUpdateState(LockedFile* file, UpdateState state); 447 bool WriteSnapshotUpdateStatus(LockedFile* file, const SnapshotUpdateStatus& status); 448 std::string GetStateFilePath() const; 449 450 // Interact with /metadata/ota/merge_state. 451 // This file contains information related to the snapshot merge process. 452 std::string GetMergeStateFilePath() const; 453 454 // Helpers for merging. 455 bool SwitchSnapshotToMerge(LockedFile* lock, const std::string& name); 456 bool RewriteSnapshotDeviceTable(const std::string& dm_name); 457 bool MarkSnapshotMergeCompleted(LockedFile* snapshot_lock, const std::string& snapshot_name); 458 void AcknowledgeMergeSuccess(LockedFile* lock); 459 void AcknowledgeMergeFailure(); 460 std::unique_ptr<LpMetadata> ReadCurrentMetadata(); 461 462 enum class MetadataPartitionState { 463 // Partition does not exist. 464 None, 465 // Partition is flashed. 466 Flashed, 467 // Partition is created by OTA client. 468 Updated, 469 }; 470 // Helper function to check the state of a partition as described in metadata. 471 MetadataPartitionState GetMetadataPartitionState(const LpMetadata& metadata, 472 const std::string& name); 473 474 // Note that these require the name of the device containing the snapshot, 475 // which may be the "inner" device. Use GetsnapshotDeviecName(). 476 bool QuerySnapshotStatus(const std::string& dm_name, std::string* target_type, 477 DmTargetSnapshot::Status* status); 478 bool IsSnapshotDevice(const std::string& dm_name, TargetInfo* target = nullptr); 479 480 // Internal callback for when merging is complete. 481 bool OnSnapshotMergeComplete(LockedFile* lock, const std::string& name, 482 const SnapshotStatus& status); 483 bool CollapseSnapshotDevice(const std::string& name, const SnapshotStatus& status); 484 485 // Only the following UpdateStates are used here: 486 // UpdateState::Merging 487 // UpdateState::MergeCompleted 488 // UpdateState::MergeFailed 489 // UpdateState::MergeNeedsReboot 490 UpdateState CheckMergeState(const std::function<bool()>& before_cancel); 491 UpdateState CheckMergeState(LockedFile* lock, const std::function<bool()>& before_cancel); 492 UpdateState CheckTargetMergeState(LockedFile* lock, const std::string& name); 493 494 // Interact with status files under /metadata/ota/snapshots. 495 bool WriteSnapshotStatus(LockedFile* lock, const SnapshotStatus& status); 496 bool ReadSnapshotStatus(LockedFile* lock, const std::string& name, SnapshotStatus* status); 497 std::string GetSnapshotStatusFilePath(const std::string& name); 498 499 std::string GetSnapshotBootIndicatorPath(); 500 std::string GetRollbackIndicatorPath(); 501 std::string GetForwardMergeIndicatorPath(); 502 503 // Return the name of the device holding the "snapshot" or "snapshot-merge" 504 // target. This may not be the final device presented via MapSnapshot(), if 505 // for example there is a linear segment. 506 std::string GetSnapshotDeviceName(const std::string& snapshot_name, 507 const SnapshotStatus& status); 508 509 // Map the base device, COW devices, and snapshot device. 510 bool MapPartitionWithSnapshot(LockedFile* lock, CreateLogicalPartitionParams params, 511 std::string* path); 512 513 // Map the COW devices, including the partition in super and the images. 514 // |params|: 515 // - |partition_name| should be the name of the top-level partition (e.g. system_b), 516 // not system_b-cow-img 517 // - |device_name| and |partition| is ignored 518 // - |timeout_ms| and the rest is respected 519 // Return the path in |cow_device_path| (e.g. /dev/block/dm-1) and major:minor in 520 // |cow_device_string| 521 bool MapCowDevices(LockedFile* lock, const CreateLogicalPartitionParams& params, 522 const SnapshotStatus& snapshot_status, AutoDeviceList* created_devices, 523 std::string* cow_name); 524 525 // The reverse of MapCowDevices. 526 bool UnmapCowDevices(LockedFile* lock, const std::string& name); 527 528 // The reverse of MapPartitionWithSnapshot. 529 bool UnmapPartitionWithSnapshot(LockedFile* lock, const std::string& target_partition_name); 530 531 // If there isn't a previous update, return true. |needs_merge| is set to false. 532 // If there is a previous update but the device has not boot into it, tries to cancel the 533 // update and delete any snapshots. Return true if successful. |needs_merge| is set to false. 534 // If there is a previous update and the device has boot into it, do nothing and return true. 535 // |needs_merge| is set to true. 536 bool TryCancelUpdate(bool* needs_merge); 537 538 // Helper for CreateUpdateSnapshots. 539 // Creates all underlying images, COW partitions and snapshot files. Does not initialize them. 540 Return CreateUpdateSnapshotsInternal( 541 LockedFile* lock, const DeltaArchiveManifest& manifest, 542 PartitionCowCreator* cow_creator, AutoDeviceList* created_devices, 543 std::map<std::string, SnapshotStatus>* all_snapshot_status); 544 545 // Initialize snapshots so that they can be mapped later. 546 // Map the COW partition and zero-initialize the header. 547 Return InitializeUpdateSnapshots( 548 LockedFile* lock, MetadataBuilder* target_metadata, 549 const LpMetadata* exported_target_metadata, const std::string& target_suffix, 550 const std::map<std::string, SnapshotStatus>& all_snapshot_status); 551 552 // Unmap all partitions that were mapped by CreateLogicalAndSnapshotPartitions. 553 // This should only be called in recovery. 554 bool UnmapAllPartitions(); 555 556 // Check no snapshot overflows. Note that this returns false negatives if the snapshot 557 // overflows, then is remapped and not written afterwards. 558 bool EnsureNoOverflowSnapshot(LockedFile* lock); 559 560 enum class Slot { Unknown, Source, Target }; 561 friend std::ostream& operator<<(std::ostream& os, SnapshotManager::Slot slot); 562 Slot GetCurrentSlot(); 563 564 std::string ReadUpdateSourceSlotSuffix(); 565 566 // Helper for RemoveAllSnapshots. 567 // Check whether |name| should be deleted as a snapshot name. 568 bool ShouldDeleteSnapshot(LockedFile* lock, const std::map<std::string, bool>& flashing_status, 569 Slot current_slot, const std::string& name); 570 571 // Create or delete forward merge indicator given |wipe|. Iff wipe is scheduled, 572 // allow forward merge on FDR. 573 bool UpdateForwardMergeIndicator(bool wipe); 574 575 // Helper for HandleImminentDataWipe. 576 // Call ProcessUpdateState and handle states with special rules before data wipe. Specifically, 577 // if |allow_forward_merge| and allow-forward-merge indicator exists, initiate merge if 578 // necessary. 579 bool ProcessUpdateStateOnDataWipe(bool allow_forward_merge, 580 const std::function<bool()>& callback); 581 582 // Return device string of a mapped image, or if it is not available, the mapped image path. 583 bool GetMappedImageDeviceStringOrPath(const std::string& device_name, 584 std::string* device_string_or_mapped_path); 585 586 std::string gsid_dir_; 587 std::string metadata_dir_; 588 std::unique_ptr<IDeviceInfo> device_; 589 std::unique_ptr<IImageManager> images_; 590 bool has_local_image_manager_ = false; 591 bool in_factory_data_reset_ = false; 592 }; 593 594 } // namespace snapshot 595 } // namespace android 596 597 #ifdef DEFINED_FRIEND_TEST 598 #undef DEFINED_FRIEND_TEST 599 #undef FRIEND_TEST 600 #endif 601