blob: 1fb929eafab91319dffb37b513f88a65eae49336 [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
35#include "update_engine/common/terminator.h"
36#include "update_engine/common/utils.h"
37#include "update_engine/payload_consumer/bzip_extent_writer.h"
38#include "update_engine/payload_consumer/cached_file_descriptor.h"
39#include "update_engine/payload_consumer/extent_reader.h"
40#include "update_engine/payload_consumer/extent_writer.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040041#include "update_engine/payload_consumer/file_descriptor_utils.h"
Kelvin Zhange52b6cd2021-02-09 15:28:40 -050042#include "update_engine/payload_consumer/install_operation_executor.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040043#include "update_engine/payload_consumer/install_plan.h"
44#include "update_engine/payload_consumer/mount_history.h"
45#include "update_engine/payload_consumer/payload_constants.h"
46#include "update_engine/payload_consumer/xz_extent_writer.h"
Kelvin Zhang37b9b702021-02-23 10:30:37 -050047#include "update_engine/payload_generator/extent_utils.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040048
49namespace chromeos_update_engine {
50
51namespace {
52constexpr uint64_t kCacheSize = 1024 * 1024; // 1MB
53
54// Discard the tail of the block device referenced by |fd|, from the offset
55// |data_size| until the end of the block device. Returns whether the data was
56// discarded.
57
58bool DiscardPartitionTail(const FileDescriptorPtr& fd, uint64_t data_size) {
59 uint64_t part_size = fd->BlockDevSize();
60 if (!part_size || part_size <= data_size)
61 return false;
62
63 struct blkioctl_request {
64 int number;
65 const char* name;
66 };
67 const std::initializer_list<blkioctl_request> blkioctl_requests = {
68 {BLKDISCARD, "BLKDISCARD"},
69 {BLKSECDISCARD, "BLKSECDISCARD"},
70#ifdef BLKZEROOUT
71 {BLKZEROOUT, "BLKZEROOUT"},
72#endif
73 };
74 for (const auto& req : blkioctl_requests) {
75 int error = 0;
76 if (fd->BlkIoctl(req.number, data_size, part_size - data_size, &error) &&
77 error == 0) {
78 return true;
79 }
80 LOG(WARNING) << "Error discarding the last "
81 << (part_size - data_size) / 1024 << " KiB using ioctl("
82 << req.name << ")";
83 }
84 return false;
85}
86
87} // namespace
88
89// Opens path for read/write. On success returns an open FileDescriptor
90// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
91FileDescriptorPtr OpenFile(const char* path,
92 int mode,
93 bool cache_writes,
94 int* err) {
95 // Try to mark the block device read-only based on the mode. Ignore any
96 // failure since this won't work when passing regular files.
97 bool read_only = (mode & O_ACCMODE) == O_RDONLY;
98 utils::SetBlockDeviceReadOnly(path, read_only);
99
100 FileDescriptorPtr fd(new EintrSafeFileDescriptor());
101 if (cache_writes && !read_only) {
102 fd = FileDescriptorPtr(new CachedFileDescriptor(fd, kCacheSize));
103 LOG(INFO) << "Caching writes.";
104 }
105 if (!fd->Open(path, mode, 000)) {
106 *err = errno;
107 PLOG(ERROR) << "Unable to open file " << path;
108 return nullptr;
109 }
110 *err = 0;
111 return fd;
112}
113
Kelvin Zhang50bac652020-09-28 15:51:41 -0400114PartitionWriter::PartitionWriter(
115 const PartitionUpdate& partition_update,
116 const InstallPlan::Partition& install_part,
117 DynamicPartitionControlInterface* dynamic_control,
118 size_t block_size,
119 bool is_interactive)
120 : partition_update_(partition_update),
121 install_part_(install_part),
122 dynamic_control_(dynamic_control),
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500123 verified_source_fd_(block_size, install_part.source_path),
Kelvin Zhang50bac652020-09-28 15:51:41 -0400124 interactive_(is_interactive),
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500125 block_size_(block_size),
126 install_op_executor_(block_size) {}
Kelvin Zhang50bac652020-09-28 15:51:41 -0400127
128PartitionWriter::~PartitionWriter() {
129 Close();
130}
131
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500132bool PartitionWriter::OpenSourcePartition(uint32_t source_slot,
133 bool source_may_exist) {
134 source_path_.clear();
135 if (!source_may_exist) {
136 return true;
137 }
138 if (install_part_.source_size > 0 && !install_part_.source_path.empty()) {
139 source_path_ = install_part_.source_path;
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500140 if (!verified_source_fd_.Open()) {
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500141 LOG(ERROR) << "Unable to open source partition " << install_part_.name
142 << " on slot " << BootControlInterface::SlotName(source_slot)
143 << ", file " << source_path_;
144 return false;
145 }
146 }
147 return true;
148}
149
Kelvin Zhang50bac652020-09-28 15:51:41 -0400150bool PartitionWriter::Init(const InstallPlan* install_plan,
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400151 bool source_may_exist,
152 size_t next_op_index) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400153 const PartitionUpdate& partition = partition_update_;
154 uint32_t source_slot = install_plan->source_slot;
155 uint32_t target_slot = install_plan->target_slot;
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500156 TEST_AND_RETURN_FALSE(OpenSourcePartition(source_slot, source_may_exist));
Kelvin Zhang50bac652020-09-28 15:51:41 -0400157
158 // We shouldn't open the source partition in certain cases, e.g. some dynamic
159 // partitions in delta payload, partitions included in the full payload for
160 // partial updates. Use the source size as the indicator.
Kelvin Zhang50bac652020-09-28 15:51:41 -0400161
162 target_path_ = install_part_.target_path;
163 int err;
164
165 int flags = O_RDWR;
166 if (!interactive_)
167 flags |= O_DSYNC;
168
169 LOG(INFO) << "Opening " << target_path_ << " partition with"
170 << (interactive_ ? "out" : "") << " O_DSYNC";
171
172 target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
173 if (!target_fd_) {
174 LOG(ERROR) << "Unable to open target partition "
175 << partition.partition_name() << " on slot "
176 << BootControlInterface::SlotName(target_slot) << ", file "
177 << target_path_;
178 return false;
179 }
180
181 LOG(INFO) << "Applying " << partition.operations().size()
182 << " operations to partition \"" << partition.partition_name()
183 << "\"";
184
185 // Discard the end of the partition, but ignore failures.
186 DiscardPartitionTail(target_fd_, install_part_.target_size);
187
188 return true;
189}
190
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500191bool PartitionWriter::PerformReplaceOperation(const InstallOperation& operation,
192 const void* data,
193 size_t count) {
194 // Setup the ExtentWriter stack based on the operation type.
195 std::unique_ptr<ExtentWriter> writer = CreateBaseExtentWriter();
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500196 return install_op_executor_.ExecuteReplaceOperation(
197 operation, std::move(writer), data, count);
198}
199
Kelvin Zhang50bac652020-09-28 15:51:41 -0400200bool PartitionWriter::PerformZeroOrDiscardOperation(
201 const InstallOperation& operation) {
202#ifdef BLKZEROOUT
Kelvin Zhang50bac652020-09-28 15:51:41 -0400203 int request =
204 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
205#else // !defined(BLKZEROOUT)
Kelvin Zhangf4575862021-02-24 10:46:32 -0500206 auto writer = CreateBaseExtentWriter();
207 return install_op_executor_.ExecuteZeroOrDiscardOperation(operation,
208 writer.get());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400209#endif // !defined(BLKZEROOUT)
210
Kelvin Zhang50bac652020-09-28 15:51:41 -0400211 for (const Extent& extent : operation.dst_extents()) {
212 const uint64_t start = extent.start_block() * block_size_;
213 const uint64_t length = extent.num_blocks() * block_size_;
Kelvin Zhangf4575862021-02-24 10:46:32 -0500214 int result = 0;
215 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0) {
216 continue;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400217 }
Kelvin Zhangf4575862021-02-24 10:46:32 -0500218 // In case of failure, we fall back to writing 0 for the entire operation.
219 PLOG(WARNING) << "BlkIoctl failed. Falling back to write 0s for remainder "
220 "of this operation.";
221 auto writer = CreateBaseExtentWriter();
Kelvin Zhang23dfcd22021-08-31 16:32:49 -0700222 return install_op_executor_.ExecuteZeroOrDiscardOperation(
223 operation, std::move(writer));
Kelvin Zhang50bac652020-09-28 15:51:41 -0400224 }
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400225 return true;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400226}
227
228bool PartitionWriter::PerformSourceCopyOperation(
229 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400230 // The device may optimize the SOURCE_COPY operation.
231 // Being this a device-specific optimization let DynamicPartitionController
232 // decide it the operation should be skipped.
233 const PartitionUpdate& partition = partition_update_;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400234
235 InstallOperation buf;
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500236 const bool should_optimize = dynamic_control_->OptimizeOperation(
Kelvin Zhang50bac652020-09-28 15:51:41 -0400237 partition.partition_name(), operation, &buf);
238 const InstallOperation& optimized = should_optimize ? buf : operation;
239
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500240 // Invoke ChooseSourceFD with original operation, so that it can properly
241 // verify source hashes. Optimized operation might contain a smaller set of
242 // extents, or completely empty.
243 auto source_fd = ChooseSourceFD(operation, error);
244 if (source_fd == nullptr) {
245 LOG(ERROR) << "Unrecoverable source hash mismatch found on partition "
246 << partition.partition_name()
Kelvin Zhange52b6cd2021-02-09 15:28:40 -0500247 << " extents: " << ExtentsToString(operation.src_extents());
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500248 return false;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400249 }
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500250
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500251 auto writer = CreateBaseExtentWriter();
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500252 return install_op_executor_.ExecuteSourceCopyOperation(
Kelvin Zhang23dfcd22021-08-31 16:32:49 -0700253 optimized, std::move(writer), source_fd);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400254}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400255
Tianjie8e0090d2021-08-30 22:35:21 -0700256bool PartitionWriter::PerformDiffOperation(const InstallOperation& operation,
257 ErrorCode* error,
258 const void* data,
259 size_t count) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400260 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
261 TEST_AND_RETURN_FALSE(source_fd != nullptr);
262
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500263 auto writer = CreateBaseExtentWriter();
Tianjie8e0090d2021-08-30 22:35:21 -0700264 return install_op_executor_.ExecuteDiffOperation(
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500265 operation, std::move(writer), source_fd, data, count);
266}
267
Kelvin Zhang50bac652020-09-28 15:51:41 -0400268FileDescriptorPtr PartitionWriter::ChooseSourceFD(
269 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500270 return verified_source_fd_.ChooseSourceFD(operation, error);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400271}
272
273int PartitionWriter::Close() {
274 int err = 0;
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500275
Kelvin Zhang50bac652020-09-28 15:51:41 -0400276 source_path_.clear();
277
278 if (target_fd_ && !target_fd_->Close()) {
279 err = errno;
280 PLOG(ERROR) << "Error closing target partition";
281 if (!err)
282 err = 1;
283 }
284 target_fd_.reset();
285 target_path_.clear();
286
Kelvin Zhang50bac652020-09-28 15:51:41 -0400287 return -err;
288}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400289
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400290void PartitionWriter::CheckpointUpdateProgress(size_t next_op_index) {
291 target_fd_->Flush();
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400292}
293
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400294std::unique_ptr<ExtentWriter> PartitionWriter::CreateBaseExtentWriter() {
Kelvin Zhang4d22ca22021-02-09 14:06:25 -0500295 return std::make_unique<DirectExtentWriter>(target_fd_);
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400296}
297
Kelvin Zhangb5bd0752022-03-10 15:45:25 -0800298bool PartitionWriter::ValidateSourceHash(const InstallOperation& operation,
299 const FileDescriptorPtr source_fd,
300 size_t block_size,
301 ErrorCode* error) {
302 brillo::Blob source_hash;
303 TEST_AND_RETURN_FALSE_ERRNO(fd_utils::ReadAndHashExtents(
304 source_fd, operation.src_extents(), block_size, &source_hash));
305 return ValidateSourceHash(source_hash, operation, source_fd, error);
306}
307
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500308bool PartitionWriter::ValidateSourceHash(const brillo::Blob& calculated_hash,
309 const InstallOperation& operation,
310 const FileDescriptorPtr source_fd,
311 ErrorCode* error) {
312 using std::string;
313 using std::vector;
314 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
315 operation.src_sha256_hash().end());
316 if (calculated_hash != expected_source_hash) {
317 LOG(ERROR) << "The hash of the source data on disk for this operation "
318 << "doesn't match the expected value. This could mean that the "
319 << "delta update payload was targeted for another version, or "
320 << "that the source partition was modified after it was "
321 << "installed, for example, by mounting a filesystem.";
322 LOG(ERROR) << "Expected: sha256|hex = "
323 << base::HexEncode(expected_source_hash.data(),
324 expected_source_hash.size());
325 LOG(ERROR) << "Calculated: sha256|hex = "
326 << base::HexEncode(calculated_hash.data(),
327 calculated_hash.size());
328
329 vector<string> source_extents;
330 for (const Extent& ext : operation.src_extents()) {
331 source_extents.push_back(
332 base::StringPrintf("%" PRIu64 ":%" PRIu64,
333 static_cast<uint64_t>(ext.start_block()),
334 static_cast<uint64_t>(ext.num_blocks())));
335 }
336 LOG(ERROR) << "Operation source (offset:size) in blocks: "
337 << base::JoinString(source_extents, ",");
338
339 // Log remount history if this device is an ext4 partition.
340 LogMountHistory(source_fd);
341
342 *error = ErrorCode::kDownloadStateInitializationError;
343 return false;
344 }
345 return true;
346}
347
Kelvin Zhang50bac652020-09-28 15:51:41 -0400348} // namespace chromeos_update_engine