blob: 1ae565b03776549be8c1820663f16fb9bab7e399 [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>
9
10using std::min;
11
12namespace chromeos_update_engine {
13
14namespace {
15// Returns true on success.
16bool WriteAll(int fd, const void *buf, size_t count) {
17 const char* c_buf = reinterpret_cast<const char*>(buf);
18 ssize_t bytes_written = 0;
19 while (bytes_written < static_cast<ssize_t>(count)) {
20 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
21 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
22 bytes_written += rc;
23 }
24 return true;
25}
26}
27
28bool DirectExtentWriter::Write(const void* bytes, size_t count) {
29 if (count == 0)
30 return true;
31 const char* c_bytes = reinterpret_cast<const char*>(bytes);
32 size_t bytes_written = 0;
33 while (count - bytes_written > 0) {
34 TEST_AND_RETURN_FALSE(next_extent_index_ < extents_.size());
35 uint64 bytes_remaining_next_extent =
36 extents_[next_extent_index_].num_blocks() * block_size_ -
37 extent_bytes_written_;
38 CHECK_NE(bytes_remaining_next_extent, 0);
39 size_t bytes_to_write =
40 static_cast<size_t>(min(static_cast<uint64>(count - bytes_written),
41 bytes_remaining_next_extent));
42 TEST_AND_RETURN_FALSE(bytes_to_write > 0);
43
44 if (extents_[next_extent_index_].start_block() != kSparseHole) {
45 const off64_t offset =
46 extents_[next_extent_index_].start_block() * block_size_ +
47 extent_bytes_written_;
48 TEST_AND_RETURN_FALSE_ERRNO(lseek64(fd_, offset, SEEK_SET) !=
49 static_cast<off64_t>(-1));
50 TEST_AND_RETURN_FALSE(
51 WriteAll(fd_, c_bytes + bytes_written, bytes_to_write));
52 }
53 bytes_written += bytes_to_write;
54 extent_bytes_written_ += bytes_to_write;
55 if (bytes_remaining_next_extent == bytes_to_write) {
56 // We filled this extent
57 CHECK_EQ(extent_bytes_written_,
58 extents_[next_extent_index_].num_blocks() * block_size_);
59 // move to next extent
60 extent_bytes_written_ = 0;
61 next_extent_index_++;
62 }
63 }
64 return true;
65}
66
67} // namespace chromeos_update_engine