fibmap.c revision e296161af0a2429f36b155a1ab75095f6e0a81f9
1#define _LARGEFILE64_SOURCE
2#include <unistd.h>
3#include <string.h>
4#include <stdlib.h>
5#include <stdio.h>
6#include <fcntl.h>
7#include <errno.h>
8#include <sys/ioctl.h>
9#include <sys/stat.h>
10#include <linux/types.h>
11#include <linux/fs.h>
12
13struct file_ext {
14	__u32 f_pos;
15	__u32 start_blk;
16	__u32 end_blk;
17	__u32 blk_count;
18};
19
20void print_ext(struct file_ext *ext)
21{
22	if (ext->end_blk == 0)
23		printf("%8d    %8d    %8d    %8d\n", ext->f_pos, 0, 0, ext->blk_count);
24	else
25		printf("%8d    %8d    %8d    %8d\n", ext->f_pos, ext->start_blk,
26					ext->end_blk, ext->blk_count);
27}
28
29void print_stat(struct stat64 *st)
30{
31	printf("--------------------------------------------\n");
32	printf("dev       [%d:%d]\n", major(st->st_dev), minor(st->st_dev));
33	printf("ino       [0x%8lx : %ld]\n", st->st_ino, st->st_ino);
34	printf("mode      [0x%8x : %d]\n", st->st_mode, st->st_mode);
35	printf("nlink     [0x%8lx : %ld]\n", st->st_nlink, st->st_nlink);
36	printf("uid       [0x%8x : %d]\n", st->st_uid, st->st_uid);
37	printf("gid       [0x%8x : %d]\n", st->st_gid, st->st_gid);
38	printf("size      [0x%8lx : %ld]\n", st->st_size, st->st_size);
39	printf("blksize   [0x%8lx : %ld]\n", st->st_blksize, st->st_blksize);
40	printf("blocks    [0x%8lx : %ld]\n", st->st_blocks, st->st_blocks);
41	printf("--------------------------------------------\n\n");
42}
43
44int main(int argc, char *argv[])
45{
46	int fd;
47	int ret = 0;
48	char *filename;
49	struct stat64 st;
50	int total_blks;
51	unsigned int i;
52	struct file_ext ext;
53	__u32 blknum;
54
55	if (argc != 2) {
56		fprintf(stderr, "No filename\n");
57		exit(-1);
58	}
59	filename = argv[1];
60
61	fd = open(filename, O_RDONLY|O_LARGEFILE);
62	if (fd < 0) {
63		ret = errno;
64		perror(filename);
65		exit(-1);
66	}
67
68	fsync(fd);
69
70	if (fstat64(fd, &st) < 0) {
71		ret = errno;
72		perror(filename);
73		goto out;
74	}
75
76	total_blks = (st.st_size + st.st_blksize - 1) / st.st_blksize;
77
78	printf("\n%s :\n", filename);
79	print_stat(&st);
80	printf("file_pos   start_blk     end_blk        blks\n");
81
82	blknum = 0;
83	if (ioctl(fd, FIBMAP, &blknum) < 0) {
84		ret = errno;
85		perror("ioctl(FIBMAP)");
86		goto out;
87	}
88	ext.f_pos = 0;
89	ext.start_blk = blknum;
90	ext.end_blk = blknum;
91	ext.blk_count = 1;
92
93	for (i = 1; i < total_blks; i++) {
94		blknum = i;
95
96		if (ioctl(fd, FIBMAP, &blknum) < 0) {
97			ret = errno;
98			perror("ioctl(FIBMAP)");
99			goto out;
100		}
101
102		if ((blknum == 0 && blknum == ext.end_blk) || (ext.end_blk + 1) == blknum) {
103			ext.end_blk = blknum;
104			ext.blk_count++;
105		} else {
106			print_ext(&ext);
107			ext.f_pos = i * st.st_blksize;
108			ext.start_blk = blknum;
109			ext.end_blk = blknum;
110			ext.blk_count = 1;
111		}
112	}
113
114	print_ext(&ext);
115out:
116	close(fd);
117	return ret;
118}
119