Whamcloud - gitweb
filefrag: fix an off by one error in when printing the next expected block
[tools/e2fsprogs.git] / misc / filefrag.c
1 /*
2  * filefrag.c -- report if a particular file is fragmented
3  *
4  * Copyright 2003 by Theodore Ts'o.
5  *
6  * %Begin-Header%
7  * This file may be redistributed under the terms of the GNU Public
8  * License.
9  * %End-Header%
10  */
11
12 #include "config.h"
13 #ifndef __linux__
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <unistd.h>
17
18 int main(void) {
19     fputs("This program is only supported on Linux!\n", stderr);
20     exit(EXIT_FAILURE);
21 }
22 #else
23 #define _LARGEFILE64_SOURCE
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <string.h>
29 #include <time.h>
30 #include <fcntl.h>
31 #include <errno.h>
32 #ifdef HAVE_GETOPT_H
33 #include <getopt.h>
34 #else
35 extern char *optarg;
36 extern int optind;
37 #endif
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <sys/vfs.h>
41 #include <sys/ioctl.h>
42 #include <linux/fd.h>
43 #include <ext2fs/ext2_types.h>
44 #include <ext2fs/fiemap.h>
45
46 int verbose = 0;
47 int no_bs = 0;          /* Don't use the files blocksize, use 1K blocksize */
48 int sync_file = 0;      /* fsync file before getting the mapping */
49 int xattr_map = 0;      /* get xattr mapping */
50 int force_bmap = 0;
51 int logical_width = 12;
52 int physical_width = 14;
53 unsigned long long filesize;
54
55 #define FILEFRAG_FIEMAP_FLAGS_COMPAT (FIEMAP_FLAG_SYNC | FIEMAP_FLAG_XATTR)
56
57 #define FIBMAP          _IO(0x00, 1)    /* bmap access */
58 #define FIGETBSZ        _IO(0x00, 2)    /* get the block size used for bmap */
59
60 #define EXT4_EXTENTS_FL                 0x00080000 /* Inode uses extents */
61 #define EXT3_IOC_GETFLAGS               _IOR('f', 1, long)
62
63 static int int_log2(int arg)
64 {
65         int     l = 0;
66
67         arg >>= 1;
68         while (arg) {
69                 l++;
70                 arg >>= 1;
71         }
72         return l;
73 }
74
75 static int int_log10(unsigned long long arg)
76 {
77         int     l = 0;
78
79         arg = arg / 10;
80         while (arg) {
81                 l++;
82                 arg = arg / 10;
83         }
84         return l;
85 }
86
87 static unsigned int div_ceil(unsigned int a, unsigned int b)
88 {
89         if (!a)
90                 return 0;
91         return ((a - 1) / b) + 1;
92 }
93
94 static int get_bmap(int fd, unsigned long block, unsigned long *phy_blk)
95 {
96         int     ret;
97         unsigned int b;
98
99         b = block;
100         ret = ioctl(fd, FIBMAP, &b); /* FIBMAP takes pointer to integer */
101         if (ret < 0) {
102                 if (errno == EPERM) {
103                         fprintf(stderr, "No permission to use FIBMAP ioctl; "
104                                 "must have root privileges\n");
105                         exit(1);
106                 }
107                 perror("FIBMAP");
108         }
109         *phy_blk = b;
110
111         return ret;
112 }
113
114 static void print_extent_info(struct fiemap_extent *fm_extent, int cur_ex,
115                               unsigned long long expected, int blk_shift)
116 {
117         __u64 phy_blk;
118         unsigned long long logical_blk;
119         unsigned long ext_len;
120         char flags[256] = "";
121
122         /* For inline data all offsets should be in terms of bytes, not blocks */
123         if (fm_extent->fe_flags & FIEMAP_EXTENT_DATA_INLINE)
124                 blk_shift = 0;
125
126         ext_len = fm_extent->fe_length >> blk_shift;
127         logical_blk = fm_extent->fe_logical >> blk_shift;
128         phy_blk = fm_extent->fe_physical >> blk_shift;
129
130         if (fm_extent->fe_flags & FIEMAP_EXTENT_UNKNOWN)
131                 strcat(flags, "unknown,");
132         if (fm_extent->fe_flags & FIEMAP_EXTENT_DELALLOC)
133                 strcat(flags, "delalloc,");
134         if (fm_extent->fe_flags & FIEMAP_EXTENT_DATA_ENCRYPTED)
135                 strcat(flags, "encrypted,");
136         if (fm_extent->fe_flags & FIEMAP_EXTENT_NOT_ALIGNED)
137                 strcat(flags, "not_aligned,");
138         if (fm_extent->fe_flags & FIEMAP_EXTENT_DATA_INLINE)
139                 strcat(flags, "inline,");
140         if (fm_extent->fe_flags & FIEMAP_EXTENT_DATA_TAIL)
141                 strcat(flags, "tail_packed,");
142         if (fm_extent->fe_flags & FIEMAP_EXTENT_UNWRITTEN)
143                 strcat(flags, "unwritten,");
144         if (fm_extent->fe_flags & FIEMAP_EXTENT_MERGED)
145                 strcat(flags, "merged,");
146
147         if (fm_extent->fe_logical + fm_extent->fe_length >= filesize)
148                 strcat(flags, "eof,");
149
150         /* Remove trailing comma, if any */
151         if (flags[0])
152                 flags[strlen(flags) - 1] = '\0';
153
154         if (expected)
155                 printf("%4d %*llu %*llu %*llu %6lu %s\n",
156                        cur_ex, logical_width, logical_blk,
157                        physical_width, phy_blk, physical_width, expected,
158                        ext_len, flags);
159         else
160                 printf("%4d %*llu %*llu %*s %6lu %s\n",
161                        cur_ex, logical_width, logical_blk,
162                        physical_width, phy_blk, physical_width, "",
163                        ext_len, flags);
164 }
165
166 static int filefrag_fiemap(int fd, int blk_shift, int *num_extents)
167 {
168         char buf[4096] = "";
169         struct fiemap *fiemap = (struct fiemap *)buf;
170         struct fiemap_extent *fm_ext = &fiemap->fm_extents[0];
171         int count = (sizeof(buf) - sizeof(*fiemap)) /
172                         sizeof(struct fiemap_extent);
173         unsigned long long expected = 0;
174         unsigned long flags = 0;
175         unsigned int i;
176         static int fiemap_incompat_printed;
177         int fiemap_header_printed = 0;
178         int tot_extents = 1, n = 0;
179         int last = 0;
180         int rc;
181
182         memset(fiemap, 0, sizeof(struct fiemap));
183
184         /*
185          * If count (and therefore fm_extent_count) == 0, FIEMAP
186          * returns count of extents found without filling in details.
187          */
188         if (!verbose)
189                 count = 0;
190
191         if (sync_file)
192                 flags |= FIEMAP_FLAG_SYNC;
193
194         if (xattr_map)
195                 flags |= FIEMAP_FLAG_XATTR;
196
197         do {
198                 fiemap->fm_length = ~0ULL;
199                 fiemap->fm_flags = flags;
200                 fiemap->fm_extent_count = count;
201                 rc = ioctl(fd, FS_IOC_FIEMAP, (unsigned long) fiemap);
202                 if (rc < 0) {
203                         if (errno == EBADR && fiemap_incompat_printed == 0) {
204                                 printf("FIEMAP failed with unsupported "
205                                        "flags %x\n", fiemap->fm_flags);
206                                 fiemap_incompat_printed = 1;
207                         }
208                         return rc;
209                 }
210
211                 if (verbose && !fiemap_header_printed) {
212                         /*
213                          * No extents on first call?
214                          * Skip header and show 0 extents.
215                          */
216                         if (fiemap->fm_mapped_extents == 0) {
217                                 *num_extents = 0;
218                                 goto out;
219                         }
220                         printf(" ext %*s %*s %*s length flags\n", logical_width,
221                                "logical", physical_width, "physical",
222                                physical_width, "expected");
223                         fiemap_header_printed = 1;
224                 }
225
226                 /* If 0 extents are returned, then more ioctls are not needed */
227                 if (fiemap->fm_mapped_extents == 0)
228                         break;
229
230                 for (i = 0; i < fiemap->fm_mapped_extents; i++) {
231                         __u64 phy_blk, logical_blk;
232                         unsigned long ext_len;
233
234                         phy_blk = fm_ext[i].fe_physical >> blk_shift;
235                         ext_len = fm_ext[i].fe_length >> blk_shift;
236                         logical_blk = fm_ext[i].fe_logical >> blk_shift;
237
238                         if (logical_blk && phy_blk != expected)
239                                 tot_extents++;
240                         else
241                                 expected = 0;
242                         if (verbose)
243                                 print_extent_info(&fm_ext[i], n, expected,
244                                                   blk_shift);
245
246                         expected = phy_blk + ext_len;
247                         if (fm_ext[i].fe_flags & FIEMAP_EXTENT_LAST)
248                                 last = 1;
249                         n++;
250                 }
251
252                 fiemap->fm_start = (fm_ext[i-1].fe_logical +
253                                     fm_ext[i-1].fe_length);
254         } while (last == 0);
255
256         *num_extents = tot_extents;
257 out:
258         return 0;
259 }
260
261 #define EXT2_DIRECT     12
262
263 static void frag_report(const char *filename)
264 {
265         struct statfs   fsinfo;
266 #ifdef HAVE_FSTAT64
267         struct stat64   fileinfo;
268 #else
269         struct stat     fileinfo;
270 #endif
271         int             bs;
272         long            fd;
273         unsigned long   block, last_block = 0, numblocks, i, count = 0;
274         long            bpib;   /* Blocks per indirect block */
275         long            cylgroups;
276         int             num_extents = 0, expected;
277         int             is_ext2 = 0;
278         static int      once = 1;
279         unsigned int    flags;
280         int rc;
281
282 #ifdef HAVE_OPEN64
283         fd = open64(filename, O_RDONLY);
284 #else
285         fd = open(filename, O_RDONLY);
286 #endif
287         if (fd < 0) {
288                 perror("open");
289                 return;
290         }
291
292         if (statfs(filename, &fsinfo) < 0) {
293                 perror("statfs");
294                 return;
295         }
296 #ifdef HAVE_FSTAT64
297         if (stat64(filename, &fileinfo) < 0) {
298 #else
299         if (stat(filename, &fileinfo) < 0) {
300 #endif
301                 perror("stat");
302                 return;
303         }
304         if (ioctl(fd, EXT3_IOC_GETFLAGS, &flags) < 0)
305                 flags = 0;
306         if (!(flags & EXT4_EXTENTS_FL) &&
307             ((fsinfo.f_type == 0xef51) || (fsinfo.f_type == 0xef52) ||
308              (fsinfo.f_type == 0xef53)))
309                 is_ext2++;
310         if (verbose && once)
311                 printf("Filesystem type is: %lx\n",
312                        (unsigned long) fsinfo.f_type);
313
314         cylgroups = div_ceil(fsinfo.f_blocks, fsinfo.f_bsize*8);
315         if (verbose && is_ext2 && once)
316                 printf("Filesystem cylinder groups is approximately %ld\n",
317                        cylgroups);
318
319         physical_width = int_log10(fsinfo.f_blocks);
320         if (physical_width < 8)
321                 physical_width = 8;
322
323         if (ioctl(fd, FIGETBSZ, &bs) < 0) { /* FIGETBSZ takes an int */
324                 perror("FIGETBSZ");
325                 close(fd);
326                 return;
327         }
328
329         if (no_bs)
330                 bs = 1024;
331
332         bpib = bs / 4;
333         numblocks = (fileinfo.st_size + (bs-1)) / bs;
334         logical_width = int_log10(numblocks);
335         if (logical_width < 7)
336                 logical_width = 7;
337         filesize = (long long)fileinfo.st_size;
338         if (verbose)
339                 printf("File size of %s is %lld (%ld block%s, blocksize %d)\n",
340                        filename, (long long) fileinfo.st_size, numblocks,
341                        numblocks == 1 ? "" : "s", bs);
342         if (force_bmap ||
343             filefrag_fiemap(fd, int_log2(bs), &num_extents) != 0) {
344                 for (i = 0, count = 0; i < numblocks; i++) {
345                         if (is_ext2 && last_block) {
346                                 if (((i-EXT2_DIRECT) % bpib) == 0)
347                                         last_block++;
348                                 if (((i-EXT2_DIRECT-bpib) % (bpib*bpib)) == 0)
349                                         last_block++;
350                                 if (((i-EXT2_DIRECT-bpib-bpib*bpib) %
351                                      (((__u64) bpib)*bpib*bpib)) == 0)
352                                         last_block++;
353                         }
354                         rc = get_bmap(fd, i, &block);
355                         if (block == 0)
356                                 continue;
357                         if (!num_extents)
358                                 num_extents++;
359                         count++;
360                         if (last_block && (block != last_block+1) ) {
361                                 if (verbose)
362                                         printf("Discontinuity: Block %ld is at "
363                                                "%lu (was %lu)\n",
364                                                i, block, last_block+1);
365                                 num_extents++;
366                         }
367                         last_block = block;
368                 }
369         }
370         if (num_extents == 1)
371                 printf("%s: 1 extent found", filename);
372         else
373                 printf("%s: %d extents found", filename, num_extents);
374         /* count, and thus expected, only set for indirect FIBMAP'd files */
375         expected = (count/((bs*8)-(fsinfo.f_files/8/cylgroups)-3))+1;
376         if (is_ext2 && expected && expected < num_extents)
377                 printf(", perfection would be %d extent%s\n", expected,
378                         (expected>1) ? "s" : "");
379         else
380                 fputc('\n', stdout);
381         close(fd);
382         once = 0;
383 }
384
385 static void usage(const char *progname)
386 {
387         fprintf(stderr, "Usage: %s [-Bbvsx] file ...\n", progname);
388         exit(1);
389 }
390
391 int main(int argc, char**argv)
392 {
393         char **cpp;
394         int c;
395
396         while ((c = getopt(argc, argv, "Bbsvx")) != EOF)
397                 switch (c) {
398                 case 'B':
399                         force_bmap++;
400                         break;
401                 case 'b':
402                         no_bs++;
403                         break;
404                 case 'v':
405                         verbose++;
406                         break;
407                 case 's':
408                         sync_file++;
409                         break;
410                 case 'x':
411                         xattr_map++;
412                         break;
413                 default:
414                         usage(argv[0]);
415                         break;
416                 }
417         if (optind == argc)
418                 usage(argv[0]);
419         for (cpp=argv+optind; *cpp; cpp++)
420                 frag_report(*cpp);
421         return 0;
422 }
423 #endif