blob: 17763eab0f0e4bca851ca9ff02a741a2a92427af [file] [log] [blame]
Kelvin Zhang50bac652020-09-28 15:51:41 -04001//
2// Copyright (C) 2020 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16#include <update_engine/payload_consumer/partition_writer.h>
17
18#include <fcntl.h>
19#include <linux/fs.h>
Kelvin Zhang1d402cb2021-02-09 15:28:16 -050020#include <sys/mman.h>
Kelvin Zhang50bac652020-09-28 15:51:41 -040021
Kelvin Zhangab3ce602021-02-24 14:46:40 -050022#include <inttypes.h>
23
Kelvin Zhang50bac652020-09-28 15:51:41 -040024#include <algorithm>
25#include <initializer_list>
26#include <memory>
Kelvin Zhangab3ce602021-02-24 14:46:40 -050027#include <string>
Kelvin Zhang50bac652020-09-28 15:51:41 -040028#include <utility>
29#include <vector>
30
31#include <base/strings/string_number_conversions.h>
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -070032#include <android-base/stringprintf.h>
Kelvin Zhang50bac652020-09-28 15:51:41 -040033
Kelvin Zhang7dd5a5e2023-05-11 15:30:38 -070034#include "update_engine/common/error_code.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040035#include "update_engine/common/utils.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040036#include "update_engine/payload_consumer/cached_file_descriptor.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040037#include "update_engine/payload_consumer/extent_writer.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040038#include "update_engine/payload_consumer/file_descriptor_utils.h"
Kelvin Zhange52b6cd2021-02-09 15:28:40 -050039#include "update_engine/payload_consumer/install_operation_executor.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040040#include "update_engine/payload_consumer/install_plan.h"
41#include "update_engine/payload_consumer/mount_history.h"
Kelvin Zhang37b9b702021-02-23 10:30:37 -050042#include "update_engine/payload_generator/extent_utils.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040043
44namespace chromeos_update_engine {
45
46namespace {
47constexpr uint64_t kCacheSize = 1024 * 1024; // 1MB
48
49// Discard the tail of the block device referenced by |fd|, from the offset
50// |data_size| until the end of the block device. Returns whether the data was
51// discarded.
52
53bool DiscardPartitionTail(const FileDescriptorPtr& fd, uint64_t data_size) {
54 uint64_t part_size = fd->BlockDevSize();
55 if (!part_size || part_size <= data_size)
56 return false;
57
58 struct blkioctl_request {
59 int number;
60 const char* name;
61 };
62 const std::initializer_list<blkioctl_request> blkioctl_requests = {
63 {BLKDISCARD, "BLKDISCARD"},
64 {BLKSECDISCARD, "BLKSECDISCARD"},
65#ifdef BLKZEROOUT
66 {BLKZEROOUT, "BLKZEROOUT"},
67#endif
68 };
69 for (const auto& req : blkioctl_requests) {
70 int error = 0;
71 if (fd->BlkIoctl(req.number, data_size, part_size - data_size, &error) &&
72 error == 0) {
73 return true;
74 }
75 LOG(WARNING) << "Error discarding the last "
76 << (part_size - data_size) / 1024 << " KiB using ioctl("
77 << req.name << ")";
78 }
79 return false;
80}
81
82} // namespace
83
84// Opens path for read/write. On success returns an open FileDescriptor
85// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
86FileDescriptorPtr OpenFile(const char* path,
87 int mode,
88 bool cache_writes,
89 int* err) {
90 // Try to mark the block device read-only based on the mode. Ignore any
91 // failure since this won't work when passing regular files.
92 bool read_only = (mode & O_ACCMODE) == O_RDONLY;
93 utils::SetBlockDeviceReadOnly(path, read_only);
94
95 FileDescriptorPtr fd(new EintrSafeFileDescriptor());
96 if (cache_writes && !read_only) {
97 fd = FileDescriptorPtr(new CachedFileDescriptor(fd, kCacheSize));
98 LOG(INFO) << "Caching writes.";
99 }
100 if (!fd->Open(path, mode, 000)) {
101 *err = errno;
102 PLOG(ERROR) << "Unable to open file " << path;
103 return nullptr;
104 }
105 *err = 0;
106 return fd;
107}
108
Kelvin Zhang50bac652020-09-28 15:51:41 -0400109PartitionWriter::PartitionWriter(
110 const PartitionUpdate& partition_update,
111 const InstallPlan::Partition& install_part,
112 DynamicPartitionControlInterface* dynamic_control,
113 size_t block_size,
114 bool is_interactive)
115 : partition_update_(partition_update),
116 install_part_(install_part),
117 dynamic_control_(dynamic_control),
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500118 verified_source_fd_(block_size, install_part.source_path),
Kelvin Zhang50bac652020-09-28 15:51:41 -0400119 interactive_(is_interactive),
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500120 block_size_(block_size),
121 install_op_executor_(block_size) {}
Kelvin Zhang50bac652020-09-28 15:51:41 -0400122
123PartitionWriter::~PartitionWriter() {
124 Close();
125}
126
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500127bool PartitionWriter::OpenSourcePartition(uint32_t source_slot,
128 bool source_may_exist) {
129 source_path_.clear();
130 if (!source_may_exist) {
131 return true;
132 }
133 if (install_part_.source_size > 0 && !install_part_.source_path.empty()) {
134 source_path_ = install_part_.source_path;
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500135 if (!verified_source_fd_.Open()) {
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500136 LOG(ERROR) << "Unable to open source partition " << install_part_.name
137 << " on slot " << BootControlInterface::SlotName(source_slot)
138 << ", file " << source_path_;
139 return false;
140 }
141 }
142 return true;
143}
144
Kelvin Zhang50bac652020-09-28 15:51:41 -0400145bool PartitionWriter::Init(const InstallPlan* install_plan,
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400146 bool source_may_exist,
147 size_t next_op_index) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400148 const PartitionUpdate& partition = partition_update_;
149 uint32_t source_slot = install_plan->source_slot;
150 uint32_t target_slot = install_plan->target_slot;
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500151 TEST_AND_RETURN_FALSE(OpenSourcePartition(source_slot, source_may_exist));
Kelvin Zhang50bac652020-09-28 15:51:41 -0400152
153 // We shouldn't open the source partition in certain cases, e.g. some dynamic
154 // partitions in delta payload, partitions included in the full payload for
155 // partial updates. Use the source size as the indicator.
Kelvin Zhang50bac652020-09-28 15:51:41 -0400156
157 target_path_ = install_part_.target_path;
Daniel Zhengda4f7292022-09-02 22:59:32 +0000158 int err{};
Kelvin Zhang50bac652020-09-28 15:51:41 -0400159
160 int flags = O_RDWR;
161 if (!interactive_)
162 flags |= O_DSYNC;
163
164 LOG(INFO) << "Opening " << target_path_ << " partition with"
165 << (interactive_ ? "out" : "") << " O_DSYNC";
166
167 target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
168 if (!target_fd_) {
169 LOG(ERROR) << "Unable to open target partition "
170 << partition.partition_name() << " on slot "
171 << BootControlInterface::SlotName(target_slot) << ", file "
172 << target_path_;
173 return false;
174 }
175
176 LOG(INFO) << "Applying " << partition.operations().size()
177 << " operations to partition \"" << partition.partition_name()
178 << "\"";
179
180 // Discard the end of the partition, but ignore failures.
181 DiscardPartitionTail(target_fd_, install_part_.target_size);
182
183 return true;
184}
185
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500186bool PartitionWriter::PerformReplaceOperation(const InstallOperation& operation,
187 const void* data,
188 size_t count) {
189 // Setup the ExtentWriter stack based on the operation type.
190 std::unique_ptr<ExtentWriter> writer = CreateBaseExtentWriter();
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500191 return install_op_executor_.ExecuteReplaceOperation(
Daniel Zheng17be0f92024-01-23 15:12:33 -0800192 operation, std::move(writer), data);
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500193}
194
Kelvin Zhang50bac652020-09-28 15:51:41 -0400195bool PartitionWriter::PerformZeroOrDiscardOperation(
196 const InstallOperation& operation) {
197#ifdef BLKZEROOUT
Kelvin Zhang50bac652020-09-28 15:51:41 -0400198 int request =
199 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
200#else // !defined(BLKZEROOUT)
Kelvin Zhangf4575862021-02-24 10:46:32 -0500201 auto writer = CreateBaseExtentWriter();
202 return install_op_executor_.ExecuteZeroOrDiscardOperation(operation,
203 writer.get());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400204#endif // !defined(BLKZEROOUT)
205
Kelvin Zhang50bac652020-09-28 15:51:41 -0400206 for (const Extent& extent : operation.dst_extents()) {
207 const uint64_t start = extent.start_block() * block_size_;
208 const uint64_t length = extent.num_blocks() * block_size_;
Kelvin Zhangf4575862021-02-24 10:46:32 -0500209 int result = 0;
210 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0) {
211 continue;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400212 }
Kelvin Zhangf4575862021-02-24 10:46:32 -0500213 // In case of failure, we fall back to writing 0 for the entire operation.
214 PLOG(WARNING) << "BlkIoctl failed. Falling back to write 0s for remainder "
215 "of this operation.";
216 auto writer = CreateBaseExtentWriter();
Kelvin Zhang23dfcd22021-08-31 16:32:49 -0700217 return install_op_executor_.ExecuteZeroOrDiscardOperation(
218 operation, std::move(writer));
Kelvin Zhang50bac652020-09-28 15:51:41 -0400219 }
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400220 return true;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400221}
222
223bool PartitionWriter::PerformSourceCopyOperation(
224 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400225 // The device may optimize the SOURCE_COPY operation.
226 // Being this a device-specific optimization let DynamicPartitionController
227 // decide it the operation should be skipped.
228 const PartitionUpdate& partition = partition_update_;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400229
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500230 // Invoke ChooseSourceFD with original operation, so that it can properly
231 // verify source hashes. Optimized operation might contain a smaller set of
232 // extents, or completely empty.
233 auto source_fd = ChooseSourceFD(operation, error);
Kelvin Zhang7dd5a5e2023-05-11 15:30:38 -0700234 if (*error != ErrorCode::kSuccess || source_fd == nullptr) {
235 LOG(WARNING) << "Source hash mismatch detected for extents "
236 << operation.src_extents() << " on partition "
237 << partition.partition_name() << " @ " << source_path_;
238
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500239 return false;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400240 }
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500241
Kelvin Zhang7dd5a5e2023-05-11 15:30:38 -0700242 InstallOperation buf;
243 const bool should_optimize = dynamic_control_->OptimizeOperation(
244 partition.partition_name(), operation, &buf);
245 const InstallOperation& optimized = should_optimize ? buf : operation;
246
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500247 auto writer = CreateBaseExtentWriter();
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500248 return install_op_executor_.ExecuteSourceCopyOperation(
Kelvin Zhang23dfcd22021-08-31 16:32:49 -0700249 optimized, std::move(writer), source_fd);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400250}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400251
Tianjie8e0090d2021-08-30 22:35:21 -0700252bool PartitionWriter::PerformDiffOperation(const InstallOperation& operation,
253 ErrorCode* error,
254 const void* data,
255 size_t count) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400256 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
257 TEST_AND_RETURN_FALSE(source_fd != nullptr);
258
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500259 auto writer = CreateBaseExtentWriter();
Tianjie8e0090d2021-08-30 22:35:21 -0700260 return install_op_executor_.ExecuteDiffOperation(
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500261 operation, std::move(writer), source_fd, data, count);
262}
263
Kelvin Zhang50bac652020-09-28 15:51:41 -0400264FileDescriptorPtr PartitionWriter::ChooseSourceFD(
265 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500266 return verified_source_fd_.ChooseSourceFD(operation, error);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400267}
268
269int PartitionWriter::Close() {
270 int err = 0;
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500271
Kelvin Zhang50bac652020-09-28 15:51:41 -0400272 source_path_.clear();
273
274 if (target_fd_ && !target_fd_->Close()) {
275 err = errno;
276 PLOG(ERROR) << "Error closing target partition";
277 if (!err)
278 err = 1;
279 }
280 target_fd_.reset();
281 target_path_.clear();
282
Kelvin Zhang50bac652020-09-28 15:51:41 -0400283 return -err;
284}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400285
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400286void PartitionWriter::CheckpointUpdateProgress(size_t next_op_index) {
Kelvin Zhang6c057062023-01-17 15:47:31 -0800287 if (target_fd_) {
288 target_fd_->Flush();
289 }
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400290}
291
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400292std::unique_ptr<ExtentWriter> PartitionWriter::CreateBaseExtentWriter() {
Kelvin Zhang4d22ca22021-02-09 14:06:25 -0500293 return std::make_unique<DirectExtentWriter>(target_fd_);
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400294}
295
Kelvin Zhangb5bd0752022-03-10 15:45:25 -0800296bool PartitionWriter::ValidateSourceHash(const InstallOperation& operation,
297 const FileDescriptorPtr source_fd,
298 size_t block_size,
299 ErrorCode* error) {
300 brillo::Blob source_hash;
301 TEST_AND_RETURN_FALSE_ERRNO(fd_utils::ReadAndHashExtents(
302 source_fd, operation.src_extents(), block_size, &source_hash));
303 return ValidateSourceHash(source_hash, operation, source_fd, error);
304}
305
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500306bool PartitionWriter::ValidateSourceHash(const brillo::Blob& calculated_hash,
307 const InstallOperation& operation,
308 const FileDescriptorPtr source_fd,
309 ErrorCode* error) {
310 using std::string;
311 using std::vector;
312 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
313 operation.src_sha256_hash().end());
314 if (calculated_hash != expected_source_hash) {
315 LOG(ERROR) << "The hash of the source data on disk for this operation "
316 << "doesn't match the expected value. This could mean that the "
317 << "delta update payload was targeted for another version, or "
318 << "that the source partition was modified after it was "
319 << "installed, for example, by mounting a filesystem.";
320 LOG(ERROR) << "Expected: sha256|hex = "
321 << base::HexEncode(expected_source_hash.data(),
322 expected_source_hash.size());
323 LOG(ERROR) << "Calculated: sha256|hex = "
324 << base::HexEncode(calculated_hash.data(),
325 calculated_hash.size());
326
327 vector<string> source_extents;
328 for (const Extent& ext : operation.src_extents()) {
329 source_extents.push_back(
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -0700330 android::base::StringPrintf("%" PRIu64 ":%" PRIu64,
331 static_cast<uint64_t>(ext.start_block()),
332 static_cast<uint64_t>(ext.num_blocks())));
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500333 }
334 LOG(ERROR) << "Operation source (offset:size) in blocks: "
Kelvin Zhang0c184242024-10-25 11:19:27 -0700335 << android::base::Join(source_extents, ",");
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500336
337 // Log remount history if this device is an ext4 partition.
338 LogMountHistory(source_fd);
Kelvin Zhang7dd5a5e2023-05-11 15:30:38 -0700339 if (error) {
340 *error = ErrorCode::kDownloadStateInitializationError;
341 }
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500342 return false;
343 }
344 return true;
345}
346
Kelvin Zhang50bac652020-09-28 15:51:41 -0400347} // namespace chromeos_update_engine