blob: 4df0af6e6128026aee74f171fa747d305b75f899 [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
22#include <algorithm>
23#include <initializer_list>
24#include <memory>
25#include <utility>
26#include <vector>
27
28#include <base/strings/string_number_conversions.h>
Kelvin Zhang50bac652020-09-28 15:51:41 -040029
30#include "update_engine/common/terminator.h"
31#include "update_engine/common/utils.h"
32#include "update_engine/payload_consumer/bzip_extent_writer.h"
33#include "update_engine/payload_consumer/cached_file_descriptor.h"
34#include "update_engine/payload_consumer/extent_reader.h"
35#include "update_engine/payload_consumer/extent_writer.h"
36#include "update_engine/payload_consumer/fec_file_descriptor.h"
37#include "update_engine/payload_consumer/file_descriptor_utils.h"
38#include "update_engine/payload_consumer/install_plan.h"
39#include "update_engine/payload_consumer/mount_history.h"
40#include "update_engine/payload_consumer/payload_constants.h"
41#include "update_engine/payload_consumer/xz_extent_writer.h"
Kelvin Zhang37b9b702021-02-23 10:30:37 -050042#include "update_engine/payload_generator/extent_utils.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040043
44namespace chromeos_update_engine {
45
46namespace {
47constexpr uint64_t kCacheSize = 1024 * 1024; // 1MB
48
49// Discard the tail of the block device referenced by |fd|, from the offset
50// |data_size| until the end of the block device. Returns whether the data was
51// discarded.
52
53bool DiscardPartitionTail(const FileDescriptorPtr& fd, uint64_t data_size) {
54 uint64_t part_size = fd->BlockDevSize();
55 if (!part_size || part_size <= data_size)
56 return false;
57
58 struct blkioctl_request {
59 int number;
60 const char* name;
61 };
62 const std::initializer_list<blkioctl_request> blkioctl_requests = {
63 {BLKDISCARD, "BLKDISCARD"},
64 {BLKSECDISCARD, "BLKSECDISCARD"},
65#ifdef BLKZEROOUT
66 {BLKZEROOUT, "BLKZEROOUT"},
67#endif
68 };
69 for (const auto& req : blkioctl_requests) {
70 int error = 0;
71 if (fd->BlkIoctl(req.number, data_size, part_size - data_size, &error) &&
72 error == 0) {
73 return true;
74 }
75 LOG(WARNING) << "Error discarding the last "
76 << (part_size - data_size) / 1024 << " KiB using ioctl("
77 << req.name << ")";
78 }
79 return false;
80}
81
82} // namespace
83
Kelvin Zhang37b9b702021-02-23 10:30:37 -050084using google::protobuf::RepeatedPtrField;
85
Kelvin Zhang50bac652020-09-28 15:51:41 -040086// Opens path for read/write. On success returns an open FileDescriptor
87// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
88FileDescriptorPtr OpenFile(const char* path,
89 int mode,
90 bool cache_writes,
91 int* err) {
92 // Try to mark the block device read-only based on the mode. Ignore any
93 // failure since this won't work when passing regular files.
94 bool read_only = (mode & O_ACCMODE) == O_RDONLY;
95 utils::SetBlockDeviceReadOnly(path, read_only);
96
97 FileDescriptorPtr fd(new EintrSafeFileDescriptor());
98 if (cache_writes && !read_only) {
99 fd = FileDescriptorPtr(new CachedFileDescriptor(fd, kCacheSize));
100 LOG(INFO) << "Caching writes.";
101 }
102 if (!fd->Open(path, mode, 000)) {
103 *err = errno;
104 PLOG(ERROR) << "Unable to open file " << path;
105 return nullptr;
106 }
107 *err = 0;
108 return fd;
109}
110
Kelvin Zhang50bac652020-09-28 15:51:41 -0400111PartitionWriter::PartitionWriter(
112 const PartitionUpdate& partition_update,
113 const InstallPlan::Partition& install_part,
114 DynamicPartitionControlInterface* dynamic_control,
115 size_t block_size,
116 bool is_interactive)
117 : partition_update_(partition_update),
118 install_part_(install_part),
119 dynamic_control_(dynamic_control),
120 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;
136 int err;
137 source_fd_ = OpenFile(source_path_.c_str(), O_RDONLY, false, &err);
138 if (source_fd_ == nullptr) {
139 LOG(ERROR) << "Unable to open source partition " << install_part_.name
140 << " on slot " << BootControlInterface::SlotName(source_slot)
141 << ", file " << source_path_;
142 return false;
143 }
144 }
145 return true;
146}
147
Kelvin Zhang50bac652020-09-28 15:51:41 -0400148bool PartitionWriter::Init(const InstallPlan* install_plan,
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400149 bool source_may_exist,
150 size_t next_op_index) {
Kelvin Zhang50bac652020-09-28 15:51:41 -0400151 const PartitionUpdate& partition = partition_update_;
152 uint32_t source_slot = install_plan->source_slot;
153 uint32_t target_slot = install_plan->target_slot;
Kelvin Zhang3f60d532020-11-09 13:33:17 -0500154 TEST_AND_RETURN_FALSE(OpenSourcePartition(source_slot, source_may_exist));
Kelvin Zhang50bac652020-09-28 15:51:41 -0400155
156 // We shouldn't open the source partition in certain cases, e.g. some dynamic
157 // partitions in delta payload, partitions included in the full payload for
158 // partial updates. Use the source size as the indicator.
Kelvin Zhang50bac652020-09-28 15:51:41 -0400159
160 target_path_ = install_part_.target_path;
161 int err;
162
163 int flags = O_RDWR;
164 if (!interactive_)
165 flags |= O_DSYNC;
166
167 LOG(INFO) << "Opening " << target_path_ << " partition with"
168 << (interactive_ ? "out" : "") << " O_DSYNC";
169
170 target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
171 if (!target_fd_) {
172 LOG(ERROR) << "Unable to open target partition "
173 << partition.partition_name() << " on slot "
174 << BootControlInterface::SlotName(target_slot) << ", file "
175 << target_path_;
176 return false;
177 }
178
179 LOG(INFO) << "Applying " << partition.operations().size()
180 << " operations to partition \"" << partition.partition_name()
181 << "\"";
182
183 // Discard the end of the partition, but ignore failures.
184 DiscardPartitionTail(target_fd_, install_part_.target_size);
185
186 return true;
187}
188
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500189bool PartitionWriter::PerformReplaceOperation(const InstallOperation& operation,
190 const void* data,
191 size_t count) {
192 // Setup the ExtentWriter stack based on the operation type.
193 std::unique_ptr<ExtentWriter> writer = CreateBaseExtentWriter();
194 writer->Init(operation.dst_extents(), block_size_);
195 return install_op_executor_.ExecuteReplaceOperation(
196 operation, std::move(writer), data, count);
197}
198
Kelvin Zhang50bac652020-09-28 15:51:41 -0400199bool PartitionWriter::PerformZeroOrDiscardOperation(
200 const InstallOperation& operation) {
201#ifdef BLKZEROOUT
Kelvin Zhang50bac652020-09-28 15:51:41 -0400202 int request =
203 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
204#else // !defined(BLKZEROOUT)
Kelvin Zhangf4575862021-02-24 10:46:32 -0500205 auto writer = CreateBaseExtentWriter();
206 return install_op_executor_.ExecuteZeroOrDiscardOperation(operation,
207 writer.get());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400208#endif // !defined(BLKZEROOUT)
209
Kelvin Zhang50bac652020-09-28 15:51:41 -0400210 for (const Extent& extent : operation.dst_extents()) {
211 const uint64_t start = extent.start_block() * block_size_;
212 const uint64_t length = extent.num_blocks() * block_size_;
Kelvin Zhangf4575862021-02-24 10:46:32 -0500213 int result = 0;
214 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0) {
215 continue;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400216 }
Kelvin Zhangf4575862021-02-24 10:46:32 -0500217 // In case of failure, we fall back to writing 0 for the entire operation.
218 PLOG(WARNING) << "BlkIoctl failed. Falling back to write 0s for remainder "
219 "of this operation.";
220 auto writer = CreateBaseExtentWriter();
221 writer->Init(operation.dst_extents(), block_size_);
222 return install_op_executor_.ExecuteZeroOrDiscardOperation(operation,
223 writer.get());
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
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500228std::ostream& operator<<(std::ostream& out,
229 const RepeatedPtrField<Extent>& extents) {
230 if (extents.size() == 0) {
231 out << "[]";
232 return out;
233 }
234 out << "[";
235 auto begin = extents.begin();
236 out << *begin;
237 for (int i = 1; i < extents.size(); i++) {
238 ++begin;
239 out << ", " << *begin;
240 }
241 out << "]";
242 return out;
243}
244
Kelvin Zhang50bac652020-09-28 15:51:41 -0400245bool PartitionWriter::PerformSourceCopyOperation(
246 const InstallOperation& operation, ErrorCode* error) {
247 TEST_AND_RETURN_FALSE(source_fd_ != nullptr);
248
249 // The device may optimize the SOURCE_COPY operation.
250 // Being this a device-specific optimization let DynamicPartitionController
251 // decide it the operation should be skipped.
252 const PartitionUpdate& partition = partition_update_;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400253
254 InstallOperation buf;
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500255 const bool should_optimize = dynamic_control_->OptimizeOperation(
Kelvin Zhang50bac652020-09-28 15:51:41 -0400256 partition.partition_name(), operation, &buf);
257 const InstallOperation& optimized = should_optimize ? buf : operation;
258
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500259 // Invoke ChooseSourceFD with original operation, so that it can properly
260 // verify source hashes. Optimized operation might contain a smaller set of
261 // extents, or completely empty.
262 auto source_fd = ChooseSourceFD(operation, error);
263 if (source_fd == nullptr) {
264 LOG(ERROR) << "Unrecoverable source hash mismatch found on partition "
265 << partition.partition_name()
266 << " extents: " << operation.src_extents();
267 return false;
Kelvin Zhang50bac652020-09-28 15:51:41 -0400268 }
Kelvin Zhang37b9b702021-02-23 10:30:37 -0500269
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500270 auto writer = CreateBaseExtentWriter();
271 writer->Init(optimized.dst_extents(), block_size_);
272 return install_op_executor_.ExecuteSourceCopyOperation(
273 optimized, writer.get(), source_fd);
Kelvin Zhang50bac652020-09-28 15:51:41 -0400274}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400275
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500276bool PartitionWriter::PerformSourceBsdiffOperation(
Kelvin Zhang50bac652020-09-28 15:51:41 -0400277 const InstallOperation& operation,
278 ErrorCode* error,
279 const void* data,
280 size_t count) {
281 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
282 TEST_AND_RETURN_FALSE(source_fd != nullptr);
283
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500284 auto writer = CreateBaseExtentWriter();
285 writer->Init(operation.dst_extents(), block_size_);
286 return install_op_executor_.ExecuteSourceBsdiffOperation(
287 operation, std::move(writer), source_fd, data, count);
288}
289
Kelvin Zhang1d402cb2021-02-09 15:28:16 -0500290bool PartitionWriter::PerformPuffDiffOperation(
291 const InstallOperation& operation,
292 ErrorCode* error,
293 const void* data,
294 size_t count) {
295 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
296 TEST_AND_RETURN_FALSE(source_fd != nullptr);
297
298 auto writer = CreateBaseExtentWriter();
299 writer->Init(operation.dst_extents(), block_size_);
300 return install_op_executor_.ExecutePuffDiffOperation(
301 operation, std::move(writer), source_fd, data, count);
302}
303
Kelvin Zhang50bac652020-09-28 15:51:41 -0400304FileDescriptorPtr PartitionWriter::ChooseSourceFD(
305 const InstallOperation& operation, ErrorCode* error) {
306 if (source_fd_ == nullptr) {
307 LOG(ERROR) << "ChooseSourceFD fail: source_fd_ == nullptr";
308 return nullptr;
309 }
310
311 if (!operation.has_src_sha256_hash()) {
312 // When the operation doesn't include a source hash, we attempt the error
Kelvin Zhangf4575862021-02-24 10:46:32 -0500313 // corrected device first since we can't verify the block in the raw
314 // device at this point, but we first need to make sure all extents are
315 // readable since the error corrected device can be shorter or not
316 // available.
Kelvin Zhang50bac652020-09-28 15:51:41 -0400317 if (OpenCurrentECCPartition() &&
318 fd_utils::ReadAndHashExtents(
319 source_ecc_fd_, operation.src_extents(), block_size_, nullptr)) {
320 return source_ecc_fd_;
321 }
322 return source_fd_;
323 }
324
325 brillo::Blob source_hash;
326 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
327 operation.src_sha256_hash().end());
328 if (fd_utils::ReadAndHashExtents(
329 source_fd_, operation.src_extents(), block_size_, &source_hash) &&
330 source_hash == expected_source_hash) {
331 return source_fd_;
332 }
333 // We fall back to use the error corrected device if the hash of the raw
334 // device doesn't match or there was an error reading the source partition.
335 if (!OpenCurrentECCPartition()) {
336 // The following function call will return false since the source hash
337 // mismatches, but we still want to call it so it prints the appropriate
338 // log message.
339 ValidateSourceHash(source_hash, operation, source_fd_, error);
340 return nullptr;
341 }
342 LOG(WARNING) << "Source hash from RAW device mismatched: found "
343 << base::HexEncode(source_hash.data(), source_hash.size())
344 << ", expected "
345 << base::HexEncode(expected_source_hash.data(),
346 expected_source_hash.size());
347
348 if (fd_utils::ReadAndHashExtents(
349 source_ecc_fd_, operation.src_extents(), block_size_, &source_hash) &&
350 ValidateSourceHash(source_hash, operation, source_ecc_fd_, error)) {
351 // At this point reading from the error corrected device worked, but
352 // reading from the raw device failed, so this is considered a recovered
353 // failure.
354 source_ecc_recovered_failures_++;
355 return source_ecc_fd_;
356 }
357 return nullptr;
358}
359
360bool PartitionWriter::OpenCurrentECCPartition() {
361 // No support for ECC for full payloads.
362 // Full payload should not have any opeartion that requires ECC partitions.
363 if (source_ecc_fd_)
364 return true;
365
366 if (source_ecc_open_failure_)
367 return false;
368
369#if USE_FEC
370 const PartitionUpdate& partition = partition_update_;
371 const InstallPlan::Partition& install_part = install_part_;
372 std::string path = install_part.source_path;
373 FileDescriptorPtr fd(new FecFileDescriptor());
374 if (!fd->Open(path.c_str(), O_RDONLY, 0)) {
375 PLOG(ERROR) << "Unable to open ECC source partition "
376 << partition.partition_name() << ", file " << path;
377 source_ecc_open_failure_ = true;
378 return false;
379 }
380 source_ecc_fd_ = fd;
381#else
382 // No support for ECC compiled.
383 source_ecc_open_failure_ = true;
384#endif // USE_FEC
385
386 return !source_ecc_open_failure_;
387}
388
389int PartitionWriter::Close() {
390 int err = 0;
391 if (source_fd_ && !source_fd_->Close()) {
392 err = errno;
393 PLOG(ERROR) << "Error closing source partition";
394 if (!err)
395 err = 1;
396 }
397 source_fd_.reset();
398 source_path_.clear();
399
400 if (target_fd_ && !target_fd_->Close()) {
401 err = errno;
402 PLOG(ERROR) << "Error closing target partition";
403 if (!err)
404 err = 1;
405 }
406 target_fd_.reset();
407 target_path_.clear();
408
409 if (source_ecc_fd_ && !source_ecc_fd_->Close()) {
410 err = errno;
411 PLOG(ERROR) << "Error closing ECC source partition";
412 if (!err)
413 err = 1;
414 }
415 source_ecc_fd_.reset();
416 source_ecc_open_failure_ = false;
417 return -err;
418}
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400419
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400420void PartitionWriter::CheckpointUpdateProgress(size_t next_op_index) {
421 target_fd_->Flush();
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400422}
423
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400424std::unique_ptr<ExtentWriter> PartitionWriter::CreateBaseExtentWriter() {
Kelvin Zhang4d22ca22021-02-09 14:06:25 -0500425 return std::make_unique<DirectExtentWriter>(target_fd_);
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400426}
427
Kelvin Zhang50bac652020-09-28 15:51:41 -0400428} // namespace chromeos_update_engine