Andrew de los Reyes | b4025e6 | 2010-02-23 17:47:03 -0800 | [diff] [blame^] | 1 | // Copyright (c) 2010 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_mapper.h" |
| 6 | |
| 7 | #include <sys/ioctl.h> |
| 8 | #include <sys/types.h> |
| 9 | #include <sys/stat.h> |
| 10 | |
| 11 | #include <assert.h> |
| 12 | #include <errno.h> |
| 13 | #include <fcntl.h> |
| 14 | #include <stdio.h> |
| 15 | #include <string.h> |
| 16 | |
| 17 | #include <linux/fs.h> |
| 18 | |
| 19 | #include "update_engine/utils.h" |
| 20 | |
| 21 | using std::string; |
| 22 | using std::vector; |
| 23 | |
| 24 | namespace chromeos_update_engine { |
| 25 | |
| 26 | namespace extent_mapper { |
| 27 | |
| 28 | namespace { |
| 29 | const int kBlockSize = 4096; |
| 30 | } |
| 31 | |
| 32 | bool ExtentsForFileFibmap(const std::string& path, std::vector<Extent>* out) { |
| 33 | CHECK(out); |
| 34 | // TODO(adlr): verify path is a file |
| 35 | struct stat stbuf; |
| 36 | int rc = stat(path.c_str(), &stbuf); |
| 37 | TEST_AND_RETURN_FALSE_ERRNO(rc == 0); |
| 38 | TEST_AND_RETURN_FALSE(S_ISREG(stbuf.st_mode)); |
| 39 | |
| 40 | int fd = open(path.c_str(), O_RDONLY, 0); |
| 41 | TEST_AND_RETURN_FALSE_ERRNO(fd >= 0); |
| 42 | ScopedFdCloser fd_closer(&fd); |
| 43 | |
| 44 | // Get file size in blocks |
| 45 | rc = fstat(fd, &stbuf); |
| 46 | if (rc < 0) { |
| 47 | perror("fstat"); |
| 48 | return false; |
| 49 | } |
| 50 | const int block_count = (stbuf.st_size + kBlockSize - 1) / kBlockSize; |
| 51 | Extent current; |
| 52 | current.set_start_block(0); |
| 53 | current.set_num_blocks(0); |
| 54 | |
| 55 | for (int i = 0; i < block_count; i++) { |
| 56 | unsigned int block = i; |
| 57 | rc = ioctl(fd, FIBMAP, &block); |
| 58 | TEST_AND_RETURN_FALSE_ERRNO(rc == 0); |
| 59 | |
| 60 | // Add next block to extents |
| 61 | if (current.num_blocks() == 0) { |
| 62 | // We're starting a new extent |
| 63 | current.set_start_block(block); |
| 64 | current.set_num_blocks(1); |
| 65 | continue; |
| 66 | } |
| 67 | if ((current.start_block() + current.num_blocks()) == block) { |
| 68 | // We're continuing the last extent |
| 69 | current.set_num_blocks(current.num_blocks() + 1); |
| 70 | continue; |
| 71 | } |
| 72 | // We're starting a new extent and keeping the current one |
| 73 | out->push_back(current); |
| 74 | current.set_start_block(block); |
| 75 | current.set_num_blocks(1); |
| 76 | continue; |
| 77 | } |
| 78 | |
| 79 | if (current.num_blocks() > 0) |
| 80 | out->push_back(current); |
| 81 | |
| 82 | return true; |
| 83 | } |
| 84 | |
| 85 | } // namespace extent_mapper |
| 86 | |
| 87 | } // namespace chromeos_update_engine |