blob: e02f5a281693a15e74a5a0247e139ccc97334ce3 [file] [log] [blame]
Andrew de los Reyesb4025e62010-02-23 17:47:03 -08001// 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
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070019#include "update_engine/graph_types.h"
20#include "update_engine/graph_utils.h"
Andrew de los Reyesb4025e62010-02-23 17:47:03 -080021#include "update_engine/utils.h"
22
23using std::string;
24using std::vector;
25
26namespace chromeos_update_engine {
27
28namespace extent_mapper {
29
30namespace {
31const int kBlockSize = 4096;
32}
33
34bool ExtentsForFileFibmap(const std::string& path, std::vector<Extent>* out) {
35 CHECK(out);
Andrew de los Reyesb4025e62010-02-23 17:47:03 -080036 struct stat stbuf;
37 int rc = stat(path.c_str(), &stbuf);
38 TEST_AND_RETURN_FALSE_ERRNO(rc == 0);
39 TEST_AND_RETURN_FALSE(S_ISREG(stbuf.st_mode));
40
41 int fd = open(path.c_str(), O_RDONLY, 0);
42 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
43 ScopedFdCloser fd_closer(&fd);
44
45 // Get file size in blocks
46 rc = fstat(fd, &stbuf);
47 if (rc < 0) {
48 perror("fstat");
49 return false;
50 }
51 const int block_count = (stbuf.st_size + kBlockSize - 1) / kBlockSize;
52 Extent current;
53 current.set_start_block(0);
54 current.set_num_blocks(0);
55
56 for (int i = 0; i < block_count; i++) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070057 unsigned int block32 = i;
58 rc = ioctl(fd, FIBMAP, &block32);
Andrew de los Reyesb4025e62010-02-23 17:47:03 -080059 TEST_AND_RETURN_FALSE_ERRNO(rc == 0);
60
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070061 const uint64_t block = (block32 == 0 ? kSparseHole : block32);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070062
63 graph_utils::AppendBlockToExtents(out, block);
Andrew de los Reyesb4025e62010-02-23 17:47:03 -080064 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070065 return true;
66}
Andrew de los Reyesb4025e62010-02-23 17:47:03 -080067
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070068bool GetFilesystemBlockSize(const std::string& path, uint32_t* out_blocksize) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070069 int fd = open(path.c_str(), O_RDONLY, 0);
70 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
71 ScopedFdCloser fd_closer(&fd);
72 int rc = ioctl(fd, FIGETBSZ, out_blocksize);
73 TEST_AND_RETURN_FALSE_ERRNO(rc != -1);
Andrew de los Reyesb4025e62010-02-23 17:47:03 -080074 return true;
75}
76
77} // namespace extent_mapper
78
79} // namespace chromeos_update_engine