blob: baac66cbdd5283ee836c9d4cef832869dfa985cf [file] [log] [blame]
Andrew de los Reyes80061062010-02-04 14:25:00 -08001// Copyright (c) 2009 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/extent_writer.h"
6#include <errno.h>
7#include <unistd.h>
8#include <algorithm>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07009#include "update_engine/graph_types.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070010#include "update_engine/utils.h"
Andrew de los Reyes80061062010-02-04 14:25:00 -080011
12using std::min;
13
14namespace chromeos_update_engine {
15
Andrew de los Reyes80061062010-02-04 14:25:00 -080016bool DirectExtentWriter::Write(const void* bytes, size_t count) {
17 if (count == 0)
18 return true;
19 const char* c_bytes = reinterpret_cast<const char*>(bytes);
20 size_t bytes_written = 0;
21 while (count - bytes_written > 0) {
22 TEST_AND_RETURN_FALSE(next_extent_index_ < extents_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023 uint64_t bytes_remaining_next_extent =
Andrew de los Reyes80061062010-02-04 14:25:00 -080024 extents_[next_extent_index_].num_blocks() * block_size_ -
25 extent_bytes_written_;
26 CHECK_NE(bytes_remaining_next_extent, 0);
27 size_t bytes_to_write =
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070028 static_cast<size_t>(min(static_cast<uint64_t>(count - bytes_written),
Andrew de los Reyes80061062010-02-04 14:25:00 -080029 bytes_remaining_next_extent));
30 TEST_AND_RETURN_FALSE(bytes_to_write > 0);
31
32 if (extents_[next_extent_index_].start_block() != kSparseHole) {
33 const off64_t offset =
34 extents_[next_extent_index_].start_block() * block_size_ +
35 extent_bytes_written_;
36 TEST_AND_RETURN_FALSE_ERRNO(lseek64(fd_, offset, SEEK_SET) !=
37 static_cast<off64_t>(-1));
38 TEST_AND_RETURN_FALSE(
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070039 utils::WriteAll(fd_, c_bytes + bytes_written, bytes_to_write));
Andrew de los Reyes80061062010-02-04 14:25:00 -080040 }
41 bytes_written += bytes_to_write;
42 extent_bytes_written_ += bytes_to_write;
43 if (bytes_remaining_next_extent == bytes_to_write) {
44 // We filled this extent
45 CHECK_EQ(extent_bytes_written_,
46 extents_[next_extent_index_].num_blocks() * block_size_);
47 // move to next extent
48 extent_bytes_written_ = 0;
49 next_extent_index_++;
50 }
51 }
52 return true;
53}
54
55} // namespace chromeos_update_engine