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