2 * filefrag.c -- report if a particular file is fragmented
4 * Copyright 2003 by Theodore Ts'o.
7 * This file may be redistributed under the terms of the GNU Public
17 fputs("This program is only supported on Linux!\n", stderr);
21 #define _LARGEFILE64_SOURCE
36 #include <sys/types.h>
39 #include <sys/ioctl.h>
44 #define FIBMAP _IO(0x00,1) /* bmap access */
45 #define FIGETBSZ _IO(0x00,2) /* get the block size used for bmap */
47 static unsigned long get_bmap(int fd, unsigned long block)
53 ret = ioctl(fd, FIBMAP, &b);
56 fprintf(stderr, "No permission to use FIBMAP ioctl; must have root privileges\n");
64 #define EXT2_DIRECT 12
66 static void frag_report(const char *filename)
69 struct stat64 fileinfo;
70 long i, fd, bs, block, last_block = 0, numblocks;
71 long bpib; /* Blocks per indirect block */
73 int discont = 0, expected;
76 if (statfs(filename, &fsinfo) < 0) {
80 if (stat64(filename, &fileinfo) < 0) {
84 if (!S_ISREG(fileinfo.st_mode)) {
85 printf("%s: Not a regular file\n", filename);
88 if ((fsinfo.f_type == 0xef51) || (fsinfo.f_type == 0xef52) ||
89 (fsinfo.f_type == 0xef53))
92 printf("Filesystem type is: %x\n", fsinfo.f_type);
94 cylgroups = (fsinfo.f_blocks + fsinfo.f_bsize*8-1) / fsinfo.f_bsize*8;
96 printf("Filesystem cylinder groups is approximately %ld\n",
99 fd = open(filename, O_RDONLY | O_LARGEFILE);
104 if (ioctl(fd, FIGETBSZ, &bs) < 0) {
110 printf("Blocksize of file %s is %ld\n", filename, bs);
112 numblocks = (fileinfo.st_size + (bs-1)) / bs;
114 printf("File size of %s is %lld (%ld blocks)\n", filename,
115 (long long) fileinfo.st_size, numblocks);
116 printf("First block: %ld\nLast block: %ld\n",
117 get_bmap(fd, 0), get_bmap(fd, numblocks - 1));
119 for (i=0; i < numblocks; i++) {
121 if (((i-EXT2_DIRECT) % bpib) == 0)
123 if (((i-EXT2_DIRECT-bpib) % (bpib*bpib)) == 0)
125 if (((i-EXT2_DIRECT-bpib-bpib*bpib) % (bpib*bpib*bpib)) == 0)
128 block = get_bmap(fd, i);
129 if (i && block && (block != last_block +1) ) {
131 printf("Discontinuity: Block %ld is at %ld (was %ld)\n",
132 i, block, last_block);
139 printf("%s: 1 extent found", filename);
141 printf("%s: %d extents found", filename, discont+1);
142 expected = (numblocks/((bs*8)-(fsinfo.f_files/8/cylgroups)-3))+1;
143 if (is_ext2 && expected != discont+1)
144 printf(", perfection would be %d extent%s\n", expected,
145 (expected>1) ? "s" : "");
151 static void usage(const char *progname)
153 fprintf(stderr, "Usage: %s [-v] file ...\n", progname);
157 int main(int argc, char**argv)
162 while ((c = getopt(argc, argv, "v")) != EOF)
173 for (cpp=argv+optind; *cpp; cpp++) {
175 printf("Checking %s\n", *cpp);