blob: 7922eb2e04cd178bb8c4e2a698067e5a07f6f72d [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();
198 writer->Init(operation.dst_extents(), block_size_);
199 return install_op_executor_.ExecuteReplaceOperation(
200 operation, std::move(writer), data, count);
201}
202
Kelvin Zhang50bac652020-09-28 15:51:41 -0400203bool PartitionWriter::PerformZeroOrDiscardOperation(
204 const InstallOperation& operation) {
205#ifdef BLKZEROOUT
Kelvin Zhang50bac652020-09-28 15:51:41 -0400206 int request =
207 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
208#else // !defined(BLKZEROOUT)
Kelvin Zhangf4575862021-02-24 10:46:32 -0500209 auto writer = CreateBaseExtentWriter();
210 return install_op_executor_.ExecuteZeroOrDiscardOperation(operation,
211 writer.get());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400212#endif // !defined(BLKZEROOUT)
213
Kelvin Zhang50bac652020-09-28 15:51:41 -0400214 for (const Extent& extent : operation.dst_extents()) {
215 const uint64_t start = extent.start_block() * block_size_;
216 const uint64_t length = extent.num_blocks() * block_size_;
Kelvin Zhangf4575862021-02-24 10:46:32 -0500217 int result = 0;
218 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0) {
219 continue;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400220 }
Kelvin Zhangf4575862021-02-24 10:46:32 -0500221 // In case of failure, we fall back to writing 0 for the entire operation.
222 PLOG(WARNING) << "BlkIoctl failed. Falling back to write 0s for remainder "
223 "of this operation.";
224 auto writer = CreateBaseExtentWriter();
225 writer->Init(operation.dst_extents(), block_size_);
226 return install_op_executor_.ExecuteZeroOrDiscardOperation(operation,
227 writer.get());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400228 }
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400229 return true;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400230}
231
232bool PartitionWriter::PerformSourceCopyOperation(
233 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400234 // The device may optimize the SOURCE_COPY operation.
235 // Being this a device-specific optimization let DynamicPartitionController
236 // decide it the operation should be skipped.
237 const PartitionUpdate& partition = partition_update_;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400238
239 InstallOperation buf;
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500240 const bool should_optimize = dynamic_control_->OptimizeOperation(
Kelvin Zhang50bac652020-09-28 15:51:41 -0400241 partition.partition_name(), operation, &buf);
242 const InstallOperation& optimized = should_optimize ? buf : operation;
243
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500244 // Invoke ChooseSourceFD with original operation, so that it can properly
245 // verify source hashes. Optimized operation might contain a smaller set of
246 // extents, or completely empty.
247 auto source_fd = ChooseSourceFD(operation, error);
248 if (source_fd == nullptr) {
249 LOG(ERROR) << "Unrecoverable source hash mismatch found on partition "
250 << partition.partition_name()
Kelvin Zhange52b6cd2021-02-09 15:28:40 -0500251 << " extents: " << ExtentsToString(operation.src_extents());
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500252 return false;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400253 }
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500254
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500255 auto writer = CreateBaseExtentWriter();
256 writer->Init(optimized.dst_extents(), block_size_);
257 return install_op_executor_.ExecuteSourceCopyOperation(
258 optimized, writer.get(), source_fd);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400259}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400260
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500261bool PartitionWriter::PerformSourceBsdiffOperation(
Kelvin Zhang50bac652020-09-28 15:51:41 -0400262 const InstallOperation& operation,
263 ErrorCode* error,
264 const void* data,
265 size_t count) {
266 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
267 TEST_AND_RETURN_FALSE(source_fd != nullptr);
268
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500269 auto writer = CreateBaseExtentWriter();
270 writer->Init(operation.dst_extents(), block_size_);
271 return install_op_executor_.ExecuteSourceBsdiffOperation(
272 operation, std::move(writer), source_fd, data, count);
273}
274
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500275bool PartitionWriter::PerformPuffDiffOperation(
276 const InstallOperation& operation,
277 ErrorCode* error,
278 const void* data,
279 size_t count) {
280 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
281 TEST_AND_RETURN_FALSE(source_fd != nullptr);
282
283 auto writer = CreateBaseExtentWriter();
284 writer->Init(operation.dst_extents(), block_size_);
285 return install_op_executor_.ExecutePuffDiffOperation(
286 operation, std::move(writer), source_fd, data, count);
287}
288
Kelvin Zhang50bac652020-09-28 15:51:41 -0400289FileDescriptorPtr PartitionWriter::ChooseSourceFD(
290 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500291 return verified_source_fd_.ChooseSourceFD(operation, error);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400292}
293
294int PartitionWriter::Close() {
295 int err = 0;
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500296
Kelvin Zhang50bac652020-09-28 15:51:41 -0400297 source_path_.clear();
298
299 if (target_fd_ && !target_fd_->Close()) {
300 err = errno;
301 PLOG(ERROR) << "Error closing target partition";
302 if (!err)
303 err = 1;
304 }
305 target_fd_.reset();
306 target_path_.clear();
307
Kelvin Zhang50bac652020-09-28 15:51:41 -0400308 return -err;
309}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400310
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400311void PartitionWriter::CheckpointUpdateProgress(size_t next_op_index) {
312 target_fd_->Flush();
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400313}
314
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400315std::unique_ptr<ExtentWriter> PartitionWriter::CreateBaseExtentWriter() {
Kelvin Zhang4d22ca22021-02-09 14:06:25 -0500316 return std::make_unique<DirectExtentWriter>(target_fd_);
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400317}
318
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500319bool PartitionWriter::ValidateSourceHash(const brillo::Blob& calculated_hash,
320 const InstallOperation& operation,
321 const FileDescriptorPtr source_fd,
322 ErrorCode* error) {
323 using std::string;
324 using std::vector;
325 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
326 operation.src_sha256_hash().end());
327 if (calculated_hash != expected_source_hash) {
328 LOG(ERROR) << "The hash of the source data on disk for this operation "
329 << "doesn't match the expected value. This could mean that the "
330 << "delta update payload was targeted for another version, or "
331 << "that the source partition was modified after it was "
332 << "installed, for example, by mounting a filesystem.";
333 LOG(ERROR) << "Expected: sha256|hex = "
334 << base::HexEncode(expected_source_hash.data(),
335 expected_source_hash.size());
336 LOG(ERROR) << "Calculated: sha256|hex = "
337 << base::HexEncode(calculated_hash.data(),
338 calculated_hash.size());
339
340 vector<string> source_extents;
341 for (const Extent& ext : operation.src_extents()) {
342 source_extents.push_back(
343 base::StringPrintf("%" PRIu64 ":%" PRIu64,
344 static_cast<uint64_t>(ext.start_block()),
345 static_cast<uint64_t>(ext.num_blocks())));
346 }
347 LOG(ERROR) << "Operation source (offset:size) in blocks: "
348 << base::JoinString(source_extents, ",");
349
350 // Log remount history if this device is an ext4 partition.
351 LogMountHistory(source_fd);
352
353 *error = ErrorCode::kDownloadStateInitializationError;
354 return false;
355 }
356 return true;
357}
358
Kelvin Zhang50bac652020-09-28 15:51:41 -0400359} // namespace chromeos_update_engine