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