blob: e55722c0f217c6e3b134513fb022eb056aaa9694 [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 Zhangab3ce602021-02-24 14:46:40 -050032#include <base/strings/string_util.h>
33#include <base/strings/stringprintf.h>
Kelvin Zhang50bac652020-09-28 15:51:41 -040034
Kelvin Zhang7dd5a5e2023-05-11 15:30:38 -070035#include "update_engine/common/error_code.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040036#include "update_engine/common/utils.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040037#include "update_engine/payload_consumer/cached_file_descriptor.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040038#include "update_engine/payload_consumer/extent_writer.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040039#include "update_engine/payload_consumer/file_descriptor_utils.h"
Kelvin Zhange52b6cd2021-02-09 15:28:40 -050040#include "update_engine/payload_consumer/install_operation_executor.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040041#include "update_engine/payload_consumer/install_plan.h"
42#include "update_engine/payload_consumer/mount_history.h"
Kelvin Zhang37b9b702021-02-23 10:30:37 -050043#include "update_engine/payload_generator/extent_utils.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040044
45namespace chromeos_update_engine {
46
47namespace {
48constexpr uint64_t kCacheSize = 1024 * 1024; // 1MB
49
50// Discard the tail of the block device referenced by |fd|, from the offset
51// |data_size| until the end of the block device. Returns whether the data was
52// discarded.
53
54bool DiscardPartitionTail(const FileDescriptorPtr& fd, uint64_t data_size) {
55 uint64_t part_size = fd->BlockDevSize();
56 if (!part_size || part_size <= data_size)
57 return false;
58
59 struct blkioctl_request {
60 int number;
61 const char* name;
62 };
63 const std::initializer_list<blkioctl_request> blkioctl_requests = {
64 {BLKDISCARD, "BLKDISCARD"},
65 {BLKSECDISCARD, "BLKSECDISCARD"},
66#ifdef BLKZEROOUT
67 {BLKZEROOUT, "BLKZEROOUT"},
68#endif
69 };
70 for (const auto& req : blkioctl_requests) {
71 int error = 0;
72 if (fd->BlkIoctl(req.number, data_size, part_size - data_size, &error) &&
73 error == 0) {
74 return true;
75 }
76 LOG(WARNING) << "Error discarding the last "
77 << (part_size - data_size) / 1024 << " KiB using ioctl("
78 << req.name << ")";
79 }
80 return false;
81}
82
83} // namespace
84
85// Opens path for read/write. On success returns an open FileDescriptor
86// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
87FileDescriptorPtr OpenFile(const char* path,
88 int mode,
89 bool cache_writes,
90 int* err) {
91 // Try to mark the block device read-only based on the mode. Ignore any
92 // failure since this won't work when passing regular files.
93 bool read_only = (mode & O_ACCMODE) == O_RDONLY;
94 utils::SetBlockDeviceReadOnly(path, read_only);
95
96 FileDescriptorPtr fd(new EintrSafeFileDescriptor());
97 if (cache_writes && !read_only) {
98 fd = FileDescriptorPtr(new CachedFileDescriptor(fd, kCacheSize));
99 LOG(INFO) << "Caching writes.";
100 }
101 if (!fd->Open(path, mode, 000)) {
102 *err = errno;
103 PLOG(ERROR) << "Unable to open file " << path;
104 return nullptr;
105 }
106 *err = 0;
107 return fd;
108}
109
Kelvin Zhang50bac652020-09-28 15:51:41 -0400110PartitionWriter::PartitionWriter(
111 const PartitionUpdate& partition_update,
112 const InstallPlan::Partition& install_part,
113 DynamicPartitionControlInterface* dynamic_control,
114 size_t block_size,
115 bool is_interactive)
116 : partition_update_(partition_update),
117 install_part_(install_part),
118 dynamic_control_(dynamic_control),
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500119 verified_source_fd_(block_size, install_part.source_path),
Kelvin Zhang50bac652020-09-28 15:51:41 -0400120 interactive_(is_interactive),
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500121 block_size_(block_size),
122 install_op_executor_(block_size) {}
Kelvin Zhang50bac652020-09-28 15:51:41 -0400123
124PartitionWriter::~PartitionWriter() {
125 Close();
126}
127
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500128bool PartitionWriter::OpenSourcePartition(uint32_t source_slot,
129 bool source_may_exist) {
130 source_path_.clear();
131 if (!source_may_exist) {
132 return true;
133 }
134 if (install_part_.source_size > 0 && !install_part_.source_path.empty()) {
135 source_path_ = install_part_.source_path;
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500136 if (!verified_source_fd_.Open()) {
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500137 LOG(ERROR) << "Unable to open source partition " << install_part_.name
138 << " on slot " << BootControlInterface::SlotName(source_slot)
139 << ", file " << source_path_;
140 return false;
141 }
142 }
143 return true;
144}
145
Kelvin Zhang50bac652020-09-28 15:51:41 -0400146bool PartitionWriter::Init(const InstallPlan* install_plan,
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400147 bool source_may_exist,
148 size_t next_op_index) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400149 const PartitionUpdate& partition = partition_update_;
150 uint32_t source_slot = install_plan->source_slot;
151 uint32_t target_slot = install_plan->target_slot;
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500152 TEST_AND_RETURN_FALSE(OpenSourcePartition(source_slot, source_may_exist));
Kelvin Zhang50bac652020-09-28 15:51:41 -0400153
154 // We shouldn't open the source partition in certain cases, e.g. some dynamic
155 // partitions in delta payload, partitions included in the full payload for
156 // partial updates. Use the source size as the indicator.
Kelvin Zhang50bac652020-09-28 15:51:41 -0400157
158 target_path_ = install_part_.target_path;
Daniel Zhengda4f7292022-09-02 22:59:32 +0000159 int err{};
Kelvin Zhang50bac652020-09-28 15:51:41 -0400160
161 int flags = O_RDWR;
162 if (!interactive_)
163 flags |= O_DSYNC;
164
165 LOG(INFO) << "Opening " << target_path_ << " partition with"
166 << (interactive_ ? "out" : "") << " O_DSYNC";
167
168 target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
169 if (!target_fd_) {
170 LOG(ERROR) << "Unable to open target partition "
171 << partition.partition_name() << " on slot "
172 << BootControlInterface::SlotName(target_slot) << ", file "
173 << target_path_;
174 return false;
175 }
176
177 LOG(INFO) << "Applying " << partition.operations().size()
178 << " operations to partition \"" << partition.partition_name()
179 << "\"";
180
181 // Discard the end of the partition, but ignore failures.
182 DiscardPartitionTail(target_fd_, install_part_.target_size);
183
184 return true;
185}
186
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500187bool PartitionWriter::PerformReplaceOperation(const InstallOperation& operation,
188 const void* data,
189 size_t count) {
190 // Setup the ExtentWriter stack based on the operation type.
191 std::unique_ptr<ExtentWriter> writer = CreateBaseExtentWriter();
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500192 return install_op_executor_.ExecuteReplaceOperation(
Daniel Zheng17be0f92024-01-23 15:12:33 -0800193 operation, std::move(writer), data);
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500194}
195
Kelvin Zhang50bac652020-09-28 15:51:41 -0400196bool PartitionWriter::PerformZeroOrDiscardOperation(
197 const InstallOperation& operation) {
198#ifdef BLKZEROOUT
Kelvin Zhang50bac652020-09-28 15:51:41 -0400199 int request =
200 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
201#else // !defined(BLKZEROOUT)
Kelvin Zhangf4575862021-02-24 10:46:32 -0500202 auto writer = CreateBaseExtentWriter();
203 return install_op_executor_.ExecuteZeroOrDiscardOperation(operation,
204 writer.get());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400205#endif // !defined(BLKZEROOUT)
206
Kelvin Zhang50bac652020-09-28 15:51:41 -0400207 for (const Extent& extent : operation.dst_extents()) {
208 const uint64_t start = extent.start_block() * block_size_;
209 const uint64_t length = extent.num_blocks() * block_size_;
Kelvin Zhangf4575862021-02-24 10:46:32 -0500210 int result = 0;
211 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0) {
212 continue;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400213 }
Kelvin Zhangf4575862021-02-24 10:46:32 -0500214 // In case of failure, we fall back to writing 0 for the entire operation.
215 PLOG(WARNING) << "BlkIoctl failed. Falling back to write 0s for remainder "
216 "of this operation.";
217 auto writer = CreateBaseExtentWriter();
Kelvin Zhang23dfcd22021-08-31 16:32:49 -0700218 return install_op_executor_.ExecuteZeroOrDiscardOperation(
219 operation, std::move(writer));
Kelvin Zhang50bac652020-09-28 15:51:41 -0400220 }
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400221 return true;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400222}
223
224bool PartitionWriter::PerformSourceCopyOperation(
225 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400226 // The device may optimize the SOURCE_COPY operation.
227 // Being this a device-specific optimization let DynamicPartitionController
228 // decide it the operation should be skipped.
229 const PartitionUpdate& partition = partition_update_;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400230
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500231 // Invoke ChooseSourceFD with original operation, so that it can properly
232 // verify source hashes. Optimized operation might contain a smaller set of
233 // extents, or completely empty.
234 auto source_fd = ChooseSourceFD(operation, error);
Kelvin Zhang7dd5a5e2023-05-11 15:30:38 -0700235 if (*error != ErrorCode::kSuccess || source_fd == nullptr) {
236 LOG(WARNING) << "Source hash mismatch detected for extents "
237 << operation.src_extents() << " on partition "
238 << partition.partition_name() << " @ " << source_path_;
239
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500240 return false;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400241 }
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500242
Kelvin Zhang7dd5a5e2023-05-11 15:30:38 -0700243 InstallOperation buf;
244 const bool should_optimize = dynamic_control_->OptimizeOperation(
245 partition.partition_name(), operation, &buf);
246 const InstallOperation& optimized = should_optimize ? buf : operation;
247
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500248 auto writer = CreateBaseExtentWriter();
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500249 return install_op_executor_.ExecuteSourceCopyOperation(
Kelvin Zhang23dfcd22021-08-31 16:32:49 -0700250 optimized, std::move(writer), source_fd);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400251}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400252
Tianjie8e0090d2021-08-30 22:35:21 -0700253bool PartitionWriter::PerformDiffOperation(const InstallOperation& operation,
254 ErrorCode* error,
255 const void* data,
256 size_t count) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400257 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
258 TEST_AND_RETURN_FALSE(source_fd != nullptr);
259
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500260 auto writer = CreateBaseExtentWriter();
Tianjie8e0090d2021-08-30 22:35:21 -0700261 return install_op_executor_.ExecuteDiffOperation(
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500262 operation, std::move(writer), source_fd, data, count);
263}
264
Kelvin Zhang50bac652020-09-28 15:51:41 -0400265FileDescriptorPtr PartitionWriter::ChooseSourceFD(
266 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500267 return verified_source_fd_.ChooseSourceFD(operation, error);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400268}
269
270int PartitionWriter::Close() {
271 int err = 0;
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500272
Kelvin Zhang50bac652020-09-28 15:51:41 -0400273 source_path_.clear();
274
275 if (target_fd_ && !target_fd_->Close()) {
276 err = errno;
277 PLOG(ERROR) << "Error closing target partition";
278 if (!err)
279 err = 1;
280 }
281 target_fd_.reset();
282 target_path_.clear();
283
Kelvin Zhang50bac652020-09-28 15:51:41 -0400284 return -err;
285}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400286
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400287void PartitionWriter::CheckpointUpdateProgress(size_t next_op_index) {
Kelvin Zhang6c057062023-01-17 15:47:31 -0800288 if (target_fd_) {
289 target_fd_->Flush();
290 }
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400291}
292
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400293std::unique_ptr<ExtentWriter> PartitionWriter::CreateBaseExtentWriter() {
Kelvin Zhang4d22ca22021-02-09 14:06:25 -0500294 return std::make_unique<DirectExtentWriter>(target_fd_);
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400295}
296
Kelvin Zhangb5bd0752022-03-10 15:45:25 -0800297bool PartitionWriter::ValidateSourceHash(const InstallOperation& operation,
298 const FileDescriptorPtr source_fd,
299 size_t block_size,
300 ErrorCode* error) {
301 brillo::Blob source_hash;
302 TEST_AND_RETURN_FALSE_ERRNO(fd_utils::ReadAndHashExtents(
303 source_fd, operation.src_extents(), block_size, &source_hash));
304 return ValidateSourceHash(source_hash, operation, source_fd, error);
305}
306
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500307bool PartitionWriter::ValidateSourceHash(const brillo::Blob& calculated_hash,
308 const InstallOperation& operation,
309 const FileDescriptorPtr source_fd,
310 ErrorCode* error) {
311 using std::string;
312 using std::vector;
313 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
314 operation.src_sha256_hash().end());
315 if (calculated_hash != expected_source_hash) {
316 LOG(ERROR) << "The hash of the source data on disk for this operation "
317 << "doesn't match the expected value. This could mean that the "
318 << "delta update payload was targeted for another version, or "
319 << "that the source partition was modified after it was "
320 << "installed, for example, by mounting a filesystem.";
321 LOG(ERROR) << "Expected: sha256|hex = "
322 << base::HexEncode(expected_source_hash.data(),
323 expected_source_hash.size());
324 LOG(ERROR) << "Calculated: sha256|hex = "
325 << base::HexEncode(calculated_hash.data(),
326 calculated_hash.size());
327
328 vector<string> source_extents;
329 for (const Extent& ext : operation.src_extents()) {
330 source_extents.push_back(
331 base::StringPrintf("%" PRIu64 ":%" PRIu64,
332 static_cast<uint64_t>(ext.start_block()),
333 static_cast<uint64_t>(ext.num_blocks())));
334 }
335 LOG(ERROR) << "Operation source (offset:size) in blocks: "
336 << base::JoinString(source_extents, ",");
337
338 // Log remount history if this device is an ext4 partition.
339 LogMountHistory(source_fd);
Kelvin Zhang7dd5a5e2023-05-11 15:30:38 -0700340 if (error) {
341 *error = ErrorCode::kDownloadStateInitializationError;
342 }
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500343 return false;
344 }
345 return true;
346}
347
Kelvin Zhang50bac652020-09-28 15:51:41 -0400348} // namespace chromeos_update_engine