• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 #include "update_engine/payload_consumer/vabc_partition_writer.h"
18 
19 #include <algorithm>
20 #include <map>
21 #include <memory>
22 #include <string>
23 #include <utility>
24 #include <vector>
25 
26 #include <android-base/properties.h>
27 #include <brillo/secure_blob.h>
28 #include <libsnapshot/cow_writer.h>
29 
30 #include "update_engine/common/cow_operation_convert.h"
31 #include "update_engine/common/utils.h"
32 #include "update_engine/payload_consumer/block_extent_writer.h"
33 #include "update_engine/payload_consumer/extent_map.h"
34 #include "update_engine/payload_consumer/extent_reader.h"
35 #include "update_engine/payload_consumer/file_descriptor.h"
36 #include "update_engine/payload_consumer/file_descriptor_utils.h"
37 #include "update_engine/payload_consumer/install_plan.h"
38 #include "update_engine/payload_consumer/partition_writer.h"
39 #include "update_engine/payload_consumer/snapshot_extent_writer.h"
40 #include "update_engine/payload_consumer/xor_extent_writer.h"
41 #include "update_engine/payload_generator/extent_ranges.h"
42 #include "update_engine/payload_generator/extent_utils.h"
43 #include "update_engine/update_metadata.pb.h"
44 
45 namespace chromeos_update_engine {
46 // Expected layout of COW file:
47 // === Beginning of Cow Image ===
48 // All Source Copy Operations
49 // ========== Label 0 ==========
50 // Operation 0 in PartitionUpdate
51 // ========== Label 1 ==========
52 // Operation 1 in PartitionUpdate
53 // ========== label 2 ==========
54 // Operation 2 in PartitionUpdate
55 // ========== label 3 ==========
56 // .
57 // .
58 // .
59 
60 // When resuming, pass |next_op_index_| as label to
61 // |InitializeWithAppend|.
62 // For example, suppose we finished writing SOURCE_COPY, and we finished writing
63 // operation 2 completely. Update is suspended when we are half way through
64 // operation 3.
65 // |cnext_op_index_| would be 3, so we pass 3 as
66 // label to |InitializeWithAppend|. The CowWriter will retain all data before
67 // label 3, Which contains all operation 2's data, but none of operation 3's
68 // data.
69 
70 using android::snapshot::ICowWriter;
71 using ::google::protobuf::RepeatedPtrField;
72 
73 // Compute XOR map, a map from dst extent to corresponding merge operation
ComputeXorMap(const RepeatedPtrField<CowMergeOperation> & merge_ops)74 static ExtentMap<const CowMergeOperation*, ExtentLess> ComputeXorMap(
75     const RepeatedPtrField<CowMergeOperation>& merge_ops) {
76   ExtentMap<const CowMergeOperation*, ExtentLess> xor_map;
77   for (const auto& merge_op : merge_ops) {
78     if (merge_op.type() == CowMergeOperation::COW_XOR) {
79       xor_map.AddExtent(merge_op.dst_extent(), &merge_op);
80     }
81   }
82   return xor_map;
83 }
84 
VABCPartitionWriter(const PartitionUpdate & partition_update,const InstallPlan::Partition & install_part,DynamicPartitionControlInterface * dynamic_control,size_t block_size)85 VABCPartitionWriter::VABCPartitionWriter(
86     const PartitionUpdate& partition_update,
87     const InstallPlan::Partition& install_part,
88     DynamicPartitionControlInterface* dynamic_control,
89     size_t block_size)
90     : partition_update_(partition_update),
91       install_part_(install_part),
92       dynamic_control_(dynamic_control),
93       block_size_(block_size),
94       executor_(block_size),
95       verified_source_fd_(block_size, install_part.source_path) {}
96 
Init(const InstallPlan * install_plan,bool source_may_exist,size_t next_op_index)97 bool VABCPartitionWriter::Init(const InstallPlan* install_plan,
98                                bool source_may_exist,
99                                size_t next_op_index) {
100   if (dynamic_control_->GetVirtualAbCompressionXorFeatureFlag().IsEnabled()) {
101     xor_map_ = ComputeXorMap(partition_update_.merge_operations());
102     if (xor_map_.size() > 0) {
103       LOG(INFO) << "Virtual AB Compression with XOR is enabled";
104     } else {
105       LOG(INFO) << "Device supports Virtual AB compression with XOR, but OTA "
106                    "package does not.";
107     }
108   } else {
109     LOG(INFO) << "Virtual AB Compression with XOR is disabled.";
110   }
111   TEST_AND_RETURN_FALSE(install_plan != nullptr);
112   if (source_may_exist && install_part_.source_size > 0) {
113     TEST_AND_RETURN_FALSE(!install_part_.source_path.empty());
114     TEST_AND_RETURN_FALSE(verified_source_fd_.Open());
115   }
116   std::optional<std::string> source_path;
117   if (!install_part_.source_path.empty()) {
118     // TODO(zhangkelvin) Make |source_path| a std::optional<std::string>
119     source_path = install_part_.source_path;
120   }
121   cow_writer_ = dynamic_control_->OpenCowWriter(
122       install_part_.name, source_path, install_plan->is_resume);
123   TEST_AND_RETURN_FALSE(cow_writer_ != nullptr);
124 
125   // ===== Resume case handling code goes here ====
126   // It is possible that the SOURCE_COPY are already written but
127   // |next_op_index_| is still 0. In this case we discard previously written
128   // SOURCE_COPY, and start over.
129   if (install_plan->is_resume && next_op_index > 0) {
130     LOG(INFO) << "Resuming update on partition `"
131               << partition_update_.partition_name() << "` op index "
132               << next_op_index;
133     TEST_AND_RETURN_FALSE(cow_writer_->InitializeAppend(next_op_index));
134     return true;
135   } else {
136     TEST_AND_RETURN_FALSE(cow_writer_->Initialize());
137   }
138 
139   // ==============================================
140   if (!partition_update_.merge_operations().empty()) {
141     if (IsXorEnabled()) {
142       LOG(INFO) << "VABC XOR enabled for partition "
143                 << partition_update_.partition_name();
144       TEST_AND_RETURN_FALSE(WriteMergeSequence(
145           partition_update_.merge_operations(), cow_writer_.get()));
146     }
147   }
148 
149   // TODO(zhangkelvin) Rewrite this in C++20 coroutine once that's available.
150   // TODO(177104308) Don't write all COPY ops up-front if merge sequence is
151   // written
152   const auto converted = ConvertToCowOperations(
153       partition_update_.operations(), partition_update_.merge_operations());
154 
155   if (!converted.empty()) {
156     // Use source fd directly. Ideally we want to verify all extents used in
157     // source copy, but then what do we do if some extents contain correct
158     // hashes and some don't?
159     auto source_fd = std::make_shared<EintrSafeFileDescriptor>();
160     TEST_AND_RETURN_FALSE_ERRNO(
161         source_fd->Open(install_part_.source_path.c_str(), O_RDONLY));
162     TEST_AND_RETURN_FALSE(WriteSourceCopyCowOps(
163         block_size_, converted, cow_writer_.get(), source_fd));
164     cow_writer_->AddLabel(0);
165   }
166   return true;
167 }
168 
WriteMergeSequence(const RepeatedPtrField<CowMergeOperation> & merge_sequence,ICowWriter * cow_writer)169 bool VABCPartitionWriter::WriteMergeSequence(
170     const RepeatedPtrField<CowMergeOperation>& merge_sequence,
171     ICowWriter* cow_writer) {
172   std::vector<uint32_t> blocks_merge_order;
173   for (const auto& merge_op : merge_sequence) {
174     const auto& dst_extent = merge_op.dst_extent();
175     const auto& src_extent = merge_op.src_extent();
176     // In place copy are basically noops, they do not need to be "merged" at
177     // all, don't include them in merge sequence.
178     if (merge_op.type() == CowMergeOperation::COW_COPY &&
179         merge_op.src_extent() == merge_op.dst_extent()) {
180       continue;
181     }
182 
183     const bool extent_overlap =
184         ExtentRanges::ExtentsOverlap(src_extent, dst_extent);
185     // TODO(193863443) Remove this check once this feature
186     // lands on all pixel devices.
187     const bool is_ascending = android::base::GetBoolProperty(
188         "ro.virtual_ab.userspace.snapshots.enabled", false);
189 
190     // If this is a self-overlapping op and |dst_extent| comes after
191     // |src_extent|, we must write in reverse order for correctness.
192     //
193     // If this is self-overlapping op and |dst_extent| comes before
194     // |src_extent|, we must write in ascending order for correctness.
195     //
196     // If this isn't a self overlapping op, write block in ascending order
197     // if userspace snapshots are enabled
198     if (extent_overlap) {
199       if (dst_extent.start_block() <= src_extent.start_block()) {
200         for (size_t i = 0; i < dst_extent.num_blocks(); i++) {
201           blocks_merge_order.push_back(dst_extent.start_block() + i);
202         }
203       } else {
204         for (int i = dst_extent.num_blocks() - 1; i >= 0; i--) {
205           blocks_merge_order.push_back(dst_extent.start_block() + i);
206         }
207       }
208     } else {
209       if (is_ascending) {
210         for (size_t i = 0; i < dst_extent.num_blocks(); i++) {
211           blocks_merge_order.push_back(dst_extent.start_block() + i);
212         }
213       } else {
214         for (int i = dst_extent.num_blocks() - 1; i >= 0; i--) {
215           blocks_merge_order.push_back(dst_extent.start_block() + i);
216         }
217       }
218     }
219   }
220   return cow_writer->AddSequenceData(blocks_merge_order.size(),
221                                      blocks_merge_order.data());
222 }
223 
WriteSourceCopyCowOps(size_t block_size,const std::vector<CowOperation> & converted,ICowWriter * cow_writer,FileDescriptorPtr source_fd)224 bool VABCPartitionWriter::WriteSourceCopyCowOps(
225     size_t block_size,
226     const std::vector<CowOperation>& converted,
227     ICowWriter* cow_writer,
228     FileDescriptorPtr source_fd) {
229   for (const auto& cow_op : converted) {
230     std::vector<uint8_t> buffer;
231     switch (cow_op.op) {
232       case CowOperation::CowCopy:
233         if (cow_op.src_block == cow_op.dst_block) {
234           continue;
235         }
236         // Add blocks in reverse order, because snapused specifically prefers
237         // this ordering. Since we already eliminated all self-overlapping
238         // SOURCE_COPY during delta generation, this should be safe to do.
239         for (size_t i = cow_op.block_count; i > 0; i--) {
240           TEST_AND_RETURN_FALSE(cow_writer->AddCopy(cow_op.dst_block + i - 1,
241                                                     cow_op.src_block + i - 1));
242         }
243         break;
244       case CowOperation::CowReplace:
245         buffer.resize(block_size * cow_op.block_count);
246         ssize_t bytes_read = 0;
247         TEST_AND_RETURN_FALSE(utils::ReadAll(source_fd,
248                                              buffer.data(),
249                                              block_size * cow_op.block_count,
250                                              cow_op.src_block * block_size,
251                                              &bytes_read));
252         if (bytes_read <= 0 ||
253             static_cast<size_t>(bytes_read) != buffer.size()) {
254           LOG(ERROR) << "source_fd->Read failed: " << bytes_read;
255           return false;
256         }
257         TEST_AND_RETURN_FALSE(cow_writer->AddRawBlocks(
258             cow_op.dst_block, buffer.data(), buffer.size()));
259         break;
260     }
261   }
262 
263   return true;
264 }
265 
CreateBaseExtentWriter()266 std::unique_ptr<ExtentWriter> VABCPartitionWriter::CreateBaseExtentWriter() {
267   return std::make_unique<SnapshotExtentWriter>(cow_writer_.get());
268 }
269 
PerformZeroOrDiscardOperation(const InstallOperation & operation)270 [[nodiscard]] bool VABCPartitionWriter::PerformZeroOrDiscardOperation(
271     const InstallOperation& operation) {
272   for (const auto& extent : operation.dst_extents()) {
273     TEST_AND_RETURN_FALSE(
274         cow_writer_->AddZeroBlocks(extent.start_block(), extent.num_blocks()));
275   }
276   return true;
277 }
278 
PerformSourceCopyOperation(const InstallOperation & operation,ErrorCode * error)279 [[nodiscard]] bool VABCPartitionWriter::PerformSourceCopyOperation(
280     const InstallOperation& operation, ErrorCode* error) {
281   // COPY ops are already handled during Init(), no need to do actual work, but
282   // we still want to verify that all blocks contain expected data.
283   auto source_fd = std::make_shared<EintrSafeFileDescriptor>();
284   TEST_AND_RETURN_FALSE_ERRNO(
285       source_fd->Open(install_part_.source_path.c_str(), O_RDONLY));
286   if (!operation.has_src_sha256_hash()) {
287     return true;
288   }
289   return PartitionWriter::ValidateSourceHash(
290       operation, source_fd, block_size_, error);
291 }
292 
PerformReplaceOperation(const InstallOperation & op,const void * data,size_t count)293 bool VABCPartitionWriter::PerformReplaceOperation(const InstallOperation& op,
294                                                   const void* data,
295                                                   size_t count) {
296   // Setup the ExtentWriter stack based on the operation type.
297   std::unique_ptr<ExtentWriter> writer = CreateBaseExtentWriter();
298 
299   return executor_.ExecuteReplaceOperation(op, std::move(writer), data, count);
300 }
301 
PerformDiffOperation(const InstallOperation & operation,ErrorCode * error,const void * data,size_t count)302 bool VABCPartitionWriter::PerformDiffOperation(
303     const InstallOperation& operation,
304     ErrorCode* error,
305     const void* data,
306     size_t count) {
307   FileDescriptorPtr source_fd =
308       verified_source_fd_.ChooseSourceFD(operation, error);
309   TEST_AND_RETURN_FALSE(source_fd != nullptr);
310   TEST_AND_RETURN_FALSE(source_fd->IsOpen());
311 
312   std::unique_ptr<ExtentWriter> writer =
313       IsXorEnabled() ? std::make_unique<XORExtentWriter>(
314                            operation, source_fd, cow_writer_.get(), xor_map_)
315                      : CreateBaseExtentWriter();
316   return executor_.ExecuteDiffOperation(
317       operation, std::move(writer), source_fd, data, count);
318 }
319 
CheckpointUpdateProgress(size_t next_op_index)320 void VABCPartitionWriter::CheckpointUpdateProgress(size_t next_op_index) {
321   // No need to call fsync/sync, as CowWriter flushes after a label is added
322   // added.
323   // if cow_writer_ failed, that means Init() failed. This function shouldn't be
324   // called if Init() fails.
325   TEST_AND_RETURN(cow_writer_ != nullptr);
326   cow_writer_->AddLabel(next_op_index);
327 }
328 
FinishedInstallOps()329 [[nodiscard]] bool VABCPartitionWriter::FinishedInstallOps() {
330   // Add a hardcoded magic label to indicate end of all install ops. This label
331   // is needed by filesystem verification, don't remove.
332   TEST_AND_RETURN_FALSE(cow_writer_ != nullptr);
333   TEST_AND_RETURN_FALSE(cow_writer_->AddLabel(kEndOfInstallLabel));
334   TEST_AND_RETURN_FALSE(cow_writer_->Finalize());
335   TEST_AND_RETURN_FALSE(cow_writer_->VerifyMergeOps());
336   return true;
337 }
338 
~VABCPartitionWriter()339 VABCPartitionWriter::~VABCPartitionWriter() {
340   Close();
341 }
342 
Close()343 int VABCPartitionWriter::Close() {
344   if (cow_writer_) {
345     cow_writer_->Finalize();
346     cow_writer_ = nullptr;
347   }
348   return 0;
349 }
350 
351 }  // namespace chromeos_update_engine
352