Whamcloud - gitweb
filefrag: fix issues with 29758d2
[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/ext2fs.h>
44 #include <ext2fs/ext2_types.h>
45 #include <ext2fs/fiemap.h>
46
47 int verbose = 0;
48 int blocksize;          /* Use specified blocksize (default 1kB) */
49 int sync_file = 0;      /* fsync file before getting the mapping */
50 int xattr_map = 0;      /* get xattr mapping */
51 int force_bmap; /* force use of FIBMAP instead of FIEMAP */
52 int force_extent;       /* print output in extent format always */
53 int logical_width = 8;
54 int physical_width = 10;
55 const char *ext_fmt = "%4d: %*llu..%*llu: %*llu..%*llu: %6llu: %s\n";
56 const char *hex_fmt = "%4d: %*llx..%*llx: %*llx..%*llx: %6llx: %s\n";
57
58 #define FILEFRAG_FIEMAP_FLAGS_COMPAT (FIEMAP_FLAG_SYNC | FIEMAP_FLAG_XATTR)
59
60 #define FIBMAP          _IO(0x00, 1)    /* bmap access */
61 #define FIGETBSZ        _IO(0x00, 2)    /* get the block size used for bmap */
62
63 #define LUSTRE_SUPER_MAGIC 0x0BD00BD0
64
65 #define EXT4_EXTENTS_FL                 0x00080000 /* Inode uses extents */
66 #define EXT3_IOC_GETFLAGS               _IOR('f', 1, long)
67
68 static int int_log2(int arg)
69 {
70         int     l = 0;
71
72         arg >>= 1;
73         while (arg) {
74                 l++;
75                 arg >>= 1;
76         }
77         return l;
78 }
79
80 static int int_log10(unsigned long long arg)
81 {
82         int     l = 0;
83
84         arg = arg / 10;
85         while (arg) {
86                 l++;
87                 arg = arg / 10;
88         }
89         return l;
90 }
91
92 static unsigned int div_ceil(unsigned int a, unsigned int b)
93 {
94         if (!a)
95                 return 0;
96         return ((a - 1) / b) + 1;
97 }
98
99 static int get_bmap(int fd, unsigned long block, unsigned long *phy_blk)
100 {
101         int     ret;
102         unsigned int b;
103
104         b = block;
105         ret = ioctl(fd, FIBMAP, &b); /* FIBMAP takes pointer to integer */
106         if (ret < 0)
107                 return -errno;
108         *phy_blk = b;
109
110         return ret;
111 }
112
113 static void print_extent_header(void)
114 {
115         printf(" ext: %*s %*s length: %*s flags:\n",
116                logical_width * 2 + 3,
117                "logical_offset:",
118                physical_width * 2 + 3, "physical_offset:",
119                physical_width + 1,
120                "expected:");
121 }
122
123 static void print_flag(__u32 *flags, __u32 mask, char *buf, const char *name)
124 {
125         if ((*flags & mask) == 0)
126                 return;
127
128         strcat(buf, name);
129         *flags &= ~mask;
130 }
131
132 static void print_extent_info(struct fiemap_extent *fm_extent, int cur_ex,
133                               unsigned long long expected, int blk_shift,
134                               ext2fs_struct_stat *st)
135 {
136         unsigned long long physical_blk;
137         unsigned long long logical_blk;
138         unsigned long long ext_len;
139         unsigned long long ext_blks;
140         __u32 fe_flags, mask;
141         char flags[256] = "";
142
143         /* For inline data all offsets should be in bytes, not blocks */
144         if (fm_extent->fe_flags & FIEMAP_EXTENT_DATA_INLINE)
145                 blk_shift = 0;
146
147         ext_len = fm_extent->fe_length >> blk_shift;
148         ext_blks = (fm_extent->fe_length - 1) >> blk_shift;
149         logical_blk = fm_extent->fe_logical >> blk_shift;
150         if (fm_extent->fe_flags & FIEMAP_EXTENT_UNKNOWN) {
151                 physical_blk = 0;
152         } else {
153                 physical_blk = fm_extent->fe_physical >> blk_shift;
154         }
155
156         if (expected)
157                 sprintf(flags, ext_fmt == hex_fmt ? "%*llx: " : "%*llu: ",
158                         physical_width, expected >> blk_shift);
159         else
160                 sprintf(flags, "%.*s  ", physical_width, "                   ");
161
162         fe_flags = fm_extent->fe_flags;
163         print_flag(&fe_flags, FIEMAP_EXTENT_LAST, flags, "last,");
164         print_flag(&fe_flags, FIEMAP_EXTENT_UNKNOWN, flags, "unknown_loc,");
165         print_flag(&fe_flags, FIEMAP_EXTENT_DELALLOC, flags, "delalloc,");
166         print_flag(&fe_flags, FIEMAP_EXTENT_ENCODED, flags, "encoded,");
167         print_flag(&fe_flags, FIEMAP_EXTENT_DATA_ENCRYPTED, flags,"encrypted,");
168         print_flag(&fe_flags, FIEMAP_EXTENT_NOT_ALIGNED, flags, "not_aligned,");
169         print_flag(&fe_flags, FIEMAP_EXTENT_DATA_INLINE, flags, "inline,");
170         print_flag(&fe_flags, FIEMAP_EXTENT_DATA_TAIL, flags, "tail_packed,");
171         print_flag(&fe_flags, FIEMAP_EXTENT_UNWRITTEN, flags, "unwritten,");
172         print_flag(&fe_flags, FIEMAP_EXTENT_MERGED, flags, "merged,");
173         print_flag(&fe_flags, FIEMAP_EXTENT_SHARED, flags, "shared,");
174         /* print any unknown flags as hex values */
175         for (mask = 1; fe_flags != 0 && mask != 0; mask <<= 1) {
176                 char hex[6];
177
178                 if ((fe_flags & mask) == 0)
179                         continue;
180                 sprintf(hex, "%#04x,", mask);
181                 print_flag(&fe_flags, mask, flags, hex);
182         }
183
184         if (fm_extent->fe_logical + fm_extent->fe_length >= st->st_size)
185                 strcat(flags, "eof,");
186
187         /* Remove trailing comma, if any */
188         if (flags[0] != '\0')
189                 flags[strnlen(flags, sizeof(flags)) - 1] = '\0';
190
191         printf(ext_fmt, cur_ex, logical_width, logical_blk,
192                logical_width, logical_blk + ext_blks,
193                physical_width, physical_blk,
194                physical_width, physical_blk + ext_blks,
195                ext_len, flags);
196 }
197
198 static int filefrag_fiemap(int fd, int blk_shift, int *num_extents,
199                            ext2fs_struct_stat *st)
200 {
201         char buf[16384];
202         struct fiemap *fiemap = (struct fiemap *)buf;
203         struct fiemap_extent *fm_ext = &fiemap->fm_extents[0];
204         int count = (sizeof(buf) - sizeof(*fiemap)) /
205                         sizeof(struct fiemap_extent);
206         unsigned long long expected = 0;
207         unsigned long flags = 0;
208         unsigned int i;
209         int fiemap_header_printed = 0;
210         int tot_extents = 0, n = 0;
211         int last = 0;
212         int rc;
213
214         memset(fiemap, 0, sizeof(struct fiemap));
215
216         if (sync_file)
217                 flags |= FIEMAP_FLAG_SYNC;
218
219         if (xattr_map)
220                 flags |= FIEMAP_FLAG_XATTR;
221
222         do {
223                 fiemap->fm_length = ~0ULL;
224                 fiemap->fm_flags = flags;
225                 fiemap->fm_extent_count = count;
226                 rc = ioctl(fd, FS_IOC_FIEMAP, (unsigned long) fiemap);
227                 if (rc < 0) {
228                         static int fiemap_incompat_printed;
229                         rc = -errno;
230                         if (rc == -EBADR && !fiemap_incompat_printed) {
231                                 printf("FIEMAP failed with unknown flags %#x\n",
232                                        fiemap->fm_flags);
233                                 fiemap_incompat_printed = 1;
234                         }
235                         return rc;
236                 }
237
238                 /* If 0 extents are returned, then more ioctls are not needed */
239                 if (fiemap->fm_mapped_extents == 0)
240                         break;
241
242                 if (verbose && !fiemap_header_printed) {
243                         print_extent_header();
244                         fiemap_header_printed = 1;
245                 }
246
247                 for (i = 0; i < fiemap->fm_mapped_extents; i++) {
248                         if (fm_ext[i].fe_logical != 0 &&
249                             fm_ext[i].fe_physical != expected) {
250                                 tot_extents++;
251                         } else {
252                                 expected = 0;
253                                 if (!tot_extents)
254                                         tot_extents = 1;
255                         }
256                         if (verbose)
257                                 print_extent_info(&fm_ext[i], n, expected,
258                                                   blk_shift, st);
259
260                         expected = fm_ext[i].fe_physical + fm_ext[i].fe_length;
261                         if (fm_ext[i].fe_flags & FIEMAP_EXTENT_LAST)
262                                 last = 1;
263                         n++;
264                 }
265
266                 fiemap->fm_start = (fm_ext[i - 1].fe_logical +
267                                     fm_ext[i - 1].fe_length);
268         } while (last == 0);
269
270         *num_extents = tot_extents;
271
272         return 0;
273 }
274
275 #define EXT2_DIRECT     12
276
277 static int filefrag_fibmap(int fd, int blk_shift, int *num_extents,
278                            ext2fs_struct_stat *st,
279                            unsigned long numblocks, int is_ext2)
280 {
281         struct fiemap_extent    fm_ext;
282         unsigned long           i, last_block;
283         unsigned long long      logical;
284                                 /* Blocks per indirect block */
285         const long              bpib = st->st_blksize / 4;
286         int                     count;
287
288         if (force_extent) {
289                 memset(&fm_ext, 0, sizeof(fm_ext));
290                 fm_ext.fe_flags = FIEMAP_EXTENT_MERGED;
291         }
292
293         if (sync_file)
294                 fsync(fd);
295
296         for (i = 0, logical = 0, *num_extents = 0, count = last_block = 0;
297              i < numblocks;
298              i++, logical += st->st_blksize) {
299                 unsigned long block = 0;
300                 int rc;
301
302                 if (is_ext2 && last_block) {
303                         if (((i - EXT2_DIRECT) % bpib) == 0)
304                                 last_block++;
305                         if (((i - EXT2_DIRECT - bpib) % (bpib * bpib)) == 0)
306                                 last_block++;
307                         if (((i - EXT2_DIRECT - bpib - bpib * bpib) %
308                              (((unsigned long long)bpib) * bpib * bpib)) == 0)
309                                 last_block++;
310                 }
311                 rc = get_bmap(fd, i, &block);
312                 if (rc < 0)
313                         return rc;
314                 if (block == 0)
315                         continue;
316                 if (*num_extents == 0) {
317                         (*num_extents)++;
318                         if (force_extent) {
319                                 print_extent_header();
320                                 fm_ext.fe_physical = block * st->st_blksize;
321                         }
322                 }
323                 count++;
324                 if (force_extent && last_block != 0 &&
325                     (block != last_block + 1 ||
326                      fm_ext.fe_logical + fm_ext.fe_length != logical)) {
327                         print_extent_info(&fm_ext, *num_extents - 1,
328                                           (last_block + 1) * st->st_blksize,
329                                           blk_shift, st);
330                         fm_ext.fe_logical = logical;
331                         fm_ext.fe_physical = block * st->st_blksize;
332                         fm_ext.fe_length = 0;
333                         (*num_extents)++;
334                 } else if (verbose && last_block && (block != last_block + 1)) {
335                         printf("Discontinuity: Block %ld is at %lu (was %lu)\n",
336                                i, block, last_block + 1);
337                         (*num_extents)++;
338                 }
339                 fm_ext.fe_length += st->st_blksize;
340                 last_block = block;
341         }
342
343         if (force_extent)
344                 print_extent_info(&fm_ext, *num_extents - 1,
345                                   last_block * st->st_blksize, blk_shift, st);
346
347         return count;
348 }
349
350 static int frag_report(const char *filename)
351 {
352         static struct statfs fsinfo;
353         ext2fs_struct_stat st;
354         int             blk_shift;
355         long            fd;
356         unsigned long long      numblocks;
357         int             data_blocks_per_cyl = 1;
358         int             num_extents = 1, expected = ~0;
359         int             is_ext2 = 0;
360         static dev_t    last_device;
361         unsigned int    flags;
362         int             width;
363         int             rc = 0;
364
365 #if defined(HAVE_OPEN64) && !defined(__OSX_AVAILABLE_BUT_DEPRECATED)
366         fd = open64(filename, O_RDONLY);
367 #else
368         fd = open(filename, O_RDONLY);
369 #endif
370         if (fd < 0) {
371                 rc = -errno;
372                 perror("open");
373                 return rc;
374         }
375
376 #if defined(HAVE_FSTAT64) && !defined(__OSX_AVAILABLE_BUT_DEPRECATED)
377         if (fstat64(fd, &st) < 0) {
378 #else
379         if (fstat(fd, &st) < 0) {
380 #endif
381                 rc = -errno;
382                 perror("stat");
383                 close(fd);
384                 return rc;
385         }
386
387         if (last_device != st.st_dev) {
388                 if (fstatfs(fd, &fsinfo) < 0) {
389                         rc = -errno;
390                         perror("fstatfs");
391                         close(fd);
392                         return rc;
393                 }
394                 if (verbose)
395                         printf("Filesystem type is: %lx\n",
396                                (unsigned long)fsinfo.f_type);
397         }
398         st.st_blksize = fsinfo.f_bsize;
399         if (ioctl(fd, EXT3_IOC_GETFLAGS, &flags) < 0)
400                 flags = 0;
401         if (!(flags & EXT4_EXTENTS_FL) &&
402             ((fsinfo.f_type == 0xef51) || (fsinfo.f_type == 0xef52) ||
403              (fsinfo.f_type == 0xef53)))
404                 is_ext2++;
405
406         if (is_ext2) {
407                 long cylgroups = div_ceil(fsinfo.f_blocks, fsinfo.f_bsize * 8);
408
409                 if (verbose && last_device != st.st_dev)
410                         printf("Filesystem cylinder groups approximately %ld\n",
411                                cylgroups);
412
413                 data_blocks_per_cyl = fsinfo.f_bsize * 8 -
414                                         (fsinfo.f_files / 8 / cylgroups) - 3;
415         }
416         last_device = st.st_dev;
417
418         width = int_log10(fsinfo.f_blocks);
419         if (width > physical_width)
420                 physical_width = width;
421
422         numblocks = (st.st_size + fsinfo.f_bsize - 1) / fsinfo.f_bsize;
423         if (blocksize != 0)
424                 blk_shift = int_log2(blocksize);
425         else
426                 blk_shift = int_log2(fsinfo.f_bsize);
427
428         width = int_log10(numblocks);
429         if (width > logical_width)
430                 logical_width = width;
431         if (verbose)
432                 printf("File size of %s is %llu (%llu block%s of %d bytes)\n",
433                        filename, (unsigned long long)st.st_size,
434                        numblocks * fsinfo.f_bsize >> blk_shift,
435                        numblocks == 1 ? "" : "s", 1 << blk_shift);
436
437         if (!force_bmap) {
438                 rc = filefrag_fiemap(fd, blk_shift, &num_extents, &st);
439                 expected = 0;
440         }
441
442         if (rc < 0) {
443                 expected = filefrag_fibmap(fd, blk_shift, &num_extents,
444                                            &st, numblocks, is_ext2);
445                 if (expected < 0) {
446                         if (expected == -EINVAL || expected == -ENOTTY) {
447                                 fprintf(stderr, "%s: FIBMAP unsupported\n",
448                                         filename);
449                         } else if (expected == -EPERM) {
450                                 fprintf(stderr,
451                                         "%s: FIBMAP requires root privileges\n",
452                                         filename);
453                         } else {
454                                 fprintf(stderr, "%s: FIBMAP error: %s",
455                                         filename, strerror(expected));
456                         }
457                         rc = expected;
458                         goto out_close;
459                 } else {
460                         rc = 0;
461                 }
462                 expected = expected / data_blocks_per_cyl + 1;
463         }
464
465         if (num_extents == 1)
466                 printf("%s: 1 extent found", filename);
467         else
468                 printf("%s: %d extents found", filename, num_extents);
469         /* count, and thus expected, only set for indirect FIBMAP'd files */
470         if (is_ext2 && expected && expected < num_extents)
471                 printf(", perfection would be %d extent%s\n", expected,
472                         (expected > 1) ? "s" : "");
473         else
474                 fputc('\n', stdout);
475 out_close:
476         close(fd);
477
478         return rc;
479 }
480
481 static void usage(const char *progname)
482 {
483         fprintf(stderr, "Usage: %s [-b{blocksize}] [-BeklsvxX] file ...\n",
484                 progname);
485         exit(1);
486 }
487
488 int main(int argc, char**argv)
489 {
490         char **cpp;
491         int rc = 0, c;
492
493         while ((c = getopt(argc, argv, "Bb::eksvxX")) != EOF)
494                 switch (c) {
495                 case 'B':
496                         force_bmap++;
497                         break;
498                 case 'b':
499                         if (optarg) {
500                                 char *end;
501                                 blocksize = strtoul(optarg, &end, 0);
502                                 if (end) {
503                                         switch (end[0]) {
504                                         case 'g':
505                                         case 'G':
506                                                 blocksize *= 1024;
507                                                 /* no break */
508                                         case 'm':
509                                         case 'M':
510                                                 blocksize *= 1024;
511                                                 /* no break */
512                                         case 'k':
513                                         case 'K':
514                                                 blocksize *= 1024;
515                                                 break;
516                                         default:
517                                                 break;
518                                         }
519                                 }
520                         } else { /* Allow -b without argument for compat. Remove
521                                   * this eventually so "-b {blocksize}" works */
522                                 fprintf(stderr, "%s: -b needs a blocksize "
523                                         "option, assuming 1024-byte blocks.\n",
524                                         argv[0]);
525                                 blocksize = 1024;
526                         }
527                         break;
528                 case 'e':
529                         force_extent++;
530                         if (!verbose)
531                                 verbose++;
532                         break;
533                 case 'k':
534                         blocksize = 1024;
535                         break;
536                 case 's':
537                         sync_file++;
538                         break;
539                 case 'v':
540                         verbose++;
541                         break;
542                 case 'x':
543                         xattr_map++;
544                         break;
545                 case 'X':
546                         ext_fmt = hex_fmt;
547                         break;
548                 default:
549                         usage(argv[0]);
550                         break;
551                 }
552
553         if (optind == argc)
554                 usage(argv[0]);
555
556         for (cpp = argv + optind; *cpp != '\0'; cpp++) {
557                 int rc2 = frag_report(*cpp);
558
559                 if (rc2 < 0 && rc == 0)
560                         rc = rc2;
561         }
562
563         return rc;
564 }
565 #endif