blob: 4625a7af2a8c9cd84cfd5995ba901f5d8b67aa56 [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
Kelvin Zhang37b9b702021-02-23 10:30:37 -050089using google::protobuf::RepeatedPtrField;
90
Kelvin Zhang50bac652020-09-28 15:51:41 -040091// Opens path for read/write. On success returns an open FileDescriptor
92// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
93FileDescriptorPtr OpenFile(const char* path,
94 int mode,
95 bool cache_writes,
96 int* err) {
97 // Try to mark the block device read-only based on the mode. Ignore any
98 // failure since this won't work when passing regular files.
99 bool read_only = (mode & O_ACCMODE) == O_RDONLY;
100 utils::SetBlockDeviceReadOnly(path, read_only);
101
102 FileDescriptorPtr fd(new EintrSafeFileDescriptor());
103 if (cache_writes && !read_only) {
104 fd = FileDescriptorPtr(new CachedFileDescriptor(fd, kCacheSize));
105 LOG(INFO) << "Caching writes.";
106 }
107 if (!fd->Open(path, mode, 000)) {
108 *err = errno;
109 PLOG(ERROR) << "Unable to open file " << path;
110 return nullptr;
111 }
112 *err = 0;
113 return fd;
114}
115
Kelvin Zhang50bac652020-09-28 15:51:41 -0400116PartitionWriter::PartitionWriter(
117 const PartitionUpdate& partition_update,
118 const InstallPlan::Partition& install_part,
119 DynamicPartitionControlInterface* dynamic_control,
120 size_t block_size,
121 bool is_interactive)
122 : partition_update_(partition_update),
123 install_part_(install_part),
124 dynamic_control_(dynamic_control),
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500125 verified_source_fd_(block_size, install_part.source_path),
Kelvin Zhang50bac652020-09-28 15:51:41 -0400126 interactive_(is_interactive),
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500127 block_size_(block_size),
128 install_op_executor_(block_size) {}
Kelvin Zhang50bac652020-09-28 15:51:41 -0400129
130PartitionWriter::~PartitionWriter() {
131 Close();
132}
133
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500134bool PartitionWriter::OpenSourcePartition(uint32_t source_slot,
135 bool source_may_exist) {
136 source_path_.clear();
137 if (!source_may_exist) {
138 return true;
139 }
140 if (install_part_.source_size > 0 && !install_part_.source_path.empty()) {
141 source_path_ = install_part_.source_path;
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500142 if (!verified_source_fd_.Open()) {
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500143 LOG(ERROR) << "Unable to open source partition " << install_part_.name
144 << " on slot " << BootControlInterface::SlotName(source_slot)
145 << ", file " << source_path_;
146 return false;
147 }
148 }
149 return true;
150}
151
Kelvin Zhang50bac652020-09-28 15:51:41 -0400152bool PartitionWriter::Init(const InstallPlan* install_plan,
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400153 bool source_may_exist,
154 size_t next_op_index) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400155 const PartitionUpdate& partition = partition_update_;
156 uint32_t source_slot = install_plan->source_slot;
157 uint32_t target_slot = install_plan->target_slot;
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500158 TEST_AND_RETURN_FALSE(OpenSourcePartition(source_slot, source_may_exist));
Kelvin Zhang50bac652020-09-28 15:51:41 -0400159
160 // We shouldn't open the source partition in certain cases, e.g. some dynamic
161 // partitions in delta payload, partitions included in the full payload for
162 // partial updates. Use the source size as the indicator.
Kelvin Zhang50bac652020-09-28 15:51:41 -0400163
164 target_path_ = install_part_.target_path;
165 int err;
166
167 int flags = O_RDWR;
168 if (!interactive_)
169 flags |= O_DSYNC;
170
171 LOG(INFO) << "Opening " << target_path_ << " partition with"
172 << (interactive_ ? "out" : "") << " O_DSYNC";
173
174 target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
175 if (!target_fd_) {
176 LOG(ERROR) << "Unable to open target partition "
177 << partition.partition_name() << " on slot "
178 << BootControlInterface::SlotName(target_slot) << ", file "
179 << target_path_;
180 return false;
181 }
182
183 LOG(INFO) << "Applying " << partition.operations().size()
184 << " operations to partition \"" << partition.partition_name()
185 << "\"";
186
187 // Discard the end of the partition, but ignore failures.
188 DiscardPartitionTail(target_fd_, install_part_.target_size);
189
190 return true;
191}
192
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500193bool PartitionWriter::PerformReplaceOperation(const InstallOperation& operation,
194 const void* data,
195 size_t count) {
196 // Setup the ExtentWriter stack based on the operation type.
197 std::unique_ptr<ExtentWriter> writer = CreateBaseExtentWriter();
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500198 return install_op_executor_.ExecuteReplaceOperation(
199 operation, std::move(writer), data, count);
200}
201
Kelvin Zhang50bac652020-09-28 15:51:41 -0400202bool PartitionWriter::PerformZeroOrDiscardOperation(
203 const InstallOperation& operation) {
204#ifdef BLKZEROOUT
Kelvin Zhang50bac652020-09-28 15:51:41 -0400205 int request =
206 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
207#else // !defined(BLKZEROOUT)
Kelvin Zhangf4575862021-02-24 10:46:32 -0500208 auto writer = CreateBaseExtentWriter();
209 return install_op_executor_.ExecuteZeroOrDiscardOperation(operation,
210 writer.get());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400211#endif // !defined(BLKZEROOUT)
212
Kelvin Zhang50bac652020-09-28 15:51:41 -0400213 for (const Extent& extent : operation.dst_extents()) {
214 const uint64_t start = extent.start_block() * block_size_;
215 const uint64_t length = extent.num_blocks() * block_size_;
Kelvin Zhangf4575862021-02-24 10:46:32 -0500216 int result = 0;
217 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0) {
218 continue;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400219 }
Kelvin Zhangf4575862021-02-24 10:46:32 -0500220 // In case of failure, we fall back to writing 0 for the entire operation.
221 PLOG(WARNING) << "BlkIoctl failed. Falling back to write 0s for remainder "
222 "of this operation.";
223 auto writer = CreateBaseExtentWriter();
Kelvin Zhang23dfcd22021-08-31 16:32:49 -0700224 return install_op_executor_.ExecuteZeroOrDiscardOperation(
225 operation, std::move(writer));
Kelvin Zhang50bac652020-09-28 15:51:41 -0400226 }
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400227 return true;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400228}
229
230bool PartitionWriter::PerformSourceCopyOperation(
231 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400232 // The device may optimize the SOURCE_COPY operation.
233 // Being this a device-specific optimization let DynamicPartitionController
234 // decide it the operation should be skipped.
235 const PartitionUpdate& partition = partition_update_;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400236
237 InstallOperation buf;
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500238 const bool should_optimize = dynamic_control_->OptimizeOperation(
Kelvin Zhang50bac652020-09-28 15:51:41 -0400239 partition.partition_name(), operation, &buf);
240 const InstallOperation& optimized = should_optimize ? buf : operation;
241
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500242 // Invoke ChooseSourceFD with original operation, so that it can properly
243 // verify source hashes. Optimized operation might contain a smaller set of
244 // extents, or completely empty.
245 auto source_fd = ChooseSourceFD(operation, error);
246 if (source_fd == nullptr) {
247 LOG(ERROR) << "Unrecoverable source hash mismatch found on partition "
248 << partition.partition_name()
Kelvin Zhange52b6cd2021-02-09 15:28:40 -0500249 << " extents: " << ExtentsToString(operation.src_extents());
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500250 return false;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400251 }
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500252
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500253 auto writer = CreateBaseExtentWriter();
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500254 return install_op_executor_.ExecuteSourceCopyOperation(
Kelvin Zhang23dfcd22021-08-31 16:32:49 -0700255 optimized, std::move(writer), source_fd);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400256}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400257
Tianjie8e0090d2021-08-30 22:35:21 -0700258bool PartitionWriter::PerformDiffOperation(const InstallOperation& operation,
259 ErrorCode* error,
260 const void* data,
261 size_t count) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400262 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
263 TEST_AND_RETURN_FALSE(source_fd != nullptr);
264
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500265 auto writer = CreateBaseExtentWriter();
Tianjie8e0090d2021-08-30 22:35:21 -0700266 return install_op_executor_.ExecuteDiffOperation(
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500267 operation, std::move(writer), source_fd, data, count);
268}
269
Kelvin Zhang50bac652020-09-28 15:51:41 -0400270FileDescriptorPtr PartitionWriter::ChooseSourceFD(
271 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500272 return verified_source_fd_.ChooseSourceFD(operation, error);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400273}
274
275int PartitionWriter::Close() {
276 int err = 0;
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500277
Kelvin Zhang50bac652020-09-28 15:51:41 -0400278 source_path_.clear();
279
280 if (target_fd_ && !target_fd_->Close()) {
281 err = errno;
282 PLOG(ERROR) << "Error closing target partition";
283 if (!err)
284 err = 1;
285 }
286 target_fd_.reset();
287 target_path_.clear();
288
Kelvin Zhang50bac652020-09-28 15:51:41 -0400289 return -err;
290}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400291
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400292void PartitionWriter::CheckpointUpdateProgress(size_t next_op_index) {
293 target_fd_->Flush();
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400294}
295
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400296std::unique_ptr<ExtentWriter> PartitionWriter::CreateBaseExtentWriter() {
Kelvin Zhang4d22ca22021-02-09 14:06:25 -0500297 return std::make_unique<DirectExtentWriter>(target_fd_);
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400298}
299
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500300bool PartitionWriter::ValidateSourceHash(const brillo::Blob& calculated_hash,
301 const InstallOperation& operation,
302 const FileDescriptorPtr source_fd,
303 ErrorCode* error) {
304 using std::string;
305 using std::vector;
306 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
307 operation.src_sha256_hash().end());
308 if (calculated_hash != expected_source_hash) {
309 LOG(ERROR) << "The hash of the source data on disk for this operation "
310 << "doesn't match the expected value. This could mean that the "
311 << "delta update payload was targeted for another version, or "
312 << "that the source partition was modified after it was "
313 << "installed, for example, by mounting a filesystem.";
314 LOG(ERROR) << "Expected: sha256|hex = "
315 << base::HexEncode(expected_source_hash.data(),
316 expected_source_hash.size());
317 LOG(ERROR) << "Calculated: sha256|hex = "
318 << base::HexEncode(calculated_hash.data(),
319 calculated_hash.size());
320
321 vector<string> source_extents;
322 for (const Extent& ext : operation.src_extents()) {
323 source_extents.push_back(
324 base::StringPrintf("%" PRIu64 ":%" PRIu64,
325 static_cast<uint64_t>(ext.start_block()),
326 static_cast<uint64_t>(ext.num_blocks())));
327 }
328 LOG(ERROR) << "Operation source (offset:size) in blocks: "
329 << base::JoinString(source_extents, ",");
330
331 // Log remount history if this device is an ext4 partition.
332 LogMountHistory(source_fd);
333
334 *error = ErrorCode::kDownloadStateInitializationError;
335 return false;
336 }
337 return true;
338}
339
Kelvin Zhang50bac652020-09-28 15:51:41 -0400340} // namespace chromeos_update_engine