blob: 9db7ae0800de915ee7c38198f7fd2921f51059f9 [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"
42#include "update_engine/payload_consumer/install_plan.h"
43#include "update_engine/payload_consumer/mount_history.h"
44#include "update_engine/payload_consumer/payload_constants.h"
45#include "update_engine/payload_consumer/xz_extent_writer.h"
Kelvin Zhang37b9b702021-02-23 10:30:37 -050046#include "update_engine/payload_generator/extent_utils.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040047
48namespace chromeos_update_engine {
49
50namespace {
51constexpr uint64_t kCacheSize = 1024 * 1024; // 1MB
52
53// Discard the tail of the block device referenced by |fd|, from the offset
54// |data_size| until the end of the block device. Returns whether the data was
55// discarded.
56
57bool DiscardPartitionTail(const FileDescriptorPtr& fd, uint64_t data_size) {
58 uint64_t part_size = fd->BlockDevSize();
59 if (!part_size || part_size <= data_size)
60 return false;
61
62 struct blkioctl_request {
63 int number;
64 const char* name;
65 };
66 const std::initializer_list<blkioctl_request> blkioctl_requests = {
67 {BLKDISCARD, "BLKDISCARD"},
68 {BLKSECDISCARD, "BLKSECDISCARD"},
69#ifdef BLKZEROOUT
70 {BLKZEROOUT, "BLKZEROOUT"},
71#endif
72 };
73 for (const auto& req : blkioctl_requests) {
74 int error = 0;
75 if (fd->BlkIoctl(req.number, data_size, part_size - data_size, &error) &&
76 error == 0) {
77 return true;
78 }
79 LOG(WARNING) << "Error discarding the last "
80 << (part_size - data_size) / 1024 << " KiB using ioctl("
81 << req.name << ")";
82 }
83 return false;
84}
85
86} // namespace
87
Kelvin Zhang37b9b702021-02-23 10:30:37 -050088using google::protobuf::RepeatedPtrField;
89
Kelvin Zhang50bac652020-09-28 15:51:41 -040090// Opens path for read/write. On success returns an open FileDescriptor
91// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
92FileDescriptorPtr OpenFile(const char* path,
93 int mode,
94 bool cache_writes,
95 int* err) {
96 // Try to mark the block device read-only based on the mode. Ignore any
97 // failure since this won't work when passing regular files.
98 bool read_only = (mode & O_ACCMODE) == O_RDONLY;
99 utils::SetBlockDeviceReadOnly(path, read_only);
100
101 FileDescriptorPtr fd(new EintrSafeFileDescriptor());
102 if (cache_writes && !read_only) {
103 fd = FileDescriptorPtr(new CachedFileDescriptor(fd, kCacheSize));
104 LOG(INFO) << "Caching writes.";
105 }
106 if (!fd->Open(path, mode, 000)) {
107 *err = errno;
108 PLOG(ERROR) << "Unable to open file " << path;
109 return nullptr;
110 }
111 *err = 0;
112 return fd;
113}
114
Kelvin Zhang50bac652020-09-28 15:51:41 -0400115PartitionWriter::PartitionWriter(
116 const PartitionUpdate& partition_update,
117 const InstallPlan::Partition& install_part,
118 DynamicPartitionControlInterface* dynamic_control,
119 size_t block_size,
120 bool is_interactive)
121 : partition_update_(partition_update),
122 install_part_(install_part),
123 dynamic_control_(dynamic_control),
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500124 verified_source_fd_(block_size, install_part.source_path),
Kelvin Zhang50bac652020-09-28 15:51:41 -0400125 interactive_(is_interactive),
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500126 block_size_(block_size),
127 install_op_executor_(block_size) {}
Kelvin Zhang50bac652020-09-28 15:51:41 -0400128
129PartitionWriter::~PartitionWriter() {
130 Close();
131}
132
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500133bool PartitionWriter::OpenSourcePartition(uint32_t source_slot,
134 bool source_may_exist) {
135 source_path_.clear();
136 if (!source_may_exist) {
137 return true;
138 }
139 if (install_part_.source_size > 0 && !install_part_.source_path.empty()) {
140 source_path_ = install_part_.source_path;
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500141 if (!verified_source_fd_.Open()) {
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500142 LOG(ERROR) << "Unable to open source partition " << install_part_.name
143 << " on slot " << BootControlInterface::SlotName(source_slot)
144 << ", file " << source_path_;
145 return false;
146 }
147 }
148 return true;
149}
150
Kelvin Zhang50bac652020-09-28 15:51:41 -0400151bool PartitionWriter::Init(const InstallPlan* install_plan,
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400152 bool source_may_exist,
153 size_t next_op_index) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400154 const PartitionUpdate& partition = partition_update_;
155 uint32_t source_slot = install_plan->source_slot;
156 uint32_t target_slot = install_plan->target_slot;
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500157 TEST_AND_RETURN_FALSE(OpenSourcePartition(source_slot, source_may_exist));
Kelvin Zhang50bac652020-09-28 15:51:41 -0400158
159 // We shouldn't open the source partition in certain cases, e.g. some dynamic
160 // partitions in delta payload, partitions included in the full payload for
161 // partial updates. Use the source size as the indicator.
Kelvin Zhang50bac652020-09-28 15:51:41 -0400162
163 target_path_ = install_part_.target_path;
164 int err;
165
166 int flags = O_RDWR;
167 if (!interactive_)
168 flags |= O_DSYNC;
169
170 LOG(INFO) << "Opening " << target_path_ << " partition with"
171 << (interactive_ ? "out" : "") << " O_DSYNC";
172
173 target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
174 if (!target_fd_) {
175 LOG(ERROR) << "Unable to open target partition "
176 << partition.partition_name() << " on slot "
177 << BootControlInterface::SlotName(target_slot) << ", file "
178 << target_path_;
179 return false;
180 }
181
182 LOG(INFO) << "Applying " << partition.operations().size()
183 << " operations to partition \"" << partition.partition_name()
184 << "\"";
185
186 // Discard the end of the partition, but ignore failures.
187 DiscardPartitionTail(target_fd_, install_part_.target_size);
188
189 return true;
190}
191
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500192bool PartitionWriter::PerformReplaceOperation(const InstallOperation& operation,
193 const void* data,
194 size_t count) {
195 // Setup the ExtentWriter stack based on the operation type.
196 std::unique_ptr<ExtentWriter> writer = CreateBaseExtentWriter();
197 writer->Init(operation.dst_extents(), block_size_);
198 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();
224 writer->Init(operation.dst_extents(), block_size_);
225 return install_op_executor_.ExecuteZeroOrDiscardOperation(operation,
226 writer.get());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400227 }
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400228 return true;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400229}
230
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500231std::ostream& operator<<(std::ostream& out,
232 const RepeatedPtrField<Extent>& extents) {
233 if (extents.size() == 0) {
234 out << "[]";
235 return out;
236 }
237 out << "[";
238 auto begin = extents.begin();
239 out << *begin;
240 for (int i = 1; i < extents.size(); i++) {
241 ++begin;
242 out << ", " << *begin;
243 }
244 out << "]";
245 return out;
246}
247
Kelvin Zhang50bac652020-09-28 15:51:41 -0400248bool PartitionWriter::PerformSourceCopyOperation(
249 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400250 // The device may optimize the SOURCE_COPY operation.
251 // Being this a device-specific optimization let DynamicPartitionController
252 // decide it the operation should be skipped.
253 const PartitionUpdate& partition = partition_update_;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400254
255 InstallOperation buf;
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500256 const bool should_optimize = dynamic_control_->OptimizeOperation(
Kelvin Zhang50bac652020-09-28 15:51:41 -0400257 partition.partition_name(), operation, &buf);
258 const InstallOperation& optimized = should_optimize ? buf : operation;
259
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500260 // Invoke ChooseSourceFD with original operation, so that it can properly
261 // verify source hashes. Optimized operation might contain a smaller set of
262 // extents, or completely empty.
263 auto source_fd = ChooseSourceFD(operation, error);
264 if (source_fd == nullptr) {
265 LOG(ERROR) << "Unrecoverable source hash mismatch found on partition "
266 << partition.partition_name()
267 << " extents: " << operation.src_extents();
268 return false;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400269 }
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500270
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500271 auto writer = CreateBaseExtentWriter();
272 writer->Init(optimized.dst_extents(), block_size_);
273 return install_op_executor_.ExecuteSourceCopyOperation(
274 optimized, writer.get(), source_fd);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400275}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400276
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500277bool PartitionWriter::PerformSourceBsdiffOperation(
Kelvin Zhang50bac652020-09-28 15:51:41 -0400278 const InstallOperation& operation,
279 ErrorCode* error,
280 const void* data,
281 size_t count) {
282 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
283 TEST_AND_RETURN_FALSE(source_fd != nullptr);
284
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500285 auto writer = CreateBaseExtentWriter();
286 writer->Init(operation.dst_extents(), block_size_);
287 return install_op_executor_.ExecuteSourceBsdiffOperation(
288 operation, std::move(writer), source_fd, data, count);
289}
290
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500291bool PartitionWriter::PerformPuffDiffOperation(
292 const InstallOperation& operation,
293 ErrorCode* error,
294 const void* data,
295 size_t count) {
296 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
297 TEST_AND_RETURN_FALSE(source_fd != nullptr);
298
299 auto writer = CreateBaseExtentWriter();
300 writer->Init(operation.dst_extents(), block_size_);
301 return install_op_executor_.ExecutePuffDiffOperation(
302 operation, std::move(writer), source_fd, data, count);
303}
304
Kelvin Zhang50bac652020-09-28 15:51:41 -0400305FileDescriptorPtr PartitionWriter::ChooseSourceFD(
306 const InstallOperation& operation, ErrorCode* error) {
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500307 return verified_source_fd_.ChooseSourceFD(operation, error);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400308}
309
310int PartitionWriter::Close() {
311 int err = 0;
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500312
Kelvin Zhang50bac652020-09-28 15:51:41 -0400313 source_path_.clear();
314
315 if (target_fd_ && !target_fd_->Close()) {
316 err = errno;
317 PLOG(ERROR) << "Error closing target partition";
318 if (!err)
319 err = 1;
320 }
321 target_fd_.reset();
322 target_path_.clear();
323
Kelvin Zhang50bac652020-09-28 15:51:41 -0400324 return -err;
325}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400326
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400327void PartitionWriter::CheckpointUpdateProgress(size_t next_op_index) {
328 target_fd_->Flush();
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400329}
330
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400331std::unique_ptr<ExtentWriter> PartitionWriter::CreateBaseExtentWriter() {
Kelvin Zhang4d22ca22021-02-09 14:06:25 -0500332 return std::make_unique<DirectExtentWriter>(target_fd_);
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400333}
334
Kelvin Zhangab3ce602021-02-24 14:46:40 -0500335bool PartitionWriter::ValidateSourceHash(const brillo::Blob& calculated_hash,
336 const InstallOperation& operation,
337 const FileDescriptorPtr source_fd,
338 ErrorCode* error) {
339 using std::string;
340 using std::vector;
341 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
342 operation.src_sha256_hash().end());
343 if (calculated_hash != expected_source_hash) {
344 LOG(ERROR) << "The hash of the source data on disk for this operation "
345 << "doesn't match the expected value. This could mean that the "
346 << "delta update payload was targeted for another version, or "
347 << "that the source partition was modified after it was "
348 << "installed, for example, by mounting a filesystem.";
349 LOG(ERROR) << "Expected: sha256|hex = "
350 << base::HexEncode(expected_source_hash.data(),
351 expected_source_hash.size());
352 LOG(ERROR) << "Calculated: sha256|hex = "
353 << base::HexEncode(calculated_hash.data(),
354 calculated_hash.size());
355
356 vector<string> source_extents;
357 for (const Extent& ext : operation.src_extents()) {
358 source_extents.push_back(
359 base::StringPrintf("%" PRIu64 ":%" PRIu64,
360 static_cast<uint64_t>(ext.start_block()),
361 static_cast<uint64_t>(ext.num_blocks())));
362 }
363 LOG(ERROR) << "Operation source (offset:size) in blocks: "
364 << base::JoinString(source_extents, ",");
365
366 // Log remount history if this device is an ext4 partition.
367 LogMountHistory(source_fd);
368
369 *error = ErrorCode::kDownloadStateInitializationError;
370 return false;
371 }
372 return true;
373}
374
Kelvin Zhang50bac652020-09-28 15:51:41 -0400375} // namespace chromeos_update_engine