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