]> git.ipfire.org Git - thirdparty/e2fsprogs.git/blob - misc/e4defrag.c
e4defrag: Fix compile warnings
[thirdparty/e2fsprogs.git] / misc / e4defrag.c
1 /*
2 * e4defrag.c - ext4 filesystem defragmenter
3 *
4 * Copyright (C) 2009 NEC Software Tohoku, Ltd.
5 *
6 * Author: Akira Fujita <a-fujita@rs.jp.nec.com>
7 * Takashi Sato <t-sato@yk.jp.nec.com>
8 */
9
10 #ifndef _LARGEFILE_SOURCE
11 #define _LARGEFILE_SOURCE
12 #endif
13
14 #ifndef _LARGEFILE64_SOURCE
15 #define _LARGEFILE64_SOURCE
16 #endif
17
18 #ifndef _GNU_SOURCE
19 #define _GNU_SOURCE
20 #endif
21
22 #include <ctype.h>
23 #include <dirent.h>
24 #include <endian.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <ftw.h>
28 #include <limits.h>
29 #include <mntent.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <ext2fs/ext2_types.h>
35 #include <ext2fs/ext2fs.h>
36 #include <linux/fs.h>
37 #include <sys/ioctl.h>
38 #include <sys/mman.h>
39 #include <sys/stat.h>
40 #include <sys/statfs.h>
41 #include <sys/syscall.h>
42 #include <sys/vfs.h>
43
44 /* Ioctl command */
45 #define FS_IOC_FIEMAP _IOWR('f', 11, struct fiemap)
46 #define EXT4_IOC_MOVE_EXT _IOWR('f', 15, struct move_extent)
47
48 /* Macro functions */
49 #define PRINT_ERR_MSG(msg) fprintf(stderr, "%s\n", (msg))
50 #define IN_FTW_PRINT_ERR_MSG(msg) \
51 fprintf(stderr, "\t%s\t\t[ NG ]\n", (msg))
52 #define PRINT_FILE_NAME(file) fprintf(stderr, " \"%s\"\n", (file))
53 #define PRINT_ERR_MSG_WITH_ERRNO(msg) \
54 fprintf(stderr, "\t%s:%s\t[ NG ]\n", (msg), strerror(errno))
55 #define STATISTIC_ERR_MSG(msg) \
56 fprintf(stderr, "\t%s\n", (msg))
57 #define STATISTIC_ERR_MSG_WITH_ERRNO(msg) \
58 fprintf(stderr, "\t%s:%s\n", (msg), strerror(errno))
59 #define min(x, y) (((x) > (y)) ? (y) : (x))
60 #define SECTOR_TO_BLOCK(sectors, blocksize) \
61 ((sectors) / ((blocksize) >> 9))
62 #define CALC_SCORE(ratio) \
63 ((ratio) > 10 ? (80 + 20 * (ratio) / 100) : (8 * (ratio)))
64 /* Wrap up the free function */
65 #define FREE(tmp) \
66 do { \
67 if ((tmp) != NULL) \
68 free(tmp); \
69 } while (0) \
70 /* Insert list2 after list1 */
71 #define insert(list1, list2) \
72 do { \
73 list2->next = list1->next; \
74 list1->next->prev = list2; \
75 list2->prev = list1; \
76 list1->next = list2; \
77 } while (0)
78
79 /* To delete unused warning */
80 #ifdef __GNUC__
81 #define EXT2FS_ATTR(x) __attribute__(x)
82 #else
83 #define EXT2FS_ATTR(x)
84 #endif
85
86 #ifndef __NR_fadvise64
87 #define __NR_fadvise64 250
88 #endif
89
90 #ifndef __NR_sync_file_range
91 #define __NR_sync_file_range 314
92 #endif
93
94 #ifndef __NR_fallocate
95 #define __NR_fallocate 324
96 #endif
97
98 #ifndef POSIX_FADV_DONTNEED
99 #if defined(__s390x__)
100 #define POSIX_FADV_DONTNEED 6 /* Don't need these pages */
101 #else
102 #define POSIX_FADV_DONTNEED 4 /* Don't need these pages */
103 #endif
104 #endif
105
106 #ifndef SYNC_FILE_RANGE_WAIT_BEFORE
107 #define SYNC_FILE_RANGE_WAIT_BEFORE 1
108 #endif
109 #ifndef SYNC_FILE_RANGE_WRITE
110 #define SYNC_FILE_RANGE_WRITE 2
111 #endif
112 #ifndef SYNC_FILE_RANGE_WAIT_AFTER
113 #define SYNC_FILE_RANGE_WAIT_AFTER 4
114 #endif
115
116 /* The mode of defrag */
117 #define DETAIL 0x01
118 #define STATISTIC 0x02
119
120 #define DEVNAME 0
121 #define DIRNAME 1
122 #define FILENAME 2
123
124 #define FTW_OPEN_FD 2000
125
126 #define FS_EXT4 "ext4"
127 #define ROOT_UID 0
128
129 #define BOUND_SCORE 55
130 #define SHOW_FRAG_FILES 5
131
132 /* Magic number for ext4 */
133 #define EXT4_SUPER_MAGIC 0xEF53
134
135 /* Definition of flex_bg */
136 #define EXT4_FEATURE_INCOMPAT_FLEX_BG 0x0200
137
138 /* The following four macros are used for ioctl FS_IOC_FIEMAP
139 * FIEMAP_FLAG_SYNC: sync file data before map.
140 * FIEMAP_EXTENT_LAST: last extent in file.
141 * FIEMAP_MAX_OFFSET: max file offset.
142 * EXTENT_MAX_COUNT: the maximum number of extents for exchanging between
143 * kernel-space and user-space per ioctl
144 */
145 #define FIEMAP_FLAG_SYNC 0x00000001
146 #define FIEMAP_EXTENT_LAST 0x00000001
147 #define FIEMAP_EXTENT_UNWRITTEN 0x00000800
148 #define FIEMAP_MAX_OFFSET (~0ULL)
149 #define EXTENT_MAX_COUNT 512
150
151 /* The following macros are error message */
152 #define MSG_USAGE \
153 "Usage : e4defrag [-v] file...| directory...| device...\n\
154 : e4defrag -c file...| directory...| device...\n"
155
156 #define NGMSG_EXT4 "Filesystem is not ext4 filesystem"
157 #define NGMSG_FILE_EXTENT "Failed to get file extents"
158 #define NGMSG_FILE_INFO "Failed to get file information"
159 #define NGMSG_FILE_OPEN "Failed to open"
160 #define NGMSG_FILE_UNREG "File is not regular file"
161 #define NGMSG_LOST_FOUND "Can not process \"lost+found\""
162
163 /* Data type for filesystem-wide blocks number */
164 typedef unsigned long long ext4_fsblk_t;
165
166 struct fiemap_extent_data {
167 __u64 len; /* blocks count */
168 __u64 logical; /* start logical block number */
169 ext4_fsblk_t physical; /* start physical block number */
170 };
171
172 struct fiemap_extent_list {
173 struct fiemap_extent_list *prev;
174 struct fiemap_extent_list *next;
175 struct fiemap_extent_data data; /* extent belong to file */
176 };
177
178 struct fiemap_extent_group {
179 struct fiemap_extent_group *prev;
180 struct fiemap_extent_group *next;
181 __u64 len; /* length of this continuous region */
182 struct fiemap_extent_list *start; /* start ext */
183 struct fiemap_extent_list *end; /* end ext */
184 };
185
186 struct move_extent {
187 __s32 reserved; /* original file descriptor */
188 __u32 donor_fd; /* donor file descriptor */
189 __u64 orig_start; /* logical start offset in block for orig */
190 __u64 donor_start; /* logical start offset in block for donor */
191 __u64 len; /* block length to be moved */
192 __u64 moved_len; /* moved block length */
193 };
194
195 struct fiemap_extent {
196 __u64 fe_logical; /* logical offset in bytes for the start of
197 * the extent from the beginning of the file */
198 __u64 fe_physical; /* physical offset in bytes for the start
199 * of the extent from the beginning
200 * of the disk */
201 __u64 fe_length; /* length in bytes for this extent */
202 __u64 fe_reserved64[2];
203 __u32 fe_flags; /* FIEMAP_EXTENT_* flags for this extent */
204 __u32 fe_reserved[3];
205 };
206
207 struct fiemap {
208 __u64 fm_start; /* logical offset (inclusive) at
209 * which to start mapping (in) */
210 __u64 fm_length; /* logical length of mapping which
211 * userspace wants (in) */
212 __u32 fm_flags; /* FIEMAP_FLAG_* flags for request (in/out) */
213 __u32 fm_mapped_extents;/* number of extents that were mapped (out) */
214 __u32 fm_extent_count; /* size of fm_extents array (in) */
215 __u32 fm_reserved;
216 struct fiemap_extent fm_extents[0];/* array of mapped extents (out) */
217 };
218
219 struct frag_statistic_ino {
220 int now_count; /* the file's extents count of before defrag */
221 int best_count; /* the best file's extents count */
222 float ratio; /* the ratio of fragmentation */
223 char msg_buffer[PATH_MAX + 1]; /* pathname of the file */
224 };
225
226 typedef __u16 __le16;
227 typedef __u32 __le32;
228 typedef __u64 __le64;
229
230 /*
231 * Structure of the super block
232 */
233 struct ext4_super_block {
234 /*00*/ __le32 s_inodes_count; /* Inodes count */
235 __le32 s_blocks_count_lo; /* Blocks count */
236 __le32 s_r_blocks_count_lo; /* Reserved blocks count */
237 __le32 s_free_blocks_count_lo; /* Free blocks count */
238 /*10*/ __le32 s_free_inodes_count; /* Free inodes count */
239 __le32 s_first_data_block; /* First Data Block */
240 __le32 s_log_block_size; /* Block size */
241 __le32 s_obso_log_frag_size; /* Obsoleted fragment size */
242 /*20*/ __le32 s_blocks_per_group; /* # Blocks per group */
243 __le32 s_obso_frags_per_group; /* Obsoleted fragments per group */
244 __le32 s_inodes_per_group; /* # Inodes per group */
245 __le32 s_mtime; /* Mount time */
246 /*30*/ __le32 s_wtime; /* Write time */
247 __le16 s_mnt_count; /* Mount count */
248 __le16 s_max_mnt_count; /* Maximal mount count */
249 __le16 s_magic; /* Magic signature */
250 __le16 s_state; /* File system state */
251 __le16 s_errors; /* Behaviour when detecting errors */
252 __le16 s_minor_rev_level; /* minor revision level */
253 /*40*/ __le32 s_lastcheck; /* time of last check */
254 __le32 s_checkinterval; /* max. time between checks */
255 __le32 s_creator_os; /* OS */
256 __le32 s_rev_level; /* Revision level */
257 /*50*/ __le16 s_def_resuid; /* Default uid for reserved blocks */
258 __le16 s_def_resgid; /* Default gid for reserved blocks */
259 /*
260 * These fields are for EXT4_DYNAMIC_REV superblocks only.
261 *
262 * Note: the difference between the compatible feature set and
263 * the incompatible feature set is that if there is a bit set
264 * in the incompatible feature set that the kernel doesn't
265 * know about, it should refuse to mount the filesystem.
266 *
267 * e2fsck's requirements are more strict; if it doesn't know
268 * about a feature in either the compatible or incompatible
269 * feature set, it must abort and not try to meddle with
270 * things it doesn't understand...
271 */
272 __le32 s_first_ino; /* First non-reserved inode */
273 __le16 s_inode_size; /* size of inode structure */
274 __le16 s_block_group_nr; /* block group # of this superblock */
275 __le32 s_feature_compat; /* compatible feature set */
276 /*60*/ __le32 s_feature_incompat; /* incompatible feature set */
277 __le32 s_feature_ro_compat; /* readonly-compatible feature set */
278 /*68*/ __u8 s_uuid[16]; /* 128-bit uuid for volume */
279 /*78*/ char s_volume_name[16]; /* volume name */
280 /*88*/ char s_last_mounted[64]; /* directory where last mounted */
281 /*C8*/ __le32 s_algorithm_usage_bitmap; /* For compression */
282 /*
283 * Performance hints. Directory preallocation should only
284 * happen if the EXT4_FEATURE_COMPAT_DIR_PREALLOC flag is on.
285 */
286 __u8 s_prealloc_blocks; /* Nr of blocks to try to preallocate*/
287 __u8 s_prealloc_dir_blocks; /* Nr to preallocate for dirs */
288 __le16 s_reserved_gdt_blocks; /* Per group desc for online growth */
289 /*
290 * Journaling support valid if EXT4_FEATURE_COMPAT_HAS_JOURNAL set.
291 */
292 /*D0*/ __u8 s_journal_uuid[16]; /* uuid of journal superblock */
293 /*E0*/ __le32 s_journal_inum; /* inode number of journal file */
294 __le32 s_journal_dev; /* device number of journal file */
295 __le32 s_last_orphan; /* start of list of inodes to delete */
296 __le32 s_hash_seed[4]; /* HTREE hash seed */
297 __u8 s_def_hash_version; /* Default hash version to use */
298 __u8 s_reserved_char_pad;
299 __le16 s_desc_size; /* size of group descriptor */
300 /*100*/ __le32 s_default_mount_opts;
301 __le32 s_first_meta_bg; /* First metablock block group */
302 __le32 s_mkfs_time; /* When the filesystem was created */
303 __le32 s_jnl_blocks[17]; /* Backup of the journal inode */
304 /* 64bit support valid if EXT4_FEATURE_COMPAT_64BIT */
305 /*150*/ __le32 s_blocks_count_hi; /* Blocks count */
306 __le32 s_r_blocks_count_hi; /* Reserved blocks count */
307 __le32 s_free_blocks_count_hi; /* Free blocks count */
308 __le16 s_min_extra_isize; /* All inodes have at least # bytes */
309 __le16 s_want_extra_isize; /* New inodes should reserve # bytes */
310 __le32 s_flags; /* Miscellaneous flags */
311 __le16 s_raid_stride; /* RAID stride */
312 __le16 s_mmp_interval; /* # seconds to wait in MMP checking */
313 __le64 s_mmp_block; /* Block for multi-mount protection */
314 __le32 s_raid_stripe_width; /* blocks on all data disks (N*stride)*/
315 __u8 s_log_groups_per_flex; /* FLEX_BG group size */
316 __u8 s_reserved_char_pad2;
317 __le16 s_reserved_pad;
318 __u32 s_reserved[162]; /* Padding to the end of the block */
319 };
320
321 char lost_found_dir[PATH_MAX + 1];
322 int block_size;
323 int extents_before_defrag;
324 int extents_after_defrag;
325 int mode_flag;
326 unsigned int current_uid;
327 unsigned int defraged_file_count;
328 unsigned int frag_files_before_defrag;
329 unsigned int frag_files_after_defrag;
330 unsigned int regular_count;
331 unsigned int succeed_cnt;
332 unsigned int total_count;
333 __u8 log_groups_per_flex;
334 __le32 blocks_per_group;
335 __le32 feature_incompat;
336 ext4_fsblk_t files_block_count;
337 struct frag_statistic_ino frag_rank[SHOW_FRAG_FILES];
338
339 /*
340 * ext2fs_swab32() - Change endian.
341 *
342 * @val: the entry used for change.
343 */
344 __u32 ext2fs_swab32(__u32 val)
345 {
346 #if BYTE_ORDER == BIG_ENDIAN
347 return (val >> 24) | ((val >> 8) & 0xFF00) |
348 ((val << 8) & 0xFF0000) | (val << 24);
349 #else
350 return val;
351 #endif
352 }
353
354 /*
355 * fadvise() - Give advice about file access.
356 *
357 * @fd: defrag target file's descriptor.
358 * @offset: file offset.
359 * @len: area length.
360 * @advise: process flag.
361 */
362 static int fadvise(int fd, loff_t offset, size_t len, int advise)
363 {
364 return syscall(__NR_fadvise64, fd, offset, len, advise);
365 }
366
367 /*
368 * sync_file_range() - Sync file region.
369 *
370 * @fd: defrag target file's descriptor.
371 * @offset: file offset.
372 * @length: area length.
373 * @flag: process flag.
374 */
375 int sync_file_range(int fd, loff_t offset, loff_t length, unsigned int flag)
376 {
377 return syscall(__NR_sync_file_range, fd, offset, length, flag);
378 }
379
380 /*
381 * fallocate() - Manipulate file space.
382 *
383 * @fd: defrag target file's descriptor.
384 * @mode: process flag.
385 * @offset: file offset.
386 * @len: file size.
387 */
388 static int fallocate(int fd, int mode, loff_t offset, loff_t len)
389 {
390 return syscall(__NR_fallocate, fd, mode, offset, len);
391 }
392
393 /*
394 * get_mount_point() - Get device's mount point.
395 *
396 * @devname: the device's name.
397 * @mount_point: the mount point.
398 * @dir_path_len: the length of directory.
399 */
400 static int get_mount_point(const char *devname, char *mount_point,
401 int dir_path_len)
402 {
403 /* Refer to /etc/mtab */
404 const char *mtab = MOUNTED;
405 FILE *fp = NULL;
406 struct mntent *mnt = NULL;
407
408 fp = setmntent(mtab, "r");
409 if (fp == NULL) {
410 perror("Couldn't access /etc/mtab");
411 return -1;
412 }
413
414 while ((mnt = getmntent(fp)) != NULL) {
415 if (strcmp(devname, mnt->mnt_fsname) != 0)
416 continue;
417
418 endmntent(fp);
419 if (strcmp(mnt->mnt_type, FS_EXT4) == 0) {
420 strncpy(mount_point, mnt->mnt_dir,
421 dir_path_len);
422 return 0;
423 }
424 PRINT_ERR_MSG(NGMSG_EXT4);
425 return -1;
426 }
427 endmntent(fp);
428 PRINT_ERR_MSG("Filesystem is not mounted");
429 return -1;
430 }
431
432 /*
433 * is_ext4() - Whether on an ext4 filesystem.
434 *
435 * @file: the file's name.
436 */
437 static int is_ext4(const char *file)
438 {
439 int maxlen = 0;
440 int len, ret;
441 FILE *fp = NULL;
442 char *mnt_type = NULL;
443 /* Refer to /etc/mtab */
444 const char *mtab = MOUNTED;
445 char file_path[PATH_MAX + 1];
446 struct mntent *mnt = NULL;
447 struct statfs64 fsbuf;
448
449 /* Get full path */
450 if (realpath(file, file_path) == NULL) {
451 perror("Couldn't get full path");
452 PRINT_FILE_NAME(file);
453 return -1;
454 }
455
456 if (statfs64(file_path, &fsbuf) < 0) {
457 perror("Failed to get filesystem information");
458 PRINT_FILE_NAME(file);
459 return -1;
460 }
461
462 if (fsbuf.f_type != EXT4_SUPER_MAGIC) {
463 PRINT_ERR_MSG(NGMSG_EXT4);
464 return -1;
465 }
466
467 fp = setmntent(mtab, "r");
468 if (fp == NULL) {
469 perror("Couldn't access /etc/mtab");
470 return -1;
471 }
472
473 while ((mnt = getmntent(fp)) != NULL) {
474 len = strlen(mnt->mnt_dir);
475 ret = memcmp(file_path, mnt->mnt_dir, len);
476 if (ret != 0)
477 continue;
478
479 if (maxlen >= len)
480 continue;
481
482 maxlen = len;
483
484 mnt_type = realloc(mnt_type, strlen(mnt->mnt_type) + 1);
485 if (mnt_type == NULL) {
486 endmntent(fp);
487 return -1;
488 }
489 memset(mnt_type, 0, strlen(mnt->mnt_type) + 1);
490 strncpy(mnt_type, mnt->mnt_type, strlen(mnt->mnt_type));
491 strncpy(lost_found_dir, mnt->mnt_dir, PATH_MAX);
492 }
493
494 endmntent(fp);
495 if (strcmp(mnt_type, FS_EXT4) == 0) {
496 FREE(mnt_type);
497 return 0;
498 } else {
499 FREE(mnt_type);
500 PRINT_ERR_MSG(NGMSG_EXT4);
501 return -1;
502 }
503 }
504
505 /*
506 * calc_entry_counts() - Calculate file counts.
507 *
508 * @file: file name.
509 * @buf: file info.
510 * @flag: file type.
511 * @ftwbuf: the pointer of a struct FTW.
512 */
513 static int calc_entry_counts(const char *file EXT2FS_ATTR((unused)),
514 const struct stat64 *buf, int flag EXT2FS_ATTR((unused)),
515 struct FTW *ftwbuf EXT2FS_ATTR((unused)))
516 {
517 if (S_ISREG(buf->st_mode))
518 regular_count++;
519
520 total_count++;
521
522 return 0;
523 }
524
525 /*
526 * page_in_core() - Get information on whether pages are in core.
527 *
528 * @fd: defrag target file's descriptor.
529 * @defrag_data: data used for defrag.
530 * @vec: page state array.
531 * @page_num: page number.
532 */
533 static int page_in_core(int fd, struct move_extent defrag_data,
534 unsigned char **vec, unsigned int *page_num)
535 {
536 long pagesize = sysconf(_SC_PAGESIZE);
537 void *page = NULL;
538 loff_t offset, end_offset, length;
539
540 if (vec == NULL || *vec != NULL)
541 return -1;
542
543 /* In mmap, offset should be a multiple of the page size */
544 offset = (loff_t)defrag_data.orig_start * block_size;
545 length = (loff_t)defrag_data.len * block_size;
546 end_offset = offset + length;
547 /* Round the offset down to the nearest multiple of pagesize */
548 offset = (offset / pagesize) * pagesize;
549 length = end_offset - offset;
550
551 page = mmap(NULL, length, PROT_READ, MAP_SHARED, fd, offset);
552 if (page == MAP_FAILED)
553 return -1;
554
555 *page_num = 0;
556 *page_num = (length + pagesize - 1) / pagesize;
557 *vec = (unsigned char *)calloc(*page_num, 1);
558 if (*vec == NULL)
559 return -1;
560
561 /* Get information on whether pages are in core */
562 if (mincore(page, (size_t)length, *vec) == -1 ||
563 munmap(page, length) == -1) {
564 FREE(*vec);
565 return -1;
566 }
567
568 return 0;
569 }
570
571 /*
572 * defrag_fadvise() - Predeclare an access pattern for file data.
573 *
574 * @fd: defrag target file's descriptor.
575 * @defrag_data: data used for defrag.
576 * @vec: page state array.
577 * @page_num: page number.
578 */
579 static int defrag_fadvise(int fd, struct move_extent defrag_data,
580 unsigned char *vec, unsigned int page_num)
581 {
582 int flag = 1;
583 long pagesize = sysconf(_SC_PAGESIZE);
584 int fadvise_flag = POSIX_FADV_DONTNEED;
585 int sync_flag = SYNC_FILE_RANGE_WAIT_BEFORE |
586 SYNC_FILE_RANGE_WRITE |
587 SYNC_FILE_RANGE_WAIT_AFTER;
588 unsigned int i;
589 loff_t offset;
590
591 offset = (loff_t)defrag_data.orig_start * block_size;
592 offset = (offset / pagesize) * pagesize;
593
594 /* Sync file for fadvise process */
595 if (sync_file_range(fd, offset,
596 (loff_t)pagesize * page_num, sync_flag) < 0)
597 return -1;
598
599 /* Try to release buffer cache which this process used,
600 * then other process can use the released buffer
601 */
602 for (i = 0; i < page_num; i++) {
603 if ((vec[i] & 0x1) == 0) {
604 offset += pagesize;
605 continue;
606 }
607 if (fadvise(fd, offset, pagesize, fadvise_flag) < 0) {
608 if ((mode_flag & DETAIL) && flag) {
609 perror("\tFailed to fadvise");
610 flag = 0;
611 }
612 }
613 offset += pagesize;
614 }
615
616 return 0;
617 }
618
619 /*
620 * check_free_size() - Check if there's enough disk space.
621 *
622 * @fd: defrag target file's descriptor.
623 * @file: file name.
624 * @buf: the pointer of the struct stat64.
625 */
626 static int check_free_size(int fd, const char *file, const struct stat64 *buf)
627 {
628 ext4_fsblk_t blk_count;
629 ext4_fsblk_t free_blk_count;
630 struct statfs64 fsbuf;
631
632 if (fstatfs64(fd, &fsbuf) < 0) {
633 if (mode_flag & DETAIL) {
634 PRINT_FILE_NAME(file);
635 PRINT_ERR_MSG_WITH_ERRNO(
636 "Failed to get filesystem information");
637 }
638 return -1;
639 }
640
641 /* Target file size measured by filesystem IO blocksize */
642 blk_count = SECTOR_TO_BLOCK(buf->st_blocks, fsbuf.f_bsize);
643
644 /* Compute free space for root and normal user separately */
645 if (current_uid == ROOT_UID)
646 free_blk_count = fsbuf.f_bfree;
647 else
648 free_blk_count = fsbuf.f_bavail;
649
650 if (free_blk_count >= blk_count)
651 return 0;
652
653 return -ENOSPC;
654 }
655
656 /*
657 * file_frag_count() - Get file fragment count.
658 *
659 * @fd: defrag target file's descriptor.
660 */
661 static int file_frag_count(int fd)
662 {
663 int ret;
664 struct fiemap fiemap_buf;
665
666 /* When fm_extent_count is 0,
667 * ioctl just get file fragment count.
668 */
669 memset(&fiemap_buf, 0, sizeof(struct fiemap));
670 fiemap_buf.fm_start = 0;
671 fiemap_buf.fm_length = FIEMAP_MAX_OFFSET;
672 fiemap_buf.fm_flags |= FIEMAP_FLAG_SYNC;
673
674 ret = ioctl(fd, FS_IOC_FIEMAP, &fiemap_buf);
675 if (ret < 0)
676 return ret;
677
678 return fiemap_buf.fm_mapped_extents;
679 }
680
681 /*
682 * file_check() - Check file's attributes.
683 *
684 * @fd: defrag target file's descriptor.
685 * @buf: a pointer of the struct stat64.
686 * @file: the file's name.
687 * @extents: the file's extents.
688 */
689 static int file_check(int fd, const struct stat64 *buf, const char *file,
690 int extents)
691 {
692 int ret;
693 struct flock lock;
694
695 /* Write-lock check is more reliable */
696 lock.l_type = F_WRLCK;
697 lock.l_start = 0;
698 lock.l_whence = SEEK_SET;
699 lock.l_len = 0;
700
701 /* Free space */
702 ret = check_free_size(fd, file, buf);
703 if (ret < 0) {
704 if ((mode_flag & DETAIL) && ret == -ENOSPC) {
705 printf("\033[79;0H\033[K[%u/%u] \"%s\"\t\t"
706 " extents: %d -> %d\n", defraged_file_count,
707 total_count, file, extents, extents);
708 IN_FTW_PRINT_ERR_MSG(
709 "Defrag size is larger than filesystem's free space");
710 }
711 return -1;
712 }
713
714 /* Access authority */
715 if (current_uid != ROOT_UID &&
716 buf->st_uid != current_uid) {
717 if (mode_flag & DETAIL) {
718 printf("\033[79;0H\033[K[%u/%u] \"%s\"\t\t"
719 " extents: %d -> %d\n", defraged_file_count,
720 total_count, file, extents, extents);
721 IN_FTW_PRINT_ERR_MSG(
722 "File is not current user's file"
723 " or current user is not root");
724 }
725 return -1;
726 }
727
728 /* Lock status */
729 if (fcntl(fd, F_GETLK, &lock) < 0) {
730 if (mode_flag & DETAIL) {
731 PRINT_FILE_NAME(file);
732 PRINT_ERR_MSG_WITH_ERRNO(
733 "Failed to get lock information");
734 }
735 return -1;
736 } else if (lock.l_type != F_UNLCK) {
737 if (mode_flag & DETAIL) {
738 PRINT_FILE_NAME(file);
739 IN_FTW_PRINT_ERR_MSG("File has been locked");
740 }
741 return -1;
742 }
743
744 return 0;
745 }
746
747 /*
748 * insert_extent_by_logical() - Sequentially insert extent by logical.
749 *
750 * @ext_list_head: the head of logical extent list.
751 * @ext: the extent element which will be inserted.
752 */
753 static int insert_extent_by_logical(struct fiemap_extent_list **ext_list_head,
754 struct fiemap_extent_list *ext)
755 {
756 struct fiemap_extent_list *ext_list_tmp = *ext_list_head;
757
758 if (ext == NULL)
759 goto out;
760
761 /* First element */
762 if (*ext_list_head == NULL) {
763 (*ext_list_head) = ext;
764 (*ext_list_head)->prev = *ext_list_head;
765 (*ext_list_head)->next = *ext_list_head;
766 return 0;
767 }
768
769 if (ext->data.logical <= ext_list_tmp->data.logical) {
770 /* Insert before head */
771 if (ext_list_tmp->data.logical <
772 ext->data.logical + ext->data.len)
773 /* Overlap */
774 goto out;
775 /* Adjust head */
776 *ext_list_head = ext;
777 } else {
778 /* Insert into the middle or last of the list */
779 do {
780 if (ext->data.logical < ext_list_tmp->data.logical)
781 break;
782 ext_list_tmp = ext_list_tmp->next;
783 } while (ext_list_tmp != (*ext_list_head));
784 if (ext->data.logical <
785 ext_list_tmp->prev->data.logical +
786 ext_list_tmp->prev->data.len)
787 /* Overlap */
788 goto out;
789
790 if (ext_list_tmp != *ext_list_head &&
791 ext_list_tmp->data.logical <
792 ext->data.logical + ext->data.len)
793 /* Overlap */
794 goto out;
795 }
796 ext_list_tmp = ext_list_tmp->prev;
797 /* Insert "ext" after "ext_list_tmp" */
798 insert(ext_list_tmp, ext);
799 return 0;
800 out:
801 errno = EINVAL;
802 return -1;
803 }
804
805 /*
806 * insert_extent_by_physical() - Sequentially insert extent by physical.
807 *
808 * @ext_list_head: the head of physical extent list.
809 * @ext: the extent element which will be inserted.
810 */
811 static int insert_extent_by_physical(struct fiemap_extent_list **ext_list_head,
812 struct fiemap_extent_list *ext)
813 {
814 struct fiemap_extent_list *ext_list_tmp = *ext_list_head;
815
816 if (ext == NULL)
817 goto out;
818
819 /* First element */
820 if (*ext_list_head == NULL) {
821 (*ext_list_head) = ext;
822 (*ext_list_head)->prev = *ext_list_head;
823 (*ext_list_head)->next = *ext_list_head;
824 return 0;
825 }
826
827 if (ext->data.physical <= ext_list_tmp->data.physical) {
828 /* Insert before head */
829 if (ext_list_tmp->data.physical <
830 ext->data.physical + ext->data.len)
831 /* Overlap */
832 goto out;
833 /* Adjust head */
834 *ext_list_head = ext;
835 } else {
836 /* Insert into the middle or last of the list */
837 do {
838 if (ext->data.physical < ext_list_tmp->data.physical)
839 break;
840 ext_list_tmp = ext_list_tmp->next;
841 } while (ext_list_tmp != (*ext_list_head));
842 if (ext->data.physical <
843 ext_list_tmp->prev->data.physical +
844 ext_list_tmp->prev->data.len)
845 /* Overlap */
846 goto out;
847
848 if (ext_list_tmp != *ext_list_head &&
849 ext_list_tmp->data.physical <
850 ext->data.physical + ext->data.len)
851 /* Overlap */
852 goto out;
853 }
854 ext_list_tmp = ext_list_tmp->prev;
855 /* Insert "ext" after "ext_list_tmp" */
856 insert(ext_list_tmp, ext);
857 return 0;
858 out:
859 errno = EINVAL;
860 return -1;
861 }
862
863 /*
864 * insert_exts_group() - Insert a exts_group.
865 *
866 * @ext_group_head: the head of a exts_group list.
867 * @exts_group: the exts_group element which will be inserted.
868 */
869 static int insert_exts_group(struct fiemap_extent_group **ext_group_head,
870 struct fiemap_extent_group *exts_group)
871 {
872 struct fiemap_extent_group *ext_group_tmp = NULL;
873
874 if (exts_group == NULL) {
875 errno = EINVAL;
876 return -1;
877 }
878
879 /* Initialize list */
880 if (*ext_group_head == NULL) {
881 (*ext_group_head) = exts_group;
882 (*ext_group_head)->prev = *ext_group_head;
883 (*ext_group_head)->next = *ext_group_head;
884 return 0;
885 }
886
887 ext_group_tmp = (*ext_group_head)->prev;
888 insert(ext_group_tmp, exts_group);
889
890 return 0;
891 }
892
893 /*
894 * join_extents() - Find continuous region(exts_group).
895 *
896 * @ext_list_head: the head of the extent list.
897 * @ext_group_head: the head of the target exts_group list.
898 */
899 static int join_extents(struct fiemap_extent_list *ext_list_head,
900 struct fiemap_extent_group **ext_group_head)
901 {
902 __u64 len = ext_list_head->data.len;
903 struct fiemap_extent_list *ext_list_start = ext_list_head;
904 struct fiemap_extent_list *ext_list_tmp = ext_list_head->next;
905
906 do {
907 struct fiemap_extent_group *ext_group_tmp = NULL;
908
909 /* This extent and previous extent are not continuous,
910 * so, all previous extents are treated as an extent group.
911 */
912 if ((ext_list_tmp->prev->data.logical +
913 ext_list_tmp->prev->data.len)
914 != ext_list_tmp->data.logical) {
915 ext_group_tmp =
916 malloc(sizeof(struct fiemap_extent_group));
917 if (ext_group_tmp == NULL)
918 return -1;
919
920 memset(ext_group_tmp, 0,
921 sizeof(struct fiemap_extent_group));
922 ext_group_tmp->len = len;
923 ext_group_tmp->start = ext_list_start;
924 ext_group_tmp->end = ext_list_tmp->prev;
925
926 if (insert_exts_group(ext_group_head,
927 ext_group_tmp) < 0) {
928 FREE(ext_group_tmp);
929 return -1;
930 }
931 ext_list_start = ext_list_tmp;
932 len = ext_list_tmp->data.len;
933 ext_list_tmp = ext_list_tmp->next;
934 continue;
935 }
936
937 /* This extent and previous extent are continuous,
938 * so, they belong to the same extent group, and we check
939 * if the next extent belongs to the same extent group.
940 */
941 len += ext_list_tmp->data.len;
942 ext_list_tmp = ext_list_tmp->next;
943 } while (ext_list_tmp != ext_list_head->next);
944
945 return 0;
946 }
947
948 /*
949 * get_file_extents() - Get file's extent list.
950 *
951 * @fd: defrag target file's descriptor.
952 * @ext_list_head: the head of the extent list.
953 */
954 static int get_file_extents(int fd, struct fiemap_extent_list **ext_list_head)
955 {
956 __u32 i;
957 int ret;
958 int ext_buf_size, fie_buf_size;
959 __u64 pos = 0;
960 struct fiemap *fiemap_buf = NULL;
961 struct fiemap_extent *ext_buf = NULL;
962 struct fiemap_extent_list *ext_list = NULL;
963
964 /* Convert units, in bytes.
965 * Be careful : now, physical block number in extent is 48bit,
966 * and the maximum blocksize for ext4 is 4K(12bit),
967 * so there is no overflow, but in future it may be changed.
968 */
969
970 /* Alloc space for fiemap */
971 ext_buf_size = EXTENT_MAX_COUNT * sizeof(struct fiemap_extent);
972 fie_buf_size = sizeof(struct fiemap) + ext_buf_size;
973
974 fiemap_buf = malloc(fie_buf_size);
975 if (fiemap_buf == NULL)
976 return -1;
977
978 ext_buf = fiemap_buf->fm_extents;
979 memset(fiemap_buf, 0, fie_buf_size);
980 fiemap_buf->fm_length = FIEMAP_MAX_OFFSET;
981 fiemap_buf->fm_flags |= FIEMAP_FLAG_SYNC;
982 fiemap_buf->fm_extent_count = EXTENT_MAX_COUNT;
983
984 do {
985 fiemap_buf->fm_start = pos;
986 memset(ext_buf, 0, ext_buf_size);
987 ret = ioctl(fd, FS_IOC_FIEMAP, fiemap_buf);
988 if (ret < 0)
989 goto out;
990 for (i = 0; i < fiemap_buf->fm_mapped_extents; i++) {
991 ext_list = NULL;
992 ext_list = malloc(sizeof(struct fiemap_extent_list));
993 if (ext_list == NULL)
994 goto out;
995
996 ext_list->data.physical = ext_buf[i].fe_physical
997 / block_size;
998 ext_list->data.logical = ext_buf[i].fe_logical
999 / block_size;
1000 ext_list->data.len = ext_buf[i].fe_length
1001 / block_size;
1002
1003 ret = insert_extent_by_physical(
1004 ext_list_head, ext_list);
1005 if (ret < 0) {
1006 FREE(ext_list);
1007 goto out;
1008 }
1009 }
1010 /* Record file's logical offset this time */
1011 pos = ext_buf[EXTENT_MAX_COUNT-1].fe_logical +
1012 ext_buf[EXTENT_MAX_COUNT-1].fe_length;
1013 /*
1014 * If fm_extents array has been filled and
1015 * there are extents left, continue to cycle.
1016 */
1017 } while (fiemap_buf->fm_mapped_extents
1018 == EXTENT_MAX_COUNT &&
1019 !(ext_buf[EXTENT_MAX_COUNT-1].fe_flags
1020 & FIEMAP_EXTENT_LAST));
1021
1022 FREE(fiemap_buf);
1023 return 0;
1024 out:
1025 FREE(fiemap_buf);
1026 return -1;
1027 }
1028
1029 /*
1030 * get_logical_count() - Get the file logical extents count.
1031 *
1032 * @logical_list_head: the head of the logical extent list.
1033 */
1034 static int get_logical_count(struct fiemap_extent_list *logical_list_head)
1035 {
1036 int ret = 0;
1037 struct fiemap_extent_list *ext_list_tmp = logical_list_head;
1038
1039 do {
1040 ret++;
1041 ext_list_tmp = ext_list_tmp->next;
1042 } while (ext_list_tmp != logical_list_head);
1043
1044 return ret;
1045 }
1046
1047 /*
1048 * get_physical_count() - Get the file physical extents count.
1049 *
1050 * @physical_list_head: the head of the physical extent list.
1051 */
1052 static int get_physical_count(struct fiemap_extent_list *physical_list_head)
1053 {
1054 int ret = 0;
1055 struct fiemap_extent_list *ext_list_tmp = physical_list_head;
1056
1057 do {
1058 if ((ext_list_tmp->data.physical + ext_list_tmp->data.len)
1059 != ext_list_tmp->next->data.physical) {
1060 /* This extent and next extent are not continuous. */
1061 ret++;
1062 }
1063
1064 ext_list_tmp = ext_list_tmp->next;
1065 } while (ext_list_tmp != physical_list_head);
1066
1067 return ret;
1068 }
1069
1070 /*
1071 * change_physical_to_logical() - Change list from physical to logical.
1072 *
1073 * @physical_list_head: the head of physical extent list.
1074 * @logical_list_head: the head of logical extent list.
1075 */
1076 static int change_physical_to_logical(
1077 struct fiemap_extent_list **physical_list_head,
1078 struct fiemap_extent_list **logical_list_head)
1079 {
1080 int ret;
1081 struct fiemap_extent_list *ext_list_tmp = *physical_list_head;
1082 struct fiemap_extent_list *ext_list_next = ext_list_tmp->next;
1083
1084 while (1) {
1085 if (ext_list_tmp == ext_list_next) {
1086 ret = insert_extent_by_logical(
1087 logical_list_head, ext_list_tmp);
1088 if (ret < 0)
1089 return -1;
1090
1091 *physical_list_head = NULL;
1092 break;
1093 }
1094
1095 ext_list_tmp->prev->next = ext_list_tmp->next;
1096 ext_list_tmp->next->prev = ext_list_tmp->prev;
1097 *physical_list_head = ext_list_next;
1098
1099 ret = insert_extent_by_logical(
1100 logical_list_head, ext_list_tmp);
1101 if (ret < 0) {
1102 FREE(ext_list_tmp);
1103 return -1;
1104 }
1105 ext_list_tmp = ext_list_next;
1106 ext_list_next = ext_list_next->next;
1107 }
1108
1109 return 0;
1110 }
1111
1112 /*
1113 * free_ext() - Free the extent list.
1114 *
1115 * @ext_list_head: the extent list head of which will be free.
1116 */
1117 static void free_ext(struct fiemap_extent_list *ext_list_head)
1118 {
1119 struct fiemap_extent_list *ext_list_tmp = NULL;
1120
1121 if (ext_list_head == NULL)
1122 return;
1123
1124 while (ext_list_head->next != ext_list_head) {
1125 ext_list_tmp = ext_list_head;
1126 ext_list_head->prev->next = ext_list_head->next;
1127 ext_list_head->next->prev = ext_list_head->prev;
1128 ext_list_head = ext_list_head->next;
1129 free(ext_list_tmp);
1130 }
1131 free(ext_list_head);
1132 }
1133
1134 /*
1135 * free_exts_group() - Free the exts_group.
1136 *
1137 * @*ext_group_head: the exts_group list head which will be free.
1138 */
1139 static void free_exts_group(struct fiemap_extent_group *ext_group_head)
1140 {
1141 struct fiemap_extent_group *ext_group_tmp = NULL;
1142
1143 if (ext_group_head == NULL)
1144 return;
1145
1146 while (ext_group_head->next != ext_group_head) {
1147 ext_group_tmp = ext_group_head;
1148 ext_group_head->prev->next = ext_group_head->next;
1149 ext_group_head->next->prev = ext_group_head->prev;
1150 ext_group_head = ext_group_head->next;
1151 free(ext_group_tmp);
1152 }
1153 free(ext_group_head);
1154 }
1155
1156 /*
1157 * get_superblock_info() - Get superblock info by the file name.
1158 *
1159 * @file: the file's name.
1160 * @sb: the pointer of the struct ext4_super_block.
1161 */
1162 static int get_superblock_info(const char *file, struct ext4_super_block *sb)
1163 {
1164 /* Refer to /etc/mtab */
1165 const char *mtab = MOUNTED;
1166 FILE *fp = NULL;
1167
1168 int fd = -1;
1169 int ret;
1170 size_t maxlen = 0;
1171 size_t len;
1172 char dev_name[PATH_MAX + 1];
1173 struct mntent *mnt = NULL;
1174
1175 fp = setmntent(mtab, "r");
1176 if (fp == NULL)
1177 return -1;
1178
1179 while ((mnt = getmntent(fp)) != NULL) {
1180 len = strlen(mnt->mnt_dir);
1181 ret = memcmp(file, mnt->mnt_dir, len);
1182 if (ret != 0)
1183 continue;
1184
1185 if (len < maxlen)
1186 continue;
1187
1188 maxlen = len;
1189
1190 memset(dev_name, 0, PATH_MAX + 1);
1191 strncpy(dev_name, mnt->mnt_fsname,
1192 strnlen(mnt->mnt_fsname, PATH_MAX));
1193 }
1194
1195 fd = open64(dev_name, O_RDONLY);
1196 if (fd < 0) {
1197 ret = -1;
1198 goto out;
1199 }
1200
1201 /* Set offset to read superblock */
1202 ret = lseek64(fd, SUPERBLOCK_OFFSET, SEEK_SET);
1203 if (ret < 0)
1204 goto out;
1205
1206 ret = read(fd, sb, sizeof(struct ext4_super_block));
1207 if (ret < 0)
1208 goto out;
1209
1210 out:
1211 if (fd != -1)
1212 close(fd);
1213 endmntent(fp);
1214 return ret;
1215 }
1216
1217 /*
1218 * get_best_count() - Get the file best extents count.
1219 *
1220 * @block_count: the file's physical block count.
1221 */
1222 static int get_best_count(ext4_fsblk_t block_count)
1223 {
1224 int ret;
1225 unsigned int flex_bg_num;
1226
1227 /* Calcuate best extents count */
1228 if (feature_incompat & EXT4_FEATURE_INCOMPAT_FLEX_BG) {
1229 flex_bg_num = 1 << log_groups_per_flex;
1230 ret = ((block_count - 1) /
1231 ((ext4_fsblk_t)blocks_per_group *
1232 flex_bg_num)) + 1;
1233 } else
1234 ret = ((block_count - 1) / blocks_per_group) + 1;
1235
1236 return ret;
1237 }
1238
1239
1240 /*
1241 * file_statistic() - Get statistic info of the file's fragments.
1242 *
1243 * @file: the file's name.
1244 * @buf: the pointer of the struct stat64.
1245 * @flag: file type.
1246 * @ftwbuf: the pointer of a struct FTW.
1247 */
1248 static int file_statistic(const char *file, const struct stat64 *buf,
1249 int flag EXT2FS_ATTR((unused)),
1250 struct FTW *ftwbuf EXT2FS_ATTR((unused)))
1251 {
1252 int fd;
1253 int ret;
1254 int now_ext_count, best_ext_count = 0, physical_ext_count;
1255 int i, j;
1256 float ratio = 0.0;
1257 ext4_fsblk_t blk_count = 0;
1258 char msg_buffer[PATH_MAX + 24];
1259 struct fiemap_extent_list *physical_list_head = NULL;
1260 struct fiemap_extent_list *logical_list_head = NULL;
1261
1262 defraged_file_count++;
1263
1264 if (mode_flag & DETAIL) {
1265 if (total_count == 1 && regular_count == 1)
1266 printf("<File>\n");
1267 else {
1268 printf("[%u/%u]", defraged_file_count, total_count);
1269 fflush(stdout);
1270 }
1271 }
1272 if (lost_found_dir[0] != '\0' &&
1273 !memcmp(file, lost_found_dir, strnlen(lost_found_dir, PATH_MAX))) {
1274 if (mode_flag & DETAIL) {
1275 PRINT_FILE_NAME(file);
1276 STATISTIC_ERR_MSG(NGMSG_LOST_FOUND);
1277 }
1278 return 0;
1279 }
1280
1281 if (!S_ISREG(buf->st_mode)) {
1282 if (mode_flag & DETAIL) {
1283 PRINT_FILE_NAME(file);
1284 STATISTIC_ERR_MSG(NGMSG_FILE_UNREG);
1285 }
1286 return 0;
1287 }
1288
1289 /* Access authority */
1290 if (current_uid != ROOT_UID &&
1291 buf->st_uid != current_uid) {
1292 if (mode_flag & DETAIL) {
1293 PRINT_FILE_NAME(file);
1294 STATISTIC_ERR_MSG(
1295 "File is not current user's file"
1296 " or current user is not root");
1297 }
1298 return 0;
1299 }
1300
1301 /* Empty file */
1302 if (buf->st_size == 0) {
1303 if (mode_flag & DETAIL) {
1304 PRINT_FILE_NAME(file);
1305 STATISTIC_ERR_MSG("File size is 0");
1306 }
1307 return 0;
1308 }
1309
1310 /* Has no blocks */
1311 if (buf->st_blocks == 0) {
1312 if (mode_flag & DETAIL) {
1313 PRINT_FILE_NAME(file);
1314 STATISTIC_ERR_MSG("File has no blocks");
1315 }
1316 return 0;
1317 }
1318
1319 fd = open64(file, O_RDONLY);
1320 if (fd < 0) {
1321 if (mode_flag & DETAIL) {
1322 PRINT_FILE_NAME(file);
1323 STATISTIC_ERR_MSG_WITH_ERRNO(NGMSG_FILE_OPEN);
1324 }
1325 return 0;
1326 }
1327
1328 /* Get file's physical extents */
1329 ret = get_file_extents(fd, &physical_list_head);
1330 if (ret < 0) {
1331 if (mode_flag & DETAIL) {
1332 PRINT_FILE_NAME(file);
1333 STATISTIC_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
1334 }
1335 goto out;
1336 }
1337
1338 /* Get the count of file's continuous physical region */
1339 physical_ext_count = get_physical_count(physical_list_head);
1340
1341 /* Change list from physical to logical */
1342 ret = change_physical_to_logical(&physical_list_head,
1343 &logical_list_head);
1344 if (ret < 0) {
1345 if (mode_flag & DETAIL) {
1346 PRINT_FILE_NAME(file);
1347 STATISTIC_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
1348 }
1349 goto out;
1350 }
1351
1352 /* Count file fragments before defrag */
1353 now_ext_count = get_logical_count(logical_list_head);
1354
1355 if (current_uid == ROOT_UID) {
1356 /* Calculate fragment ratio */
1357 blk_count =
1358 SECTOR_TO_BLOCK(buf->st_blocks, block_size);
1359
1360 best_ext_count = get_best_count(blk_count);
1361
1362 ratio = (float)(physical_ext_count - best_ext_count) * 100 /
1363 blk_count;
1364
1365 extents_before_defrag += now_ext_count;
1366 extents_after_defrag += best_ext_count;
1367 files_block_count += blk_count;
1368 }
1369
1370 if (total_count == 1 && regular_count == 1) {
1371 /* File only */
1372 if (mode_flag & DETAIL) {
1373 int count = 0;
1374 struct fiemap_extent_list *ext_list_tmp =
1375 logical_list_head;
1376
1377 /* Print extents info */
1378 do {
1379 count++;
1380 printf("[ext %d]:\tstart %llu:\tlogical "
1381 "%llu:\tlen %llu\n", count,
1382 ext_list_tmp->data.physical,
1383 ext_list_tmp->data.logical,
1384 ext_list_tmp->data.len);
1385 ext_list_tmp = ext_list_tmp->next;
1386 } while (ext_list_tmp != logical_list_head);
1387
1388 } else {
1389 printf("%-40s%10s/%-10s%9s\n",
1390 "<File>", "now", "best", "ratio");
1391 if (current_uid == ROOT_UID) {
1392 if (strlen(file) > 40)
1393 printf("%s\n%50d/%-10d%8.2f%%\n",
1394 file, now_ext_count,
1395 best_ext_count, ratio);
1396 else
1397 printf("%-40s%10d/%-10d%8.2f%%\n",
1398 file, now_ext_count,
1399 best_ext_count, ratio);
1400 } else {
1401 if (strlen(file) > 40)
1402 printf("%s\n%50d/%-10s%7s\n",
1403 file, now_ext_count,
1404 "-", "-");
1405 else
1406 printf("%-40s%10d/%-10s%7s\n",
1407 file, now_ext_count,
1408 "-", "-");
1409 }
1410 }
1411 succeed_cnt++;
1412 goto out;
1413 }
1414
1415 if (mode_flag & DETAIL) {
1416 /* Print statistic info */
1417 sprintf(msg_buffer, "[%u/%u]%s",
1418 defraged_file_count, total_count, file);
1419 if (current_uid == ROOT_UID) {
1420 if (strlen(msg_buffer) > 40)
1421 printf("\033[79;0H\033[K%s\n"
1422 "%50d/%-10d%8.2f%%\n",
1423 msg_buffer, now_ext_count,
1424 best_ext_count, ratio);
1425 else
1426 printf("\033[79;0H\033[K%-40s"
1427 "%10d/%-10d%8.2f%%\n",
1428 msg_buffer, now_ext_count,
1429 best_ext_count, ratio);
1430 } else {
1431 if (strlen(msg_buffer) > 40)
1432 printf("\033[79;0H\033[K%s\n%50d/%-10s%7s\n",
1433 msg_buffer, now_ext_count,
1434 "-", "-");
1435 else
1436 printf("\033[79;0H\033[K%-40s%10d/%-10s%7s\n",
1437 msg_buffer, now_ext_count,
1438 "-", "-");
1439 }
1440 }
1441
1442 for (i = 0; i < SHOW_FRAG_FILES; i++) {
1443 if (ratio >= frag_rank[i].ratio) {
1444 for (j = SHOW_FRAG_FILES - 1; j > i; j--) {
1445 memcpy(&frag_rank[j], &frag_rank[j - 1],
1446 sizeof(struct frag_statistic_ino));
1447 }
1448 memset(&frag_rank[i], 0,
1449 sizeof(struct frag_statistic_ino));
1450 strncpy(frag_rank[i].msg_buffer, file,
1451 strnlen(file, PATH_MAX));
1452 frag_rank[i].now_count = now_ext_count;
1453 frag_rank[i].best_count = best_ext_count;
1454 frag_rank[i].ratio = ratio;
1455 break;
1456 }
1457 }
1458
1459 succeed_cnt++;
1460
1461 out:
1462 close(fd);
1463 free_ext(physical_list_head);
1464 free_ext(logical_list_head);
1465 return 0;
1466 }
1467
1468 /*
1469 * print_progress - Print defrag progress
1470 *
1471 * @file: file name.
1472 * @start: logical offset for defrag target file
1473 * @file_size: defrag target filesize
1474 */
1475 static void print_progress(const char *file, loff_t start, loff_t file_size)
1476 {
1477 int percent = (start * 100) / file_size;
1478 printf("\033[79;0H\033[K[%u/%u]%s:\t%3d%%",
1479 defraged_file_count, total_count, file, min(percent, 100));
1480 fflush(stdout);
1481
1482 return;
1483 }
1484
1485 /*
1486 * call_defrag() - Execute the defrag program.
1487 *
1488 * @fd: target file descriptor.
1489 * @donor_fd: donor file descriptor.
1490 * @file: target file name.
1491 * @buf: pointer of the struct stat64.
1492 * @ext_list_head: head of the extent list.
1493 */
1494 static int call_defrag(int fd, int donor_fd, const char *file,
1495 const struct stat64 *buf, struct fiemap_extent_list *ext_list_head)
1496 {
1497 loff_t start = 0;
1498 unsigned int page_num;
1499 unsigned char *vec = NULL;
1500 int defraged_ret = 0;
1501 int ret;
1502 struct move_extent move_data;
1503 struct fiemap_extent_list *ext_list_tmp = NULL;
1504
1505 memset(&move_data, 0, sizeof(struct move_extent));
1506 move_data.donor_fd = donor_fd;
1507
1508 /* Print defrag progress */
1509 print_progress(file, start, buf->st_size);
1510
1511 ext_list_tmp = ext_list_head;
1512 do {
1513 move_data.orig_start = ext_list_tmp->data.logical;
1514 /* Logical offset of orig and donor should be same */
1515 move_data.donor_start = move_data.orig_start;
1516 move_data.len = ext_list_tmp->data.len;
1517 move_data.moved_len = 0;
1518
1519 ret = page_in_core(fd, move_data, &vec, &page_num);
1520 if (ret < 0) {
1521 if (mode_flag & DETAIL) {
1522 printf("\n");
1523 PRINT_ERR_MSG_WITH_ERRNO(
1524 "Failed to get file map");
1525 } else {
1526 printf("\t[ NG ]\n");
1527 }
1528 return -1;
1529 }
1530
1531 /* EXT4_IOC_MOVE_EXT */
1532 defraged_ret =
1533 ioctl(fd, EXT4_IOC_MOVE_EXT, &move_data);
1534
1535 /* Free pages */
1536 ret = defrag_fadvise(fd, move_data, vec, page_num);
1537 if (vec) {
1538 free(vec);
1539 vec = NULL;
1540 }
1541 if (ret < 0) {
1542 if (mode_flag & DETAIL) {
1543 printf("\n");
1544 PRINT_ERR_MSG_WITH_ERRNO(
1545 "Failed to free page");
1546 } else {
1547 printf("\t[ NG ]\n");
1548 }
1549 return -1;
1550 }
1551
1552 if (defraged_ret < 0) {
1553 if (mode_flag & DETAIL) {
1554 printf("\n");
1555 PRINT_ERR_MSG_WITH_ERRNO(
1556 "Failed to defrag");
1557 } else {
1558 printf("\t[ NG ]\n");
1559 }
1560 return -1;
1561 }
1562 /* Adjust logical offset for next ioctl */
1563 move_data.orig_start += move_data.moved_len;
1564 move_data.donor_start = move_data.orig_start;
1565
1566 start = move_data.orig_start * buf->st_blksize;
1567
1568 /* Print defrag progress */
1569 print_progress(file, start, buf->st_size);
1570
1571 /* End of file */
1572 if (start >= buf->st_size)
1573 break;
1574
1575 ext_list_tmp = ext_list_tmp->next;
1576 } while (ext_list_tmp != ext_list_head);
1577
1578 return 0;
1579 }
1580
1581 /*
1582 * file_defrag() - Check file attributes and call ioctl to defrag.
1583 *
1584 * @file: the file's name.
1585 * @buf: the pointer of the struct stat64.
1586 * @flag: file type.
1587 * @ftwbuf: the pointer of a struct FTW.
1588 */
1589 static int file_defrag(const char *file, const struct stat64 *buf,
1590 int flag EXT2FS_ATTR((unused)),
1591 struct FTW *ftwbuf EXT2FS_ATTR((unused)))
1592 {
1593 int fd;
1594 int donor_fd = -1;
1595 int ret;
1596 int best;
1597 int file_frags_start, file_frags_end;
1598 int orig_physical_cnt, donor_physical_cnt = 0;
1599 char tmp_inode_name[PATH_MAX + 8];
1600 struct fiemap_extent_list *orig_list_physical = NULL;
1601 struct fiemap_extent_list *orig_list_logical = NULL;
1602 struct fiemap_extent_list *donor_list_physical = NULL;
1603 struct fiemap_extent_list *donor_list_logical = NULL;
1604 struct fiemap_extent_group *orig_group_head = NULL;
1605 struct fiemap_extent_group *orig_group_tmp = NULL;
1606
1607 defraged_file_count++;
1608
1609 if (mode_flag & DETAIL) {
1610 printf("[%u/%u]", defraged_file_count, total_count);
1611 fflush(stdout);
1612 }
1613
1614 if (lost_found_dir[0] != '\0' &&
1615 !memcmp(file, lost_found_dir, strnlen(lost_found_dir, PATH_MAX))) {
1616 if (mode_flag & DETAIL) {
1617 PRINT_FILE_NAME(file);
1618 IN_FTW_PRINT_ERR_MSG(NGMSG_LOST_FOUND);
1619 }
1620 return 0;
1621 }
1622
1623 if (!S_ISREG(buf->st_mode)) {
1624 if (mode_flag & DETAIL) {
1625 PRINT_FILE_NAME(file);
1626 IN_FTW_PRINT_ERR_MSG(NGMSG_FILE_UNREG);
1627 }
1628 return 0;
1629 }
1630
1631 /* Empty file */
1632 if (buf->st_size == 0) {
1633 if (mode_flag & DETAIL) {
1634 PRINT_FILE_NAME(file);
1635 IN_FTW_PRINT_ERR_MSG("File size is 0");
1636 }
1637 return 0;
1638 }
1639
1640 /* Has no blocks */
1641 if (buf->st_blocks == 0) {
1642 if (mode_flag & DETAIL) {
1643 PRINT_FILE_NAME(file);
1644 STATISTIC_ERR_MSG("File has no blocks");
1645 }
1646 return 0;
1647 }
1648
1649 fd = open64(file, O_RDONLY);
1650 if (fd < 0) {
1651 if (mode_flag & DETAIL) {
1652 PRINT_FILE_NAME(file);
1653 PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_OPEN);
1654 }
1655 return 0;
1656 }
1657
1658 /* Get file's extents */
1659 ret = get_file_extents(fd, &orig_list_physical);
1660 if (ret < 0) {
1661 if (mode_flag & DETAIL) {
1662 PRINT_FILE_NAME(file);
1663 PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
1664 }
1665 goto out;
1666 }
1667
1668 /* Get the count of file's continuous physical region */
1669 orig_physical_cnt = get_physical_count(orig_list_physical);
1670
1671 /* Change list from physical to logical */
1672 ret = change_physical_to_logical(&orig_list_physical,
1673 &orig_list_logical);
1674 if (ret < 0) {
1675 if (mode_flag & DETAIL) {
1676 PRINT_FILE_NAME(file);
1677 PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
1678 }
1679 goto out;
1680 }
1681
1682 /* Count file fragments before defrag */
1683 file_frags_start = get_logical_count(orig_list_logical);
1684
1685 if (file_check(fd, buf, file, file_frags_start) < 0)
1686 goto out;
1687
1688 if (fsync(fd) < 0) {
1689 if (mode_flag & DETAIL) {
1690 PRINT_FILE_NAME(file);
1691 PRINT_ERR_MSG_WITH_ERRNO("Failed to sync(fsync)");
1692 }
1693 goto out;
1694 }
1695
1696 if (current_uid == ROOT_UID)
1697 best =
1698 get_best_count(SECTOR_TO_BLOCK(buf->st_blocks, block_size));
1699 else
1700 best = 1;
1701
1702 if (file_frags_start <= best)
1703 goto check_improvement;
1704
1705 /* Combine extents to group */
1706 ret = join_extents(orig_list_logical, &orig_group_head);
1707 if (ret < 0) {
1708 if (mode_flag & DETAIL) {
1709 PRINT_FILE_NAME(file);
1710 PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
1711 }
1712 goto out;
1713 }
1714
1715 /* Create donor inode */
1716 memset(tmp_inode_name, 0, PATH_MAX + 8);
1717 sprintf(tmp_inode_name, "%.*s.defrag",
1718 (int)strnlen(file, PATH_MAX), file);
1719 donor_fd = open64(tmp_inode_name, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR);
1720 if (donor_fd < 0) {
1721 if (mode_flag & DETAIL) {
1722 PRINT_FILE_NAME(file);
1723 if (errno == EEXIST)
1724 PRINT_ERR_MSG_WITH_ERRNO(
1725 "File is being defraged by other program");
1726 else
1727 PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_OPEN);
1728 }
1729 goto out;
1730 }
1731
1732 /* Unlink donor inode */
1733 ret = unlink(tmp_inode_name);
1734 if (ret < 0) {
1735 if (mode_flag & DETAIL) {
1736 PRINT_FILE_NAME(file);
1737 PRINT_ERR_MSG_WITH_ERRNO("Failed to unlink");
1738 }
1739 goto out;
1740 }
1741
1742 /* Allocate space for donor inode */
1743 orig_group_tmp = orig_group_head;
1744 do {
1745 ret = fallocate(donor_fd, 0,
1746 (loff_t)orig_group_tmp->start->data.logical * block_size,
1747 (loff_t)orig_group_tmp->len * block_size);
1748 if (ret < 0) {
1749 if (mode_flag & DETAIL) {
1750 PRINT_FILE_NAME(file);
1751 PRINT_ERR_MSG_WITH_ERRNO("Failed to fallocate");
1752 }
1753 goto out;
1754 }
1755
1756 orig_group_tmp = orig_group_tmp->next;
1757 } while (orig_group_tmp != orig_group_head);
1758
1759 /* Get donor inode's extents */
1760 ret = get_file_extents(donor_fd, &donor_list_physical);
1761 if (ret < 0) {
1762 if (mode_flag & DETAIL) {
1763 PRINT_FILE_NAME(file);
1764 PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
1765 }
1766 goto out;
1767 }
1768
1769 /* Calcuate donor inode's continuous physical region */
1770 donor_physical_cnt = get_physical_count(donor_list_physical);
1771
1772 /* Change donor extent list from physical to logical */
1773 ret = change_physical_to_logical(&donor_list_physical,
1774 &donor_list_logical);
1775 if (ret < 0) {
1776 if (mode_flag & DETAIL) {
1777 PRINT_FILE_NAME(file);
1778 PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
1779 }
1780 goto out;
1781 }
1782
1783 check_improvement:
1784 if (mode_flag & DETAIL) {
1785 if (file_frags_start != 1)
1786 frag_files_before_defrag++;
1787
1788 extents_before_defrag += file_frags_start;
1789 }
1790
1791 if (file_frags_start <= best ||
1792 orig_physical_cnt <= donor_physical_cnt) {
1793 printf("\033[79;0H\033[K[%u/%u]%s:\t%3d%%",
1794 defraged_file_count, total_count, file, 100);
1795 if (mode_flag & DETAIL)
1796 printf(" extents: %d -> %d",
1797 file_frags_start, file_frags_start);
1798
1799 printf("\t[ OK ]\n");
1800 succeed_cnt++;
1801
1802 if (file_frags_start != 1)
1803 frag_files_after_defrag++;
1804
1805 extents_after_defrag += file_frags_start;
1806 goto out;
1807 }
1808
1809 /* Defrag the file */
1810 ret = call_defrag(fd, donor_fd, file, buf, donor_list_logical);
1811
1812 /* Count file fragments after defrag and print extents info */
1813 if (mode_flag & DETAIL) {
1814 file_frags_end = file_frag_count(fd);
1815 if (file_frags_end < 0) {
1816 printf("\n");
1817 PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_INFO);
1818 goto out;
1819 }
1820
1821 if (file_frags_end != 1)
1822 frag_files_after_defrag++;
1823
1824 extents_after_defrag += file_frags_end;
1825
1826 if (ret < 0)
1827 goto out;
1828
1829 printf(" extents: %d -> %d",
1830 file_frags_start, file_frags_end);
1831 fflush(stdout);
1832 }
1833
1834 if (ret < 0)
1835 goto out;
1836
1837 printf("\t[ OK ]\n");
1838 fflush(stdout);
1839 succeed_cnt++;
1840
1841 out:
1842 close(fd);
1843 if (donor_fd != -1)
1844 close(donor_fd);
1845 free_ext(orig_list_physical);
1846 free_ext(orig_list_logical);
1847 free_ext(donor_list_physical);
1848 free_exts_group(orig_group_head);
1849 return 0;
1850 }
1851
1852 /*
1853 * main() - Ext4 online defrag.
1854 *
1855 * @argc: the number of parameter.
1856 * @argv[]: the pointer array of parameter.
1857 */
1858 int main(int argc, char *argv[])
1859 {
1860 int opt;
1861 int i, j;
1862 int flags = FTW_PHYS | FTW_MOUNT;
1863 int arg_type = -1;
1864 int success_flag = 0;
1865 char dir_name[PATH_MAX + 1];
1866 struct stat64 buf;
1867 struct ext4_super_block sb;
1868
1869 /* Parse arguments */
1870 if (argc == 1)
1871 goto out;
1872
1873 while ((opt = getopt(argc, argv, "vc")) != EOF) {
1874 switch (opt) {
1875 case 'v':
1876 mode_flag |= DETAIL;
1877 break;
1878 case 'c':
1879 mode_flag |= STATISTIC;
1880 break;
1881 default:
1882 goto out;
1883 }
1884 }
1885
1886 if (argc == optind)
1887 goto out;
1888
1889 current_uid = getuid();
1890
1891 /* Main process */
1892 for (i = optind; i < argc; i++) {
1893 succeed_cnt = 0;
1894 regular_count = 0;
1895 total_count = 0;
1896 frag_files_before_defrag = 0;
1897 frag_files_after_defrag = 0;
1898 extents_before_defrag = 0;
1899 extents_after_defrag = 0;
1900 defraged_file_count = 0;
1901 files_block_count = 0;
1902 blocks_per_group = 0;
1903 feature_incompat = 0;
1904 log_groups_per_flex = 0;
1905
1906 memset(dir_name, 0, PATH_MAX + 1);
1907 memset(lost_found_dir, 0, PATH_MAX + 1);
1908 memset(frag_rank, 0,
1909 sizeof(struct frag_statistic_ino) * SHOW_FRAG_FILES);
1910
1911 if ((mode_flag & STATISTIC) && i > optind)
1912 printf("\n");
1913
1914 #if BYTE_ORDER != BIG_ENDIAN && BYTE_ORDER != LITTLE_ENDIAN
1915 PRINT_ERR_MSG("Endian's type is not big/little endian");
1916 PRINT_FILE_NAME(argv[i]);
1917 continue;
1918 #endif
1919
1920 if (lstat64(argv[i], &buf) < 0) {
1921 perror(NGMSG_FILE_INFO);
1922 PRINT_FILE_NAME(argv[i]);
1923 continue;
1924 }
1925
1926 if (S_ISBLK(buf.st_mode)) {
1927 /* Block device */
1928 if (get_mount_point(argv[i], dir_name, PATH_MAX) < 0)
1929 continue;
1930 if (lstat64(dir_name, &buf) < 0) {
1931 perror(NGMSG_FILE_INFO);
1932 PRINT_FILE_NAME(argv[i]);
1933 continue;
1934 }
1935 arg_type = DEVNAME;
1936 if (!(mode_flag & STATISTIC))
1937 printf("ext4 defragmentation for device(%s)\n",
1938 argv[i]);
1939 } else if (S_ISDIR(buf.st_mode)) {
1940 /* Directory */
1941 if (access(argv[i], R_OK) < 0) {
1942 perror(argv[i]);
1943 continue;
1944 }
1945 arg_type = DIRNAME;
1946 strncpy(dir_name, argv[i], strnlen(argv[i], PATH_MAX));
1947 } else if (S_ISREG(buf.st_mode)) {
1948 /* Regular file */
1949 arg_type = FILENAME;
1950 } else {
1951 /* Irregular file */
1952 PRINT_ERR_MSG(NGMSG_FILE_UNREG);
1953 PRINT_FILE_NAME(argv[i]);
1954 continue;
1955 }
1956
1957 /* Set blocksize */
1958 block_size = buf.st_blksize;
1959
1960 /* For device case,
1961 * filesystem type checked in get_mount_point()
1962 */
1963 if (arg_type == FILENAME || arg_type == DIRNAME) {
1964 if (is_ext4(argv[i]) < 0)
1965 continue;
1966 if (realpath(argv[i], dir_name) == NULL) {
1967 perror("Couldn't get full path");
1968 PRINT_FILE_NAME(argv[i]);
1969 continue;
1970 }
1971 }
1972
1973 if (current_uid == ROOT_UID) {
1974 /* Get super block info */
1975 memset(&sb, 0, sizeof(struct ext4_super_block));
1976 if (get_superblock_info(dir_name, &sb) < 0) {
1977 if (mode_flag & DETAIL) {
1978 perror("Can't get super block info");
1979 PRINT_FILE_NAME(argv[i]);
1980 }
1981 continue;
1982 }
1983
1984 blocks_per_group = ext2fs_swab32(sb.s_blocks_per_group);
1985 feature_incompat = ext2fs_swab32(sb.s_feature_incompat);
1986 log_groups_per_flex = sb.s_log_groups_per_flex;
1987 }
1988
1989 switch (arg_type) {
1990 case DIRNAME:
1991 if (!(mode_flag & STATISTIC))
1992 printf("ext4 defragmentation "
1993 "for directory(%s)\n", argv[i]);
1994
1995 int mount_dir_len = 0;
1996 mount_dir_len = strnlen(lost_found_dir, PATH_MAX);
1997
1998 strncat(lost_found_dir, "/lost+found",
1999 PATH_MAX - strnlen(lost_found_dir, PATH_MAX));
2000
2001 /* Not the case("e4defrag mount_piont_dir") */
2002 if (dir_name[mount_dir_len] != '\0') {
2003 /*
2004 * "e4defrag mount_piont_dir/lost+found"
2005 * or "e4defrag mount_piont_dir/lost+found/"
2006 */
2007 if (strncmp(lost_found_dir, dir_name,
2008 strnlen(lost_found_dir,
2009 PATH_MAX)) == 0 &&
2010 (dir_name[strnlen(lost_found_dir,
2011 PATH_MAX)] == '\0' ||
2012 dir_name[strnlen(lost_found_dir,
2013 PATH_MAX)] == '/')) {
2014 PRINT_ERR_MSG(NGMSG_LOST_FOUND);
2015 PRINT_FILE_NAME(argv[i]);
2016 continue;
2017 }
2018
2019 /* "e4defrag mount_piont_dir/else_dir" */
2020 memset(lost_found_dir, 0, PATH_MAX + 1);
2021 }
2022 case DEVNAME:
2023 if (arg_type == DEVNAME) {
2024 strncpy(lost_found_dir, dir_name,
2025 strnlen(dir_name, PATH_MAX));
2026 strncat(lost_found_dir, "/lost+found/",
2027 PATH_MAX - strnlen(lost_found_dir,
2028 PATH_MAX));
2029 }
2030
2031 nftw64(dir_name, calc_entry_counts, FTW_OPEN_FD, flags);
2032
2033 if (mode_flag & STATISTIC) {
2034 if (mode_flag & DETAIL)
2035 printf("%-40s%10s/%-10s%9s\n",
2036 "<File>", "now", "best", "ratio");
2037
2038 if (!(mode_flag & DETAIL) &&
2039 current_uid != ROOT_UID) {
2040 printf(" Done.\n");
2041 continue;
2042 }
2043
2044 nftw64(dir_name, file_statistic,
2045 FTW_OPEN_FD, flags);
2046
2047 if (succeed_cnt != 0 &&
2048 current_uid == ROOT_UID) {
2049 if (mode_flag & DETAIL)
2050 printf("\n");
2051 printf("%-40s%10s/%-10s%9s\n",
2052 "<Fragmented files>", "now",
2053 "best", "ratio");
2054 for (j = 0; j < SHOW_FRAG_FILES; j++) {
2055 if (strlen(frag_rank[j].
2056 msg_buffer) > 37) {
2057 printf("%d. %s\n%50d/"
2058 "%-10d%8.2f%%\n", j + 1,
2059 frag_rank[j].msg_buffer,
2060 frag_rank[j].now_count,
2061 frag_rank[j].best_count,
2062 frag_rank[j].ratio);
2063 } else if (strlen(frag_rank[j].
2064 msg_buffer) > 0) {
2065 printf("%d. %-37s%10d/"
2066 "%-10d%8.2f%%\n", j + 1,
2067 frag_rank[j].msg_buffer,
2068 frag_rank[j].now_count,
2069 frag_rank[j].best_count,
2070 frag_rank[j].ratio);
2071 } else
2072 break;
2073 }
2074 }
2075 break;
2076 }
2077 /* File tree walk */
2078 nftw64(dir_name, file_defrag, FTW_OPEN_FD, flags);
2079 printf("\n\tSuccess:\t\t\t[ %u/%u ]\n", succeed_cnt,
2080 total_count);
2081 printf("\tFailure:\t\t\t[ %u/%u ]\n",
2082 total_count - succeed_cnt, total_count);
2083 if (mode_flag & DETAIL) {
2084 printf("\tTotal extents:\t\t\t%4d->%d\n",
2085 extents_before_defrag,
2086 extents_after_defrag);
2087 printf("\tFragmented percentage:\t\t"
2088 "%3llu%%->%llu%%\n",
2089 !regular_count ? 0 :
2090 ((unsigned long long)
2091 frag_files_before_defrag * 100) /
2092 regular_count,
2093 !regular_count ? 0 :
2094 ((unsigned long long)
2095 frag_files_after_defrag * 100) /
2096 regular_count);
2097 }
2098 break;
2099 case FILENAME:
2100 total_count = 1;
2101 regular_count = 1;
2102 strncat(lost_found_dir, "/lost+found/",
2103 PATH_MAX - strnlen(lost_found_dir,
2104 PATH_MAX));
2105 if (strncmp(lost_found_dir, dir_name,
2106 strnlen(lost_found_dir,
2107 PATH_MAX)) == 0) {
2108 PRINT_ERR_MSG(NGMSG_LOST_FOUND);
2109 PRINT_FILE_NAME(argv[i]);
2110 continue;
2111 }
2112
2113 if (mode_flag & STATISTIC) {
2114 file_statistic(argv[i], &buf, FTW_F, NULL);
2115 break;
2116 } else
2117 printf("ext4 defragmentation for %s\n",
2118 argv[i]);
2119 /* Defrag single file process */
2120 file_defrag(argv[i], &buf, FTW_F, NULL);
2121 if (succeed_cnt != 0)
2122 printf(" Success:\t\t\t[1/1]\n");
2123 else
2124 printf(" Success:\t\t\t[0/1]\n");
2125
2126 break;
2127 }
2128
2129 if (succeed_cnt != 0)
2130 success_flag = 1;
2131 if (mode_flag & STATISTIC) {
2132 if (current_uid != ROOT_UID) {
2133 printf(" Done.\n");
2134 continue;
2135 }
2136
2137 if (!succeed_cnt) {
2138 if (mode_flag & DETAIL)
2139 printf("\n");
2140
2141 if (arg_type == DEVNAME)
2142 printf(" In this device(%s), "
2143 "none can be defragmented.\n", argv[i]);
2144 else if (arg_type == DIRNAME)
2145 printf(" In this directory(%s), "
2146 "none can be defragmented.\n", argv[i]);
2147 else
2148 printf(" This file(%s) "
2149 "can't be defragmented.\n", argv[i]);
2150 } else {
2151 float files_ratio = 0.0;
2152 float score = 0.0;
2153 files_ratio = (float)(extents_before_defrag -
2154 extents_after_defrag) *
2155 100 / files_block_count;
2156 score = CALC_SCORE(files_ratio);
2157 printf("\n Total/best extents\t\t\t\t%d/%d\n"
2158 " Fragmentation ratio\t\t\t\t%.2f%%\n"
2159 " Fragmentation score\t\t\t\t%.2f\n",
2160 extents_before_defrag,
2161 extents_after_defrag,
2162 files_ratio, score);
2163 printf(" [0-30 no problem:"
2164 " 31-55 a little bit fragmented:"
2165 " 55- needs defrag]\n");
2166
2167 if (arg_type == DEVNAME)
2168 printf(" This device(%s) ", argv[i]);
2169 else if (arg_type == DIRNAME)
2170 printf(" This directory(%s) ", argv[i]);
2171 else
2172 printf(" This file(%s) ", argv[i]);
2173
2174 if (score > BOUND_SCORE)
2175 printf("needs defragmentation.\n");
2176 else
2177 printf("does not need "
2178 "defragmentation.\n");
2179 }
2180 printf(" Done.\n");
2181 }
2182
2183 }
2184
2185 if (success_flag)
2186 return 0;
2187
2188 exit(1);
2189
2190 out:
2191 printf(MSG_USAGE);
2192 exit(1);
2193 }
2194