xref: /aosp_15_r20/system/update_engine/payload_consumer/partition_writer.cc (revision 5a9231315b4521097b8dc3750bc806fcafe0c72f)
1 //
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>
20 #include <sys/mman.h>
21 
22 #include <inttypes.h>
23 
24 #include <algorithm>
25 #include <initializer_list>
26 #include <memory>
27 #include <string>
28 #include <utility>
29 #include <vector>
30 
31 #include <base/strings/string_number_conversions.h>
32 #include <android-base/stringprintf.h>
33 
34 #include "update_engine/common/error_code.h"
35 #include "update_engine/common/utils.h"
36 #include "update_engine/payload_consumer/cached_file_descriptor.h"
37 #include "update_engine/payload_consumer/extent_writer.h"
38 #include "update_engine/payload_consumer/file_descriptor_utils.h"
39 #include "update_engine/payload_consumer/install_operation_executor.h"
40 #include "update_engine/payload_consumer/install_plan.h"
41 #include "update_engine/payload_consumer/mount_history.h"
42 #include "update_engine/payload_generator/extent_utils.h"
43 
44 namespace chromeos_update_engine {
45 
46 namespace {
47 constexpr 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 
DiscardPartitionTail(const FileDescriptorPtr & fd,uint64_t data_size)53 bool 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 
84 // Opens path for read/write. On success returns an open FileDescriptor
85 // and sets *err to 0. On failure, sets *err to errno and returns nullptr.
OpenFile(const char * path,int mode,bool cache_writes,int * err)86 FileDescriptorPtr OpenFile(const char* path,
87                            int mode,
88                            bool cache_writes,
89                            int* err) {
90   // Try to mark the block device read-only based on the mode. Ignore any
91   // failure since this won't work when passing regular files.
92   bool read_only = (mode & O_ACCMODE) == O_RDONLY;
93   utils::SetBlockDeviceReadOnly(path, read_only);
94 
95   FileDescriptorPtr fd(new EintrSafeFileDescriptor());
96   if (cache_writes && !read_only) {
97     fd = FileDescriptorPtr(new CachedFileDescriptor(fd, kCacheSize));
98     LOG(INFO) << "Caching writes.";
99   }
100   if (!fd->Open(path, mode, 000)) {
101     *err = errno;
102     PLOG(ERROR) << "Unable to open file " << path;
103     return nullptr;
104   }
105   *err = 0;
106   return fd;
107 }
108 
PartitionWriter(const PartitionUpdate & partition_update,const InstallPlan::Partition & install_part,DynamicPartitionControlInterface * dynamic_control,size_t block_size,bool is_interactive)109 PartitionWriter::PartitionWriter(
110     const PartitionUpdate& partition_update,
111     const InstallPlan::Partition& install_part,
112     DynamicPartitionControlInterface* dynamic_control,
113     size_t block_size,
114     bool is_interactive)
115     : partition_update_(partition_update),
116       install_part_(install_part),
117       dynamic_control_(dynamic_control),
118       verified_source_fd_(block_size, install_part.source_path),
119       interactive_(is_interactive),
120       block_size_(block_size),
121       install_op_executor_(block_size) {}
122 
~PartitionWriter()123 PartitionWriter::~PartitionWriter() {
124   Close();
125 }
126 
OpenSourcePartition(uint32_t source_slot,bool source_may_exist)127 bool PartitionWriter::OpenSourcePartition(uint32_t source_slot,
128                                           bool source_may_exist) {
129   source_path_.clear();
130   if (!source_may_exist) {
131     return true;
132   }
133   if (install_part_.source_size > 0 && !install_part_.source_path.empty()) {
134     source_path_ = install_part_.source_path;
135     if (!verified_source_fd_.Open()) {
136       LOG(ERROR) << "Unable to open source partition " << install_part_.name
137                  << " on slot " << BootControlInterface::SlotName(source_slot)
138                  << ", file " << source_path_;
139       return false;
140     }
141   }
142   return true;
143 }
144 
Init(const InstallPlan * install_plan,bool source_may_exist,size_t next_op_index)145 bool PartitionWriter::Init(const InstallPlan* install_plan,
146                            bool source_may_exist,
147                            size_t next_op_index) {
148   const PartitionUpdate& partition = partition_update_;
149   uint32_t source_slot = install_plan->source_slot;
150   uint32_t target_slot = install_plan->target_slot;
151   TEST_AND_RETURN_FALSE(OpenSourcePartition(source_slot, source_may_exist));
152 
153   // We shouldn't open the source partition in certain cases, e.g. some dynamic
154   // partitions in delta payload, partitions included in the full payload for
155   // partial updates. Use the source size as the indicator.
156 
157   target_path_ = install_part_.target_path;
158   int err{};
159 
160   int flags = O_RDWR;
161   if (!interactive_)
162     flags |= O_DSYNC;
163 
164   LOG(INFO) << "Opening " << target_path_ << " partition with"
165             << (interactive_ ? "out" : "") << " O_DSYNC";
166 
167   target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
168   if (!target_fd_) {
169     LOG(ERROR) << "Unable to open target partition "
170                << partition.partition_name() << " on slot "
171                << BootControlInterface::SlotName(target_slot) << ", file "
172                << target_path_;
173     return false;
174   }
175 
176   LOG(INFO) << "Applying " << partition.operations().size()
177             << " operations to partition \"" << partition.partition_name()
178             << "\"";
179 
180   // Discard the end of the partition, but ignore failures.
181   DiscardPartitionTail(target_fd_, install_part_.target_size);
182 
183   return true;
184 }
185 
PerformReplaceOperation(const InstallOperation & operation,const void * data,size_t count)186 bool PartitionWriter::PerformReplaceOperation(const InstallOperation& operation,
187                                               const void* data,
188                                               size_t count) {
189   // Setup the ExtentWriter stack based on the operation type.
190   std::unique_ptr<ExtentWriter> writer = CreateBaseExtentWriter();
191   return install_op_executor_.ExecuteReplaceOperation(
192       operation, std::move(writer), data);
193 }
194 
PerformZeroOrDiscardOperation(const InstallOperation & operation)195 bool PartitionWriter::PerformZeroOrDiscardOperation(
196     const InstallOperation& operation) {
197 #ifdef BLKZEROOUT
198   int request =
199       (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
200 #else   // !defined(BLKZEROOUT)
201   auto writer = CreateBaseExtentWriter();
202   return install_op_executor_.ExecuteZeroOrDiscardOperation(operation,
203                                                             writer.get());
204 #endif  // !defined(BLKZEROOUT)
205 
206   for (const Extent& extent : operation.dst_extents()) {
207     const uint64_t start = extent.start_block() * block_size_;
208     const uint64_t length = extent.num_blocks() * block_size_;
209     int result = 0;
210     if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0) {
211       continue;
212     }
213     // In case of failure, we fall back to writing 0 for the entire operation.
214     PLOG(WARNING) << "BlkIoctl failed. Falling back to write 0s for remainder "
215                      "of this operation.";
216     auto writer = CreateBaseExtentWriter();
217     return install_op_executor_.ExecuteZeroOrDiscardOperation(
218         operation, std::move(writer));
219   }
220   return true;
221 }
222 
PerformSourceCopyOperation(const InstallOperation & operation,ErrorCode * error)223 bool PartitionWriter::PerformSourceCopyOperation(
224     const InstallOperation& operation, ErrorCode* error) {
225   // The device may optimize the SOURCE_COPY operation.
226   // Being this a device-specific optimization let DynamicPartitionController
227   // decide it the operation should be skipped.
228   const PartitionUpdate& partition = partition_update_;
229 
230   // Invoke ChooseSourceFD with original operation, so that it can properly
231   // verify source hashes. Optimized operation might contain a smaller set of
232   // extents, or completely empty.
233   auto source_fd = ChooseSourceFD(operation, error);
234   if (*error != ErrorCode::kSuccess || source_fd == nullptr) {
235     LOG(WARNING) << "Source hash mismatch detected for extents "
236                  << operation.src_extents() << " on partition "
237                  << partition.partition_name() << " @ " << source_path_;
238 
239     return false;
240   }
241 
242   InstallOperation buf;
243   const bool should_optimize = dynamic_control_->OptimizeOperation(
244       partition.partition_name(), operation, &buf);
245   const InstallOperation& optimized = should_optimize ? buf : operation;
246 
247   auto writer = CreateBaseExtentWriter();
248   return install_op_executor_.ExecuteSourceCopyOperation(
249       optimized, std::move(writer), source_fd);
250 }
251 
PerformDiffOperation(const InstallOperation & operation,ErrorCode * error,const void * data,size_t count)252 bool PartitionWriter::PerformDiffOperation(const InstallOperation& operation,
253                                            ErrorCode* error,
254                                            const void* data,
255                                            size_t count) {
256   FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
257   TEST_AND_RETURN_FALSE(source_fd != nullptr);
258 
259   auto writer = CreateBaseExtentWriter();
260   return install_op_executor_.ExecuteDiffOperation(
261       operation, std::move(writer), source_fd, data, count);
262 }
263 
ChooseSourceFD(const InstallOperation & operation,ErrorCode * error)264 FileDescriptorPtr PartitionWriter::ChooseSourceFD(
265     const InstallOperation& operation, ErrorCode* error) {
266   return verified_source_fd_.ChooseSourceFD(operation, error);
267 }
268 
Close()269 int PartitionWriter::Close() {
270   int err = 0;
271 
272   source_path_.clear();
273 
274   if (target_fd_ && !target_fd_->Close()) {
275     err = errno;
276     PLOG(ERROR) << "Error closing target partition";
277     if (!err)
278       err = 1;
279   }
280   target_fd_.reset();
281   target_path_.clear();
282 
283   return -err;
284 }
285 
CheckpointUpdateProgress(size_t next_op_index)286 void PartitionWriter::CheckpointUpdateProgress(size_t next_op_index) {
287   if (target_fd_) {
288     target_fd_->Flush();
289   }
290 }
291 
CreateBaseExtentWriter()292 std::unique_ptr<ExtentWriter> PartitionWriter::CreateBaseExtentWriter() {
293   return std::make_unique<DirectExtentWriter>(target_fd_);
294 }
295 
ValidateSourceHash(const InstallOperation & operation,const FileDescriptorPtr source_fd,size_t block_size,ErrorCode * error)296 bool PartitionWriter::ValidateSourceHash(const InstallOperation& operation,
297                                          const FileDescriptorPtr source_fd,
298                                          size_t block_size,
299                                          ErrorCode* error) {
300   brillo::Blob source_hash;
301   TEST_AND_RETURN_FALSE_ERRNO(fd_utils::ReadAndHashExtents(
302       source_fd, operation.src_extents(), block_size, &source_hash));
303   return ValidateSourceHash(source_hash, operation, source_fd, error);
304 }
305 
ValidateSourceHash(const brillo::Blob & calculated_hash,const InstallOperation & operation,const FileDescriptorPtr source_fd,ErrorCode * error)306 bool PartitionWriter::ValidateSourceHash(const brillo::Blob& calculated_hash,
307                                          const InstallOperation& operation,
308                                          const FileDescriptorPtr source_fd,
309                                          ErrorCode* error) {
310   using std::string;
311   using std::vector;
312   brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
313                                     operation.src_sha256_hash().end());
314   if (calculated_hash != expected_source_hash) {
315     LOG(ERROR) << "The hash of the source data on disk for this operation "
316                << "doesn't match the expected value. This could mean that the "
317                << "delta update payload was targeted for another version, or "
318                << "that the source partition was modified after it was "
319                << "installed, for example, by mounting a filesystem.";
320     LOG(ERROR) << "Expected:   sha256|hex = "
321                << base::HexEncode(expected_source_hash.data(),
322                                   expected_source_hash.size());
323     LOG(ERROR) << "Calculated: sha256|hex = "
324                << base::HexEncode(calculated_hash.data(),
325                                   calculated_hash.size());
326 
327     vector<string> source_extents;
328     for (const Extent& ext : operation.src_extents()) {
329       source_extents.push_back(
330           android::base::StringPrintf("%" PRIu64 ":%" PRIu64,
331                                       static_cast<uint64_t>(ext.start_block()),
332                                       static_cast<uint64_t>(ext.num_blocks())));
333     }
334     LOG(ERROR) << "Operation source (offset:size) in blocks: "
335                << android::base::Join(source_extents, ",");
336 
337     // Log remount history if this device is an ext4 partition.
338     LogMountHistory(source_fd);
339     if (error) {
340       *error = ErrorCode::kDownloadStateInitializationError;
341     }
342     return false;
343   }
344   return true;
345 }
346 
347 }  // namespace chromeos_update_engine
348