summaryrefslogtreecommitdiffstats
path: root/e2fsprogs-1.41.8-freefrag-defrag.patch
blob: 1c936775105277679a0950e5614e117490c69810 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
Index: e2fsprogs-1.41.8/misc/e4defrag.8.in
===================================================================
--- /dev/null
+++ e2fsprogs-1.41.8/misc/e4defrag.8.in
@@ -0,0 +1,76 @@
+.TH E4DEFRAG 8 "May 2009" "e4defrag version 2.0"
+.SH NAME
+e4defrag \- online defragmenter for ext4 filesystem
+.SH SYNOPSIS
+.B e4defrag
+[
+.B \-c
+]
+[
+.B \-v
+]
+.I target
+\&...
+.SH DESCRIPTION
+.B e4defrag
+reduces fragmentation of extent based file. The file targeted by
+.B e4defrag
+is created on ext4 filesystem made with "-O extent" option (see
+.BR mke2fs (8)).
+The targeted file gets more contiguous blocks and improves the file access
+speed.
+.PP
+.I target
+is a regular file, a directory, or a device that is mounted as ext4 filesystem.
+If
+.I target
+is a directory,
+.B e4defrag
+reduces fragmentation of all files in it. If
+.I target
+is a device,
+.B e4defrag
+gets the mount point of it and reduces fragmentation of all files in this mount
+point.
+.SH OPTIONS
+.TP
+.B \-c
+Get the fragmentation count and calculate fragmentation score based on it
+before and after defrag. By seeing this score, we can determine whether we
+should execute
+.B e4defrag
+to
+.IR target .
+When used with
+.B \-v
+option, the fragmentation count before and after defrag is printed for each
+file.
+.IP
+If this option is specified,
+.I target
+is never defragmented.
+.TP
+.B \-v
+Print error messages and the fragmentation count before and after defrag for
+each file.
+.SH NOTES
+.B e4defrag
+does not support swap file, files in lost+found directory, and files allocated
+in indirect blocks. When
+.I target
+is a device or a mount point,
+.B e4defrag
+doesn't defragment files in mount point of other device.
+.PP
+Non-privileged users can execute
+.B e4defrag
+to their own file, but the score is not printed if
+.B \-c
+option is specified. Therefore, it is desirable to be executed by root user.
+.SH AUTHOR
+Written by Akira Fujita <a-fujita@rs.jp.nec.com> and Takashi Sato
+<t-sato@yk.jp.nec.com>.
+.SH SEE ALSO
+.BR mke2fs (8),
+.BR mount (8).
+
Index: e2fsprogs-1.41.8/misc/e4defrag.c
===================================================================
--- /dev/null
+++ e2fsprogs-1.41.8/misc/e4defrag.c
@@ -0,0 +1,2147 @@
+/*
+ * e4defrag.c - ext4 filesystem defragmenter
+ *
+ * Copyright (C) 2009 NEC Software Tohoku, Ltd.
+ *
+ * Author: Akira Fujita	<a-fujita@rs.jp.nec.com>
+ *         Takashi Sato	<t-sato@yk.jp.nec.com>
+ */
+
+#ifndef _LARGEFILE_SOURCE
+#define _LARGEFILE_SOURCE
+#endif
+
+#ifndef _LARGEFILE64_SOURCE
+#define _LARGEFILE64_SOURCE
+#endif
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <ctype.h>
+#include <dirent.h>
+#include <endian.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <ftw.h>
+#include <limits.h>
+#include <mntent.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <ext2fs/ext2_types.h>
+#include <ext2fs/ext2fs.h>
+#include <linux/fs.h>
+#include <ext2fs/fiemap.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/statfs.h>
+#include <sys/syscall.h>
+#include <sys/vfs.h>
+
+/* A relatively new ioctl interface ... */
+#ifndef EXT4_IOC_MOVE_EXT
+#define EXT4_IOC_MOVE_EXT      _IOWR('f', 15, struct move_extent)
+#endif
+
+/* Macro functions */
+#define PRINT_ERR_MSG(msg)	fprintf(stderr, "%s\n", (msg))
+#define IN_FTW_PRINT_ERR_MSG(msg)	\
+	fprintf(stderr, "\t%s\t\t[ NG ]\n", (msg))
+#define PRINT_FILE_NAME(file)	fprintf(stderr, " \"%s\"\n", (file))
+#define PRINT_ERR_MSG_WITH_ERRNO(msg)	\
+	fprintf(stderr, "\t%s:%s\t[ NG ]\n", (msg), strerror(errno))
+#define STATISTIC_ERR_MSG(msg)	\
+	fprintf(stderr, "\t%s\n", (msg))
+#define STATISTIC_ERR_MSG_WITH_ERRNO(msg)	\
+	fprintf(stderr, "\t%s:%s\n", (msg), strerror(errno))
+#define min(x, y) (((x) > (y)) ? (y) : (x))
+#define SECTOR_TO_BLOCK(sectors, blocksize) \
+	((sectors) / ((blocksize) >> 9))
+#define CALC_SCORE(ratio) \
+	((ratio) > 10 ? (80 + 20 * (ratio) / 100) : (8 * (ratio)))
+/* Wrap up the free function */
+#define FREE(tmp)				\
+	do {					\
+		if ((tmp) != NULL)		\
+			free(tmp);		\
+	} while (0)				\
+/* Insert list2 after list1 */
+#define insert(list1, list2)			\
+	do {					\
+		list2->next = list1->next;	\
+		list1->next->prev = list2;	\
+		list2->prev = list1;		\
+		list1->next = list2;		\
+	} while (0)
+
+/* To delete unused warning */
+#ifdef __GNUC__
+#define EXT2FS_ATTR(x) __attribute__(x)
+#else
+#define EXT2FS_ATTR(x)
+#endif
+
+/* The mode of defrag */
+#define DETAIL			0x01
+#define STATISTIC		0x02
+
+#define DEVNAME			0
+#define DIRNAME			1
+#define FILENAME		2
+
+#define FTW_OPEN_FD		2000
+
+#define FS_EXT4			"ext4"
+#define ROOT_UID		0
+
+#define BOUND_SCORE		55
+#define SHOW_FRAG_FILES	5
+
+/* Magic number for ext4 */
+#define EXT4_SUPER_MAGIC	0xEF53
+
+/* Definition of flex_bg */
+#define EXT4_FEATURE_INCOMPAT_FLEX_BG		0x0200
+
+/* The following macro is used for ioctl FS_IOC_FIEMAP
+ * EXTENT_MAX_COUNT:	the maximum number of extents for exchanging between
+ *			kernel-space and user-space per ioctl
+ */
+#define EXTENT_MAX_COUNT	512
+
+/* The following macros are error message */
+#define MSG_USAGE		\
+"Usage	: e4defrag [-v] file...| directory...| device...\n\
+	: e4defrag  -c  file...| directory...| device...\n"
+
+#define NGMSG_EXT4		"Filesystem is not ext4 filesystem"
+#define NGMSG_FILE_EXTENT	"Failed to get file extents"
+#define NGMSG_FILE_INFO		"Failed to get file information"
+#define NGMSG_FILE_OPEN		"Failed to open"
+#define NGMSG_FILE_UNREG	"File is not regular file"
+#define NGMSG_LOST_FOUND	"Can not process \"lost+found\""
+
+/* Data type for filesystem-wide blocks number */
+typedef unsigned long long ext4_fsblk_t;
+
+struct fiemap_extent_data {
+	__u64 len;			/* blocks count */
+	__u64 logical;		/* start logical block number */
+	ext4_fsblk_t physical;		/* start physical block number */
+};
+
+struct fiemap_extent_list {
+	struct fiemap_extent_list *prev;
+	struct fiemap_extent_list *next;
+	struct fiemap_extent_data data;	/* extent belong to file */
+};
+
+struct fiemap_extent_group {
+	struct fiemap_extent_group *prev;
+	struct fiemap_extent_group *next;
+	__u64 len;	/* length of this continuous region */
+	struct fiemap_extent_list *start;	/* start ext */
+	struct fiemap_extent_list *end;		/* end ext */
+};
+
+struct move_extent {
+	__s32 reserved;	/* original file descriptor */
+	__u32 donor_fd;	/* donor file descriptor */
+	__u64 orig_start;	/* logical start offset in block for orig */
+	__u64 donor_start;	/* logical start offset in block for donor */
+	__u64 len;	/* block length to be moved */
+	__u64 moved_len;	/* moved block length */
+};
+
+struct frag_statistic_ino {
+	int now_count;	/* the file's extents count of before defrag */
+	int best_count; /* the best file's extents count */
+	float ratio;	/* the ratio of fragmentation */
+	char msg_buffer[PATH_MAX + 1];	/* pathname of the file */
+};
+
+typedef __u16 __le16;
+typedef __u32 __le32;
+typedef __u64 __le64;
+
+/*
+ * Structure of the super block
+ */
+struct ext4_super_block {
+/*00*/	__le32	s_inodes_count;		/* Inodes count */
+	__le32	s_blocks_count_lo;	/* Blocks count */
+	__le32	s_r_blocks_count_lo;	/* Reserved blocks count */
+	__le32	s_free_blocks_count_lo;	/* Free blocks count */
+/*10*/	__le32	s_free_inodes_count;	/* Free inodes count */
+	__le32	s_first_data_block;	/* First Data Block */
+	__le32	s_log_block_size;	/* Block size */
+	__le32	s_obso_log_frag_size;	/* Obsoleted fragment size */
+/*20*/	__le32	s_blocks_per_group;	/* # Blocks per group */
+	__le32	s_obso_frags_per_group;	/* Obsoleted fragments per group */
+	__le32	s_inodes_per_group;	/* # Inodes per group */
+	__le32	s_mtime;		/* Mount time */
+/*30*/	__le32	s_wtime;		/* Write time */
+	__le16	s_mnt_count;		/* Mount count */
+	__le16	s_max_mnt_count;	/* Maximal mount count */
+	__le16	s_magic;		/* Magic signature */
+	__le16	s_state;		/* File system state */
+	__le16	s_errors;		/* Behaviour when detecting errors */
+	__le16	s_minor_rev_level;	/* minor revision level */
+/*40*/	__le32	s_lastcheck;		/* time of last check */
+	__le32	s_checkinterval;	/* max. time between checks */
+	__le32	s_creator_os;		/* OS */
+	__le32	s_rev_level;		/* Revision level */
+/*50*/	__le16	s_def_resuid;		/* Default uid for reserved blocks */
+	__le16	s_def_resgid;		/* Default gid for reserved blocks */
+	/*
+	 * These fields are for EXT4_DYNAMIC_REV superblocks only.
+	 *
+	 * Note: the difference between the compatible feature set and
+	 * the incompatible feature set is that if there is a bit set
+	 * in the incompatible feature set that the kernel doesn't
+	 * know about, it should refuse to mount the filesystem.
+	 *
+	 * e2fsck's requirements are more strict; if it doesn't know
+	 * about a feature in either the compatible or incompatible
+	 * feature set, it must abort and not try to meddle with
+	 * things it doesn't understand...
+	 */
+	__le32	s_first_ino;		/* First non-reserved inode */
+	__le16  s_inode_size;		/* size of inode structure */
+	__le16	s_block_group_nr;	/* block group # of this superblock */
+	__le32	s_feature_compat;	/* compatible feature set */
+/*60*/	__le32	s_feature_incompat;	/* incompatible feature set */
+	__le32	s_feature_ro_compat;	/* readonly-compatible feature set */
+/*68*/	__u8	s_uuid[16];		/* 128-bit uuid for volume */
+/*78*/	char	s_volume_name[16];	/* volume name */
+/*88*/	char	s_last_mounted[64];	/* directory where last mounted */
+/*C8*/	__le32	s_algorithm_usage_bitmap; /* For compression */
+	/*
+	 * Performance hints.  Directory preallocation should only
+	 * happen if the EXT4_FEATURE_COMPAT_DIR_PREALLOC flag is on.
+	 */
+	__u8	s_prealloc_blocks;	/* Nr of blocks to try to preallocate*/
+	__u8	s_prealloc_dir_blocks;	/* Nr to preallocate for dirs */
+	__le16	s_reserved_gdt_blocks;	/* Per group desc for online growth */
+	/*
+	 * Journaling support valid if EXT4_FEATURE_COMPAT_HAS_JOURNAL set.
+	 */
+/*D0*/	__u8	s_journal_uuid[16];	/* uuid of journal superblock */
+/*E0*/	__le32	s_journal_inum;		/* inode number of journal file */
+	__le32	s_journal_dev;		/* device number of journal file */
+	__le32	s_last_orphan;		/* start of list of inodes to delete */
+	__le32	s_hash_seed[4];		/* HTREE hash seed */
+	__u8	s_def_hash_version;	/* Default hash version to use */
+	__u8	s_reserved_char_pad;
+	__le16  s_desc_size;		/* size of group descriptor */
+/*100*/	__le32	s_default_mount_opts;
+	__le32	s_first_meta_bg;	/* First metablock block group */
+	__le32	s_mkfs_time;		/* When the filesystem was created */
+	__le32	s_jnl_blocks[17];	/* Backup of the journal inode */
+	/* 64bit support valid if EXT4_FEATURE_COMPAT_64BIT */
+/*150*/	__le32	s_blocks_count_hi;	/* Blocks count */
+	__le32	s_r_blocks_count_hi;	/* Reserved blocks count */
+	__le32	s_free_blocks_count_hi;	/* Free blocks count */
+	__le16	s_min_extra_isize;	/* All inodes have at least # bytes */
+	__le16	s_want_extra_isize; 	/* New inodes should reserve # bytes */
+	__le32	s_flags;		/* Miscellaneous flags */
+	__le16  s_raid_stride;		/* RAID stride */
+	__le16  s_mmp_interval;         /* # seconds to wait in MMP checking */
+	__le64  s_mmp_block;            /* Block for multi-mount protection */
+	__le32  s_raid_stripe_width;    /* blocks on all data disks (N*stride)*/
+	__u8	s_log_groups_per_flex;  /* FLEX_BG group size */
+	__u8	s_reserved_char_pad2;
+	__le16  s_reserved_pad;
+	__u32   s_reserved[162];        /* Padding to the end of the block */
+};
+
+char	lost_found_dir[PATH_MAX + 1];
+int	block_size;
+int	extents_before_defrag;
+int	extents_after_defrag;
+int	mode_flag;
+unsigned int	current_uid;
+unsigned int	defraged_file_count;
+unsigned int	frag_files_before_defrag;
+unsigned int	frag_files_after_defrag;
+unsigned int	regular_count;
+unsigned int	succeed_cnt;
+unsigned int	total_count;
+__u8 log_groups_per_flex;
+__le32 blocks_per_group;
+__le32 feature_incompat;
+ext4_fsblk_t	files_block_count;
+struct frag_statistic_ino	frag_rank[SHOW_FRAG_FILES];
+
+
+/* Local definitions of some syscalls glibc may not yet have */
+
+#ifndef HAVE_POSIX_FADVISE
+#warning Using locally defined posix_fadvise interface.
+
+#ifndef __NR_fadvise64_64
+#error Your kernel headers dont define __NR_fadvise64_64
+#endif
+
+/*
+ * fadvise() -		Give advice about file access.
+ *
+ * @fd:			defrag target file's descriptor.
+ * @offset:		file offset.
+ * @len:		area length.
+ * @advise:		process flag.
+ */
+static int posix_fadvise(int fd, loff_t offset, size_t len, int advise)
+{
+	return syscall(__NR_fadvise64_64, fd, offset, len, advise);
+}
+#endif /* ! HAVE_FADVISE64_64 */
+
+#ifndef HAVE_SYNC_FILE_RANGE
+#warning Using locally defined sync_file_range interface.
+
+#ifndef __NR_sync_file_range
+#error Your kernel headers dont define __NR_sync_file_range
+#endif
+
+/*
+ * sync_file_range() -	Sync file region.
+ *
+ * @fd:			defrag target file's descriptor.
+ * @offset:		file offset.
+ * @length:		area length.
+ * @flag:		process flag.
+ */
+int sync_file_range(int fd, loff_t offset, loff_t length, unsigned int flag)
+{
+	return syscall(__NR_sync_file_range, fd, offset, length, flag);
+}
+#endif /* ! HAVE_SYNC_FILE_RANGE */
+
+#ifndef HAVE_FALLOCATE
+#warning Using locally defined fallocate syscall interface.
+
+#ifndef __NR_fallocate
+#error Your kernel headers dont define __NR_fallocate
+#endif
+
+/*
+ * fallocate() -	Manipulate file space.
+ *
+ * @fd:			defrag target file's descriptor.
+ * @mode:		process flag.
+ * @offset:		file offset.
+ * @len:		file size.
+ */
+static int fallocate(int fd, int mode, loff_t offset, loff_t len)
+{
+	return syscall(__NR_fallocate, fd, mode, offset, len);
+}
+#endif /* ! HAVE_FALLOCATE */
+
+/*
+ * get_mount_point() -	Get device's mount point.
+ *
+ * @devname:		the device's name.
+ * @mount_point:	the mount point.
+ * @dir_path_len:	the length of directory.
+ */
+static int get_mount_point(const char *devname, char *mount_point,
+							int dir_path_len)
+{
+	/* Refer to /etc/mtab */
+	const char	*mtab = MOUNTED;
+	FILE	*fp = NULL;
+	struct mntent	*mnt = NULL;
+
+	fp = setmntent(mtab, "r");
+	if (fp == NULL) {
+		perror("Couldn't access /etc/mtab");
+		return -1;
+	}
+
+	while ((mnt = getmntent(fp)) != NULL) {
+		if (strcmp(devname, mnt->mnt_fsname) != 0)
+			continue;
+
+		endmntent(fp);
+		if (strcmp(mnt->mnt_type, FS_EXT4) == 0) {
+			strncpy(mount_point, mnt->mnt_dir,
+				dir_path_len);
+			return 0;
+		}
+		PRINT_ERR_MSG(NGMSG_EXT4);
+		return -1;
+	}
+	endmntent(fp);
+	PRINT_ERR_MSG("Filesystem is not mounted");
+	return -1;
+}
+
+/*
+ * is_ext4() -		Whether on an ext4 filesystem.
+ *
+ * @file:		the file's name.
+ */
+static int is_ext4(const char *file)
+{
+	int 	maxlen = 0;
+	int	len, ret;
+	FILE	*fp = NULL;
+	char	*mnt_type = NULL;
+	/* Refer to /etc/mtab */
+	const char	*mtab = MOUNTED;
+	char	file_path[PATH_MAX + 1];
+	struct mntent	*mnt = NULL;
+	struct statfs64	fsbuf;
+
+	/* Get full path */
+	if (realpath(file, file_path) == NULL) {
+		perror("Couldn't get full path");
+		PRINT_FILE_NAME(file);
+		return -1;
+	}
+
+	if (statfs64(file_path, &fsbuf) < 0) {
+		perror("Failed to get filesystem information");
+		PRINT_FILE_NAME(file);
+		return -1;
+	}
+
+	if (fsbuf.f_type != EXT4_SUPER_MAGIC) {
+		PRINT_ERR_MSG(NGMSG_EXT4);
+		return -1;
+	}
+
+	fp = setmntent(mtab, "r");
+	if (fp == NULL) {
+		perror("Couldn't access /etc/mtab");
+		return -1;
+	}
+
+	while ((mnt = getmntent(fp)) != NULL) {
+		len = strlen(mnt->mnt_dir);
+		ret = memcmp(file_path, mnt->mnt_dir, len);
+		if (ret != 0)
+			continue;
+
+		if (maxlen >= len)
+			continue;
+
+		maxlen = len;
+
+		mnt_type = realloc(mnt_type, strlen(mnt->mnt_type) + 1);
+		if (mnt_type == NULL) {
+			endmntent(fp);
+			return -1;
+		}
+		memset(mnt_type, 0, strlen(mnt->mnt_type) + 1);
+		strncpy(mnt_type, mnt->mnt_type, strlen(mnt->mnt_type));
+		strncpy(lost_found_dir, mnt->mnt_dir, PATH_MAX);
+	}
+
+	endmntent(fp);
+	if (strcmp(mnt_type, FS_EXT4) == 0) {
+		FREE(mnt_type);
+		return 0;
+	} else {
+		FREE(mnt_type);
+		PRINT_ERR_MSG(NGMSG_EXT4);
+		return -1;
+	}
+}
+
+/*
+ * calc_entry_counts() -	Calculate file counts.
+ *
+ * @file:		file name.
+ * @buf:		file info.
+ * @flag:		file type.
+ * @ftwbuf:		the pointer of a struct FTW.
+ */
+static int calc_entry_counts(const char *file EXT2FS_ATTR((unused)),
+		const struct stat64 *buf, int flag EXT2FS_ATTR((unused)),
+		struct FTW *ftwbuf EXT2FS_ATTR((unused)))
+{
+	if (S_ISREG(buf->st_mode))
+		regular_count++;
+
+	total_count++;
+
+	return 0;
+}
+
+/*
+ * page_in_core() -	Get information on whether pages are in core.
+ *
+ * @fd:			defrag target file's descriptor.
+ * @defrag_data:	data used for defrag.
+ * @vec:		page state array.
+ * @page_num:		page number.
+ */
+static int page_in_core(int fd, struct move_extent defrag_data,
+			unsigned char **vec, unsigned int *page_num)
+{
+	long	pagesize = sysconf(_SC_PAGESIZE);
+	void	*page = NULL;
+	loff_t	offset, end_offset, length;
+
+	if (vec == NULL || *vec != NULL)
+		return -1;
+
+	/* In mmap, offset should be a multiple of the page size */
+	offset = (loff_t)defrag_data.orig_start * block_size;
+	length = (loff_t)defrag_data.len * block_size;
+	end_offset = offset + length;
+	/* Round the offset down to the nearest multiple of pagesize */
+	offset = (offset / pagesize) * pagesize;
+	length = end_offset - offset;
+
+	page = mmap(NULL, length, PROT_READ, MAP_SHARED, fd, offset);
+	if (page == MAP_FAILED)
+		return -1;
+
+	*page_num = 0;
+	*page_num = (length + pagesize - 1) / pagesize;
+	*vec = (unsigned char *)calloc(*page_num, 1);
+	if (*vec == NULL)
+		return -1;
+
+	/* Get information on whether pages are in core */
+	if (mincore(page, (size_t)length, *vec) == -1 ||
+		munmap(page, length) == -1) {
+		FREE(*vec);
+		return -1;
+	}
+
+	return 0;
+}
+
+/*
+ * defrag_fadvise() -	Predeclare an access pattern for file data.
+ *
+ * @fd:			defrag target file's descriptor.
+ * @defrag_data:	data used for defrag.
+ * @vec:		page state array.
+ * @page_num:		page number.
+ */
+static int defrag_fadvise(int fd, struct move_extent defrag_data,
+		   unsigned char *vec, unsigned int page_num)
+{
+	int	flag = 1;
+	long	pagesize = sysconf(_SC_PAGESIZE);
+	int	fadvise_flag = POSIX_FADV_DONTNEED;
+	int	sync_flag = SYNC_FILE_RANGE_WAIT_BEFORE |
+			    SYNC_FILE_RANGE_WRITE |
+			    SYNC_FILE_RANGE_WAIT_AFTER;
+	unsigned int	i;
+	loff_t	offset;
+
+	offset = (loff_t)defrag_data.orig_start * block_size;
+	offset = (offset / pagesize) * pagesize;
+
+	/* Sync file for fadvise process */
+	if (sync_file_range(fd, offset,
+		(loff_t)pagesize * page_num, sync_flag) < 0)
+		return -1;
+
+	/* Try to release buffer cache which this process used,
+	 * then other process can use the released buffer
+	 */
+	for (i = 0; i < page_num; i++) {
+		if ((vec[i] & 0x1) == 0) {
+			offset += pagesize;
+			continue;
+		}
+		if (posix_fadvise(fd, offset, pagesize, fadvise_flag) < 0) {
+			if ((mode_flag & DETAIL) && flag) {
+				perror("\tFailed to fadvise");
+				flag = 0;
+			}
+		}
+		offset += pagesize;
+	}
+
+	return 0;
+}
+
+/*
+ * check_free_size() -	Check if there's enough disk space.
+ *
+ * @fd:			defrag target file's descriptor.
+ * @file:		file name.
+ * @buf:		the pointer of the struct stat64.
+ */
+static int check_free_size(int fd, const char *file, const struct stat64 *buf)
+{
+	ext4_fsblk_t	blk_count;
+	ext4_fsblk_t	free_blk_count;
+	struct statfs64	fsbuf;
+
+	if (fstatfs64(fd, &fsbuf) < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			PRINT_ERR_MSG_WITH_ERRNO(
+				"Failed to get filesystem information");
+		}
+		return -1;
+	}
+
+	/* Target file size measured by filesystem IO blocksize */
+	blk_count = SECTOR_TO_BLOCK(buf->st_blocks, fsbuf.f_bsize);
+
+	/* Compute free space for root and normal user separately */
+	if (current_uid == ROOT_UID)
+		free_blk_count = fsbuf.f_bfree;
+	else
+		free_blk_count = fsbuf.f_bavail;
+
+	if (free_blk_count >= blk_count)
+		return 0;
+
+	return -ENOSPC;
+}
+
+/*
+ * file_frag_count() -	Get file fragment count.
+ *
+ * @fd:			defrag target file's descriptor.
+ */
+static int file_frag_count(int fd)
+{
+	int	ret;
+	struct fiemap	fiemap_buf;
+
+	/* When fm_extent_count is 0,
+	 * ioctl just get file fragment count.
+	 */
+	memset(&fiemap_buf, 0, sizeof(struct fiemap));
+	fiemap_buf.fm_start = 0;
+	fiemap_buf.fm_length = FIEMAP_MAX_OFFSET;
+	fiemap_buf.fm_flags |= FIEMAP_FLAG_SYNC;
+
+	ret = ioctl(fd, FS_IOC_FIEMAP, &fiemap_buf);
+	if (ret < 0)
+		return ret;
+
+	return fiemap_buf.fm_mapped_extents;
+}
+
+/*
+ * file_check() -	Check file's attributes.
+ *
+ * @fd:			defrag target file's descriptor.
+ * @buf:		a pointer of the struct stat64.
+ * @file:		the file's name.
+ * @extents:		the file's extents.
+ */
+static int file_check(int fd, const struct stat64 *buf, const char *file,
+		int extents)
+{
+	int	ret;
+	struct flock	lock;
+
+	/* Write-lock check is more reliable */
+	lock.l_type = F_WRLCK;
+	lock.l_start = 0;
+	lock.l_whence = SEEK_SET;
+	lock.l_len = 0;
+
+	/* Free space */
+	ret = check_free_size(fd, file, buf);
+	if (ret < 0) {
+		if ((mode_flag & DETAIL) && ret == -ENOSPC) {
+			printf("\033[79;0H\033[K[%u/%u] \"%s\"\t\t"
+				"  extents: %d -> %d\n", defraged_file_count,
+				total_count, file, extents, extents);
+			IN_FTW_PRINT_ERR_MSG(
+			"Defrag size is larger than filesystem's free space");
+		}
+		return -1;
+	}
+
+	/* Access authority */
+	if (current_uid != ROOT_UID &&
+		buf->st_uid != current_uid) {
+		if (mode_flag & DETAIL) {
+			printf("\033[79;0H\033[K[%u/%u] \"%s\"\t\t"
+				"  extents: %d -> %d\n", defraged_file_count,
+				total_count, file, extents, extents);
+			IN_FTW_PRINT_ERR_MSG(
+				"File is not current user's file"
+				" or current user is not root");
+		}
+		return -1;
+	}
+
+	/* Lock status */
+	if (fcntl(fd, F_GETLK, &lock) < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			PRINT_ERR_MSG_WITH_ERRNO(
+				"Failed to get lock information");
+		}
+		return -1;
+	} else if (lock.l_type != F_UNLCK) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			IN_FTW_PRINT_ERR_MSG("File has been locked");
+		}
+		return -1;
+	}
+
+	return 0;
+}
+
+/*
+ * insert_extent_by_logical() -	Sequentially insert extent by logical.
+ *
+ * @ext_list_head:	the head of logical extent list.
+ * @ext:		the extent element which will be inserted.
+ */
+static int insert_extent_by_logical(struct fiemap_extent_list **ext_list_head,
+			struct fiemap_extent_list *ext)
+{
+	struct fiemap_extent_list	*ext_list_tmp = *ext_list_head;
+
+	if (ext == NULL)
+		goto out;
+
+	/* First element */
+	if (*ext_list_head == NULL) {
+		(*ext_list_head) = ext;
+		(*ext_list_head)->prev = *ext_list_head;
+		(*ext_list_head)->next = *ext_list_head;
+		return 0;
+	}
+
+	if (ext->data.logical <= ext_list_tmp->data.logical) {
+		/* Insert before head */
+		if (ext_list_tmp->data.logical <
+			ext->data.logical + ext->data.len)
+			/* Overlap */
+			goto out;
+		/* Adjust head */
+		*ext_list_head = ext;
+	} else {
+		/* Insert into the middle or last of the list */
+		do {
+			if (ext->data.logical < ext_list_tmp->data.logical)
+				break;
+			ext_list_tmp = ext_list_tmp->next;
+		} while (ext_list_tmp != (*ext_list_head));
+		if (ext->data.logical <
+		    ext_list_tmp->prev->data.logical +
+			ext_list_tmp->prev->data.len)
+			/* Overlap */
+			goto out;
+
+		if (ext_list_tmp != *ext_list_head &&
+		    ext_list_tmp->data.logical <
+		    ext->data.logical + ext->data.len)
+			/* Overlap */
+			goto out;
+	}
+	ext_list_tmp = ext_list_tmp->prev;
+	/* Insert "ext" after "ext_list_tmp" */
+	insert(ext_list_tmp, ext);
+	return 0;
+out:
+	errno = EINVAL;
+	return -1;
+}
+
+/*
+ * insert_extent_by_physical() -	Sequentially insert extent by physical.
+ *
+ * @ext_list_head:	the head of physical extent list.
+ * @ext:		the extent element which will be inserted.
+ */
+static int insert_extent_by_physical(struct fiemap_extent_list **ext_list_head,
+			struct fiemap_extent_list *ext)
+{
+	struct fiemap_extent_list	*ext_list_tmp = *ext_list_head;
+
+	if (ext == NULL)
+		goto out;
+
+	/* First element */
+	if (*ext_list_head == NULL) {
+		(*ext_list_head) = ext;
+		(*ext_list_head)->prev = *ext_list_head;
+		(*ext_list_head)->next = *ext_list_head;
+		return 0;
+	}
+
+	if (ext->data.physical <= ext_list_tmp->data.physical) {
+		/* Insert before head */
+		if (ext_list_tmp->data.physical <
+					ext->data.physical + ext->data.len)
+			/* Overlap */
+			goto out;
+		/* Adjust head */
+		*ext_list_head = ext;
+	} else {
+		/* Insert into the middle or last of the list */
+		do {
+			if (ext->data.physical < ext_list_tmp->data.physical)
+				break;
+			ext_list_tmp = ext_list_tmp->next;
+		} while (ext_list_tmp != (*ext_list_head));
+		if (ext->data.physical <
+		    ext_list_tmp->prev->data.physical +
+				ext_list_tmp->prev->data.len)
+			/* Overlap */
+			goto out;
+
+		if (ext_list_tmp != *ext_list_head &&
+		    ext_list_tmp->data.physical <
+				ext->data.physical + ext->data.len)
+			/* Overlap */
+			goto out;
+	}
+	ext_list_tmp = ext_list_tmp->prev;
+	/* Insert "ext" after "ext_list_tmp" */
+	insert(ext_list_tmp, ext);
+	return 0;
+out:
+	errno = EINVAL;
+	return -1;
+}
+
+/*
+ * insert_exts_group() -	Insert a exts_group.
+ *
+ * @ext_group_head:		the head of a exts_group list.
+ * @exts_group:			the exts_group element which will be inserted.
+ */
+static int insert_exts_group(struct fiemap_extent_group **ext_group_head,
+				struct fiemap_extent_group *exts_group)
+{
+	struct fiemap_extent_group	*ext_group_tmp = NULL;
+
+	if (exts_group == NULL) {
+		errno = EINVAL;
+		return -1;
+	}
+
+	/* Initialize list */
+	if (*ext_group_head == NULL) {
+		(*ext_group_head) = exts_group;
+		(*ext_group_head)->prev = *ext_group_head;
+		(*ext_group_head)->next = *ext_group_head;
+		return 0;
+	}
+
+	ext_group_tmp = (*ext_group_head)->prev;
+	insert(ext_group_tmp, exts_group);
+
+	return 0;
+}
+
+/*
+ * join_extents() -		Find continuous region(exts_group).
+ *
+ * @ext_list_head:		the head of the extent list.
+ * @ext_group_head:		the head of the target exts_group list.
+ */
+static int join_extents(struct fiemap_extent_list *ext_list_head,
+		struct fiemap_extent_group **ext_group_head)
+{
+	__u64	len = ext_list_head->data.len;
+	struct fiemap_extent_list *ext_list_start = ext_list_head;
+	struct fiemap_extent_list *ext_list_tmp = ext_list_head->next;
+
+	do {
+		struct fiemap_extent_group	*ext_group_tmp = NULL;
+
+		/* This extent and previous extent are not continuous,
+		 * so, all previous extents are treated as an extent group.
+		 */
+		if ((ext_list_tmp->prev->data.logical +
+			ext_list_tmp->prev->data.len)
+				!= ext_list_tmp->data.logical) {
+			ext_group_tmp =
+				malloc(sizeof(struct fiemap_extent_group));
+			if (ext_group_tmp == NULL)
+				return -1;
+
+			memset(ext_group_tmp, 0,
+				sizeof(struct fiemap_extent_group));
+			ext_group_tmp->len = len;
+			ext_group_tmp->start = ext_list_start;
+			ext_group_tmp->end = ext_list_tmp->prev;
+
+			if (insert_exts_group(ext_group_head,
+				ext_group_tmp) < 0) {
+				FREE(ext_group_tmp);
+				return -1;
+			}
+			ext_list_start = ext_list_tmp;
+			len = ext_list_tmp->data.len;
+			ext_list_tmp = ext_list_tmp->next;
+			continue;
+		}
+
+		/* This extent and previous extent are continuous,
+		 * so, they belong to the same extent group, and we check
+		 * if the next extent belongs to the same extent group.
+		 */
+		len += ext_list_tmp->data.len;
+		ext_list_tmp = ext_list_tmp->next;
+	} while (ext_list_tmp != ext_list_head->next);
+
+	return 0;
+}
+
+/*
+ * get_file_extents() -	Get file's extent list.
+ *
+ * @fd:			defrag target file's descriptor.
+ * @ext_list_head:	the head of the extent list.
+ */
+static int get_file_extents(int fd, struct fiemap_extent_list **ext_list_head)
+{
+	__u32	i;
+	int	ret;
+	int	ext_buf_size, fie_buf_size;
+	__u64	pos = 0;
+	struct fiemap	*fiemap_buf = NULL;
+	struct fiemap_extent	*ext_buf = NULL;
+	struct fiemap_extent_list	*ext_list = NULL;
+
+	/* Convert units, in bytes.
+	 * Be careful : now, physical block number in extent is 48bit,
+	 * and the maximum blocksize for ext4 is 4K(12bit),
+	 * so there is no overflow, but in future it may be changed.
+	 */
+
+	/* Alloc space for fiemap */
+	ext_buf_size = EXTENT_MAX_COUNT * sizeof(struct fiemap_extent);
+	fie_buf_size = sizeof(struct fiemap) + ext_buf_size;
+
+	fiemap_buf = malloc(fie_buf_size);
+	if (fiemap_buf == NULL)
+		return -1;
+
+	ext_buf = fiemap_buf->fm_extents;
+	memset(fiemap_buf, 0, fie_buf_size);
+	fiemap_buf->fm_length = FIEMAP_MAX_OFFSET;
+	fiemap_buf->fm_flags |= FIEMAP_FLAG_SYNC;
+	fiemap_buf->fm_extent_count = EXTENT_MAX_COUNT;
+
+	do {
+		fiemap_buf->fm_start = pos;
+		memset(ext_buf, 0, ext_buf_size);
+		ret = ioctl(fd, FS_IOC_FIEMAP, fiemap_buf);
+		if (ret < 0)
+			goto out;
+		for (i = 0; i < fiemap_buf->fm_mapped_extents; i++) {
+			ext_list = NULL;
+			ext_list = malloc(sizeof(struct fiemap_extent_list));
+			if (ext_list == NULL)
+				goto out;
+
+			ext_list->data.physical = ext_buf[i].fe_physical
+						/ block_size;
+			ext_list->data.logical = ext_buf[i].fe_logical
+						/ block_size;
+			ext_list->data.len = ext_buf[i].fe_length
+						/ block_size;
+
+			ret = insert_extent_by_physical(
+					ext_list_head, ext_list);
+			if (ret < 0) {
+				FREE(ext_list);
+				goto out;
+			}
+		}
+		/* Record file's logical offset this time */
+		pos = ext_buf[EXTENT_MAX_COUNT-1].fe_logical +
+			ext_buf[EXTENT_MAX_COUNT-1].fe_length;
+		/*
+		 * If fm_extents array has been filled and
+		 * there are extents left, continue to cycle.
+		 */
+	} while (fiemap_buf->fm_mapped_extents
+					== EXTENT_MAX_COUNT &&
+		!(ext_buf[EXTENT_MAX_COUNT-1].fe_flags
+					& FIEMAP_EXTENT_LAST));
+
+	FREE(fiemap_buf);
+	return 0;
+out:
+	FREE(fiemap_buf);
+	return -1;
+}
+
+/*
+ * get_logical_count() -	Get the file logical extents count.
+ *
+ * @logical_list_head:	the head of the logical extent list.
+ */
+static int get_logical_count(struct fiemap_extent_list *logical_list_head)
+{
+	int ret = 0;
+	struct fiemap_extent_list *ext_list_tmp  = logical_list_head;
+
+	do {
+		ret++;
+		ext_list_tmp = ext_list_tmp->next;
+	} while (ext_list_tmp != logical_list_head);
+
+	return ret;
+}
+
+/*
+ * get_physical_count() -	Get the file physical extents count.
+ *
+ * @physical_list_head:	the head of the physical extent list.
+ */
+static int get_physical_count(struct fiemap_extent_list *physical_list_head)
+{
+	int ret = 0;
+	struct fiemap_extent_list *ext_list_tmp = physical_list_head;
+
+	do {
+		if ((ext_list_tmp->data.physical + ext_list_tmp->data.len)
+				!= ext_list_tmp->next->data.physical) {
+			/* This extent and next extent are not continuous. */
+			ret++;
+		}
+
+		ext_list_tmp = ext_list_tmp->next;
+	} while (ext_list_tmp != physical_list_head);
+
+	return ret;
+}
+
+/*
+ * change_physical_to_logical() -	Change list from physical to logical.
+ *
+ * @physical_list_head:	the head of physical extent list.
+ * @logical_list_head:	the head of logical extent list.
+ */
+static int change_physical_to_logical(
+			struct fiemap_extent_list **physical_list_head,
+			struct fiemap_extent_list **logical_list_head)
+{
+	int ret;
+	struct fiemap_extent_list *ext_list_tmp = *physical_list_head;
+	struct fiemap_extent_list *ext_list_next = ext_list_tmp->next;
+
+	while (1) {
+		if (ext_list_tmp == ext_list_next) {
+			ret = insert_extent_by_logical(
+				logical_list_head, ext_list_tmp);
+			if (ret < 0)
+				return -1;
+
+			*physical_list_head = NULL;
+			break;
+		}
+
+		ext_list_tmp->prev->next = ext_list_tmp->next;
+		ext_list_tmp->next->prev = ext_list_tmp->prev;
+		*physical_list_head = ext_list_next;
+
+		ret = insert_extent_by_logical(
+			logical_list_head, ext_list_tmp);
+		if (ret < 0) {
+			FREE(ext_list_tmp);
+			return -1;
+		}
+		ext_list_tmp = ext_list_next;
+		ext_list_next = ext_list_next->next;
+	}
+
+	return 0;
+}
+
+/*
+ * free_ext() -		Free the extent list.
+ *
+ * @ext_list_head:	the extent list head of which will be free.
+ */
+static void free_ext(struct fiemap_extent_list *ext_list_head)
+{
+	struct fiemap_extent_list	*ext_list_tmp = NULL;
+
+	if (ext_list_head == NULL)
+		return;
+
+	while (ext_list_head->next != ext_list_head) {
+		ext_list_tmp = ext_list_head;
+		ext_list_head->prev->next = ext_list_head->next;
+		ext_list_head->next->prev = ext_list_head->prev;
+		ext_list_head = ext_list_head->next;
+		free(ext_list_tmp);
+	}
+	free(ext_list_head);
+}
+
+/*
+ * free_exts_group() -		Free the exts_group.
+ *
+ * @*ext_group_head:	the exts_group list head which will be free.
+ */
+static void free_exts_group(struct fiemap_extent_group *ext_group_head)
+{
+	struct fiemap_extent_group	*ext_group_tmp = NULL;
+
+	if (ext_group_head == NULL)
+		return;
+
+	while (ext_group_head->next != ext_group_head) {
+		ext_group_tmp = ext_group_head;
+		ext_group_head->prev->next = ext_group_head->next;
+		ext_group_head->next->prev = ext_group_head->prev;
+		ext_group_head = ext_group_head->next;
+		free(ext_group_tmp);
+	}
+	free(ext_group_head);
+}
+
+/*
+ * get_superblock_info() -	Get superblock info by the file name.
+ *
+ * @file:		the file's name.
+ * @sb:		the pointer of the struct ext4_super_block.
+ */
+static int get_superblock_info(const char *file, struct ext4_super_block *sb)
+{
+	/* Refer to /etc/mtab */
+	const char	*mtab = MOUNTED;
+	FILE	*fp = NULL;
+
+	int	fd = -1;
+	int	ret;
+	size_t maxlen = 0;
+	size_t len;
+	char	dev_name[PATH_MAX + 1];
+	struct mntent	*mnt = NULL;
+
+	fp = setmntent(mtab, "r");
+	if (fp == NULL)
+		return -1;
+
+	while ((mnt = getmntent(fp)) != NULL) {
+		len = strlen(mnt->mnt_dir);
+		ret = memcmp(file, mnt->mnt_dir, len);
+		if (ret != 0)
+			continue;
+
+		if (len < maxlen)
+			continue;
+
+		maxlen = len;
+
+		memset(dev_name, 0, PATH_MAX + 1);
+		strncpy(dev_name, mnt->mnt_fsname,
+				strnlen(mnt->mnt_fsname, PATH_MAX));
+	}
+
+	fd = open64(dev_name, O_RDONLY);
+	if (fd < 0) {
+		ret = -1;
+		goto out;
+	}
+
+	/* Set offset to read superblock */
+	ret = lseek64(fd, SUPERBLOCK_OFFSET, SEEK_SET);
+	if (ret < 0)
+		goto out;
+
+	ret = read(fd, sb, sizeof(struct ext4_super_block));
+	if (ret < 0)
+		goto out;
+
+out:
+	if (fd != -1)
+		close(fd);
+	endmntent(fp);
+	return ret;
+}
+
+/*
+ * get_best_count() -	Get the file best extents count.
+ *
+ * @block_count:		the file's physical block count.
+ */
+static int get_best_count(ext4_fsblk_t block_count)
+{
+	int ret;
+	unsigned int flex_bg_num;
+
+	/* Calcuate best extents count */
+	if (feature_incompat & EXT4_FEATURE_INCOMPAT_FLEX_BG) {
+		flex_bg_num = 1 << log_groups_per_flex;
+		ret = ((block_count - 1) /
+			((ext4_fsblk_t)blocks_per_group *
+				flex_bg_num)) + 1;
+	} else
+		ret = ((block_count - 1) / blocks_per_group) + 1;
+
+	return ret;
+}
+
+
+/*
+ * file_statistic() -	Get statistic info of the file's fragments.
+ *
+ * @file:		the file's name.
+ * @buf:		the pointer of the struct stat64.
+ * @flag:		file type.
+ * @ftwbuf:		the pointer of a struct FTW.
+ */
+static int file_statistic(const char *file, const struct stat64 *buf,
+			int flag EXT2FS_ATTR((unused)),
+			struct FTW *ftwbuf EXT2FS_ATTR((unused)))
+{
+	int	fd;
+	int	ret;
+	int	now_ext_count, best_ext_count = 0, physical_ext_count;
+	int	i, j;
+	float	ratio = 0.0;
+	ext4_fsblk_t	blk_count = 0;
+	char	msg_buffer[PATH_MAX + 24];
+	struct fiemap_extent_list *physical_list_head = NULL;
+	struct fiemap_extent_list *logical_list_head = NULL;
+
+	defraged_file_count++;
+
+	if (mode_flag & DETAIL) {
+		if (total_count == 1 && regular_count == 1)
+			printf("<File>\n");
+		else {
+			printf("[%u/%u]", defraged_file_count, total_count);
+			fflush(stdout);
+		}
+	}
+	if (lost_found_dir[0] != '\0' &&
+	    !memcmp(file, lost_found_dir, strnlen(lost_found_dir, PATH_MAX))) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			STATISTIC_ERR_MSG(NGMSG_LOST_FOUND);
+		}
+			return 0;
+	}
+
+	if (!S_ISREG(buf->st_mode)) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			STATISTIC_ERR_MSG(NGMSG_FILE_UNREG);
+		}
+		return 0;
+	}
+
+	/* Access authority */
+	if (current_uid != ROOT_UID &&
+		buf->st_uid != current_uid) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			STATISTIC_ERR_MSG(
+				"File is not current user's file"
+				" or current user is not root");
+		}
+		return 0;
+	}
+
+	/* Empty file */
+	if (buf->st_size == 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			STATISTIC_ERR_MSG("File size is 0");
+		}
+		return 0;
+	}
+
+	/* Has no blocks */
+	if (buf->st_blocks == 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			STATISTIC_ERR_MSG("File has no blocks");
+		}
+		return 0;
+	}
+
+	fd = open64(file, O_RDONLY);
+	if (fd < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			STATISTIC_ERR_MSG_WITH_ERRNO(NGMSG_FILE_OPEN);
+		}
+		return 0;
+	}
+
+	/* Get file's physical extents  */
+	ret = get_file_extents(fd, &physical_list_head);
+	if (ret < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			STATISTIC_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
+		}
+		goto out;
+	}
+
+	/* Get the count of file's continuous physical region */
+	physical_ext_count = get_physical_count(physical_list_head);
+
+	/* Change list from physical to logical */
+	ret = change_physical_to_logical(&physical_list_head,
+							&logical_list_head);
+	if (ret < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			STATISTIC_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
+		}
+		goto out;
+	}
+
+	/* Count file fragments before defrag */
+	now_ext_count = get_logical_count(logical_list_head);
+
+	if (current_uid == ROOT_UID) {
+		/* Calculate fragment ratio  */
+		blk_count =
+				SECTOR_TO_BLOCK(buf->st_blocks, block_size);
+
+		best_ext_count = get_best_count(blk_count);
+
+		ratio = (float)(physical_ext_count - best_ext_count) * 100 /
+							blk_count;
+
+		extents_before_defrag += now_ext_count;
+		extents_after_defrag += best_ext_count;
+		files_block_count += blk_count;
+	}
+
+	if (total_count == 1 && regular_count == 1) {
+		/* File only */
+		if (mode_flag & DETAIL) {
+			int count = 0;
+			struct fiemap_extent_list *ext_list_tmp =
+						logical_list_head;
+
+			/* Print extents info */
+			do {
+				count++;
+				printf("[ext %d]:\tstart %llu:\tlogical "
+						"%llu:\tlen %llu\n", count,
+						ext_list_tmp->data.physical,
+						ext_list_tmp->data.logical,
+						ext_list_tmp->data.len);
+				ext_list_tmp = ext_list_tmp->next;
+			} while (ext_list_tmp != logical_list_head);
+
+		} else {
+			printf("%-40s%10s/%-10s%9s\n",
+					"<File>", "now", "best", "ratio");
+			if (current_uid == ROOT_UID) {
+				if (strlen(file) > 40)
+					printf("%s\n%50d/%-10d%8.2f%%\n",
+						file, now_ext_count,
+						best_ext_count, ratio);
+				else
+					printf("%-40s%10d/%-10d%8.2f%%\n",
+						file, now_ext_count,
+						best_ext_count, ratio);
+			} else {
+				if (strlen(file) > 40)
+					printf("%s\n%50d/%-10s%7s\n",
+							file, now_ext_count,
+							"-", "-");
+				else
+					printf("%-40s%10d/%-10s%7s\n",
+							file, now_ext_count,
+							"-", "-");
+			}
+		}
+		succeed_cnt++;
+		goto out;
+	}
+
+	if (mode_flag & DETAIL) {
+		/* Print statistic info */
+		sprintf(msg_buffer, "[%u/%u]%s",
+				defraged_file_count, total_count, file);
+		if (current_uid == ROOT_UID) {
+			if (strlen(msg_buffer) > 40)
+				printf("\033[79;0H\033[K%s\n"
+						"%50d/%-10d%8.2f%%\n",
+						msg_buffer, now_ext_count,
+						best_ext_count, ratio);
+			else
+				printf("\033[79;0H\033[K%-40s"
+						"%10d/%-10d%8.2f%%\n",
+						msg_buffer, now_ext_count,
+						best_ext_count, ratio);
+		} else {
+			if (strlen(msg_buffer) > 40)
+				printf("\033[79;0H\033[K%s\n%50d/%-10s%7s\n",
+						msg_buffer, now_ext_count,
+							"-", "-");
+			else
+				printf("\033[79;0H\033[K%-40s%10d/%-10s%7s\n",
+						msg_buffer, now_ext_count,
+							"-", "-");
+		}
+	}
+
+	for (i = 0; i < SHOW_FRAG_FILES; i++) {
+		if (ratio >= frag_rank[i].ratio) {
+			for (j = SHOW_FRAG_FILES - 1; j > i; j--) {
+				memcpy(&frag_rank[j], &frag_rank[j - 1],
+					sizeof(struct frag_statistic_ino));
+			}
+			memset(&frag_rank[i], 0,
+					sizeof(struct frag_statistic_ino));
+			strncpy(frag_rank[i].msg_buffer, file,
+						strnlen(file, PATH_MAX));
+			frag_rank[i].now_count = now_ext_count;
+			frag_rank[i].best_count = best_ext_count;
+			frag_rank[i].ratio = ratio;
+			break;
+		}
+	}
+
+	succeed_cnt++;
+
+out:
+	close(fd);
+	free_ext(physical_list_head);
+	free_ext(logical_list_head);
+	return 0;
+}
+
+/*
+ * print_progress -	Print defrag progress
+ *
+ * @file:		file name.
+ * @start:		logical offset for defrag target file
+ * @file_size:		defrag target filesize
+ */
+static void print_progress(const char *file, loff_t start, loff_t file_size)
+{
+	int percent = (start * 100) / file_size;
+	printf("\033[79;0H\033[K[%u/%u]%s:\t%3d%%",
+		defraged_file_count, total_count, file, min(percent, 100));
+	fflush(stdout);
+
+	return;
+}
+
+/*
+ * call_defrag() -	Execute the defrag program.
+ *
+ * @fd:			target file descriptor.
+ * @donor_fd:		donor file descriptor.
+ * @file:			target file name.
+ * @buf:			pointer of the struct stat64.
+ * @ext_list_head:	head of the extent list.
+ */
+static int call_defrag(int fd, int donor_fd, const char *file,
+	const struct stat64 *buf, struct fiemap_extent_list *ext_list_head)
+{
+	loff_t	start = 0;
+	unsigned int	page_num;
+	unsigned char	*vec = NULL;
+	int	defraged_ret = 0;
+	int	ret;
+	struct move_extent	move_data;
+	struct fiemap_extent_list	*ext_list_tmp = NULL;
+
+	memset(&move_data, 0, sizeof(struct move_extent));
+	move_data.donor_fd = donor_fd;
+
+	/* Print defrag progress */
+	print_progress(file, start, buf->st_size);
+
+	ext_list_tmp = ext_list_head;
+	do {
+		move_data.orig_start = ext_list_tmp->data.logical;
+		/* Logical offset of orig and donor should be same */
+		move_data.donor_start = move_data.orig_start;
+		move_data.len = ext_list_tmp->data.len;
+		move_data.moved_len = 0;
+
+		ret = page_in_core(fd, move_data, &vec, &page_num);
+		if (ret < 0) {
+			if (mode_flag & DETAIL) {
+				printf("\n");
+				PRINT_ERR_MSG_WITH_ERRNO(
+						"Failed to get file map");
+			} else {
+				printf("\t[ NG ]\n");
+			}
+			return -1;
+		}
+
+		/* EXT4_IOC_MOVE_EXT */
+		defraged_ret =
+			ioctl(fd, EXT4_IOC_MOVE_EXT, &move_data);
+
+		/* Free pages */
+		ret = defrag_fadvise(fd, move_data, vec, page_num);
+		if (vec) {
+			free(vec);
+			vec = NULL;
+		}
+		if (ret < 0) {
+			if (mode_flag & DETAIL) {
+				printf("\n");
+				PRINT_ERR_MSG_WITH_ERRNO(
+					"Failed to free page");
+			} else {
+				printf("\t[ NG ]\n");
+			}
+			return -1;
+		}
+
+		if (defraged_ret < 0) {
+			if (mode_flag & DETAIL) {
+				printf("\n");
+				PRINT_ERR_MSG_WITH_ERRNO(
+						"Failed to defrag");
+			} else {
+				printf("\t[ NG ]\n");
+			}
+			return -1;
+		}
+		/* Adjust logical offset for next ioctl */
+		move_data.orig_start += move_data.moved_len;
+		move_data.donor_start = move_data.orig_start;
+
+		start = move_data.orig_start * buf->st_blksize;
+
+		/* Print defrag progress */
+		print_progress(file, start, buf->st_size);
+
+		/* End of file */
+		if (start >= buf->st_size)
+			break;
+
+		ext_list_tmp = ext_list_tmp->next;
+	} while (ext_list_tmp != ext_list_head);
+
+	return 0;
+}
+
+/*
+ * file_defrag() -		Check file attributes and call ioctl to defrag.
+ *
+ * @file:		the file's name.
+ * @buf:		the pointer of the struct stat64.
+ * @flag:		file type.
+ * @ftwbuf:		the pointer of a struct FTW.
+ */
+static int file_defrag(const char *file, const struct stat64 *buf,
+			int flag EXT2FS_ATTR((unused)),
+			struct FTW *ftwbuf EXT2FS_ATTR((unused)))
+{
+	int	fd;
+	int	donor_fd = -1;
+	int	ret;
+	int	best;
+	int	file_frags_start, file_frags_end;
+	int	orig_physical_cnt, donor_physical_cnt = 0;
+	char	tmp_inode_name[PATH_MAX + 8];
+	struct fiemap_extent_list	*orig_list_physical = NULL;
+	struct fiemap_extent_list	*orig_list_logical = NULL;
+	struct fiemap_extent_list	*donor_list_physical = NULL;
+	struct fiemap_extent_list	*donor_list_logical = NULL;
+	struct fiemap_extent_group	*orig_group_head = NULL;
+	struct fiemap_extent_group	*orig_group_tmp = NULL;
+
+	defraged_file_count++;
+
+	if (mode_flag & DETAIL) {
+		printf("[%u/%u]", defraged_file_count, total_count);
+		fflush(stdout);
+	}
+
+	if (lost_found_dir[0] != '\0' &&
+	    !memcmp(file, lost_found_dir, strnlen(lost_found_dir, PATH_MAX))) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			IN_FTW_PRINT_ERR_MSG(NGMSG_LOST_FOUND);
+		}
+		return 0;
+	}
+
+	if (!S_ISREG(buf->st_mode)) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			IN_FTW_PRINT_ERR_MSG(NGMSG_FILE_UNREG);
+		}
+		return 0;
+	}
+
+	/* Empty file */
+	if (buf->st_size == 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			IN_FTW_PRINT_ERR_MSG("File size is 0");
+		}
+		return 0;
+	}
+
+	/* Has no blocks */
+	if (buf->st_blocks == 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			STATISTIC_ERR_MSG("File has no blocks");
+		}
+		return 0;
+	}
+
+	fd = open64(file, O_RDONLY);
+	if (fd < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_OPEN);
+		}
+		return 0;
+	}
+
+	/* Get file's extents */
+	ret = get_file_extents(fd, &orig_list_physical);
+	if (ret < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
+		}
+		goto out;
+	}
+
+	/* Get the count of file's continuous physical region */
+	orig_physical_cnt = get_physical_count(orig_list_physical);
+
+	/* Change list from physical to logical */
+	ret = change_physical_to_logical(&orig_list_physical,
+							&orig_list_logical);
+	if (ret < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
+		}
+		goto out;
+	}
+
+	/* Count file fragments before defrag */
+	file_frags_start = get_logical_count(orig_list_logical);
+
+	if (file_check(fd, buf, file, file_frags_start) < 0)
+		goto out;
+
+	if (fsync(fd) < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			PRINT_ERR_MSG_WITH_ERRNO("Failed to sync(fsync)");
+		}
+		goto out;
+	}
+
+	if (current_uid == ROOT_UID)
+		best =
+		get_best_count(SECTOR_TO_BLOCK(buf->st_blocks, block_size));
+	else
+		best = 1;
+
+	if (file_frags_start <= best)
+		goto check_improvement;
+
+	/* Combine extents to group */
+	ret = join_extents(orig_list_logical, &orig_group_head);
+	if (ret < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
+		}
+		goto out;
+	}
+
+	/* Create donor inode */
+	memset(tmp_inode_name, 0, PATH_MAX + 8);
+	sprintf(tmp_inode_name, "%.*s.defrag",
+				(int)strnlen(file, PATH_MAX), file);
+	donor_fd = open64(tmp_inode_name, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR);
+	if (donor_fd < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			if (errno == EEXIST)
+				PRINT_ERR_MSG_WITH_ERRNO(
+				"File is being defraged by other program");
+			else
+				PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_OPEN);
+		}
+		goto out;
+	}
+
+	/* Unlink donor inode */
+	ret = unlink(tmp_inode_name);
+	if (ret < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			PRINT_ERR_MSG_WITH_ERRNO("Failed to unlink");
+		}
+		goto out;
+	}
+
+	/* Allocate space for donor inode */
+	orig_group_tmp = orig_group_head;
+	do {
+		ret = fallocate(donor_fd, 0,
+		  (loff_t)orig_group_tmp->start->data.logical * block_size,
+		  (loff_t)orig_group_tmp->len * block_size);
+		if (ret < 0) {
+			if (mode_flag & DETAIL) {
+				PRINT_FILE_NAME(file);
+				PRINT_ERR_MSG_WITH_ERRNO("Failed to fallocate");
+			}
+			goto out;
+		}
+
+		orig_group_tmp = orig_group_tmp->next;
+	} while (orig_group_tmp != orig_group_head);
+
+	/* Get donor inode's extents */
+	ret = get_file_extents(donor_fd, &donor_list_physical);
+	if (ret < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
+		}
+		goto out;
+	}
+
+	/* Calcuate donor inode's continuous physical region */
+	donor_physical_cnt = get_physical_count(donor_list_physical);
+
+	/* Change donor extent list from physical to logical */
+	ret = change_physical_to_logical(&donor_list_physical,
+							&donor_list_logical);
+	if (ret < 0) {
+		if (mode_flag & DETAIL) {
+			PRINT_FILE_NAME(file);
+			PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_EXTENT);
+		}
+		goto out;
+	}
+
+check_improvement:
+	if (mode_flag & DETAIL) {
+		if (file_frags_start != 1)
+			frag_files_before_defrag++;
+
+		extents_before_defrag += file_frags_start;
+	}
+
+	if (file_frags_start <= best ||
+			orig_physical_cnt <= donor_physical_cnt) {
+		printf("\033[79;0H\033[K[%u/%u]%s:\t%3d%%",
+			defraged_file_count, total_count, file, 100);
+		if (mode_flag & DETAIL)
+			printf("  extents: %d -> %d",
+				file_frags_start, file_frags_start);
+
+		printf("\t[ OK ]\n");
+		succeed_cnt++;
+
+		if (file_frags_start != 1)
+			frag_files_after_defrag++;
+
+		extents_after_defrag += file_frags_start;
+		goto out;
+	}
+
+	/* Defrag the file */
+	ret = call_defrag(fd, donor_fd, file, buf, donor_list_logical);
+
+	/* Count file fragments after defrag and print extents info */
+	if (mode_flag & DETAIL) {
+		file_frags_end = file_frag_count(fd);
+		if (file_frags_end < 0) {
+			printf("\n");
+			PRINT_ERR_MSG_WITH_ERRNO(NGMSG_FILE_INFO);
+			goto out;
+		}
+
+		if (file_frags_end != 1)
+			frag_files_after_defrag++;
+
+		extents_after_defrag += file_frags_end;
+
+		if (ret < 0)
+			goto out;
+
+		printf("  extents: %d -> %d",
+			file_frags_start, file_frags_end);
+		fflush(stdout);
+	}
+
+	if (ret < 0)
+		goto out;
+
+	printf("\t[ OK ]\n");
+	fflush(stdout);
+	succeed_cnt++;
+
+out:
+	close(fd);
+	if (donor_fd != -1)
+		close(donor_fd);
+	free_ext(orig_list_physical);
+	free_ext(orig_list_logical);
+	free_ext(donor_list_physical);
+	free_exts_group(orig_group_head);
+	return 0;
+}
+
+/*
+ * main() -		Ext4 online defrag.
+ *
+ * @argc:		the number of parameter.
+ * @argv[]:		the pointer array of parameter.
+ */
+int main(int argc, char *argv[])
+{
+	int	opt;
+	int	i, j;
+	int	flags = FTW_PHYS | FTW_MOUNT;
+	int	arg_type = -1;
+	int	success_flag = 0;
+	char	dir_name[PATH_MAX + 1];
+	struct stat64	buf;
+	struct ext4_super_block sb;
+
+	/* Parse arguments */
+	if (argc == 1)
+		goto out;
+
+	while ((opt = getopt(argc, argv, "vc")) != EOF) {
+		switch (opt) {
+		case 'v':
+			mode_flag |= DETAIL;
+			break;
+		case 'c':
+			mode_flag |= STATISTIC;
+			break;
+		default:
+			goto out;
+		}
+	}
+
+	if (argc == optind)
+		goto out;
+
+	current_uid = getuid();
+
+	/* Main process */
+	for (i = optind; i < argc; i++) {
+		succeed_cnt = 0;
+		regular_count = 0;
+		total_count = 0;
+		frag_files_before_defrag = 0;
+		frag_files_after_defrag = 0;
+		extents_before_defrag = 0;
+		extents_after_defrag = 0;
+		defraged_file_count = 0;
+		files_block_count = 0;
+		blocks_per_group = 0;
+		feature_incompat = 0;
+		log_groups_per_flex = 0;
+
+		memset(dir_name, 0, PATH_MAX + 1);
+		memset(lost_found_dir, 0, PATH_MAX + 1);
+		memset(frag_rank, 0,
+			sizeof(struct frag_statistic_ino) * SHOW_FRAG_FILES);
+
+		if ((mode_flag & STATISTIC) && i > optind)
+			printf("\n");
+
+#if BYTE_ORDER != BIG_ENDIAN && BYTE_ORDER != LITTLE_ENDIAN
+		PRINT_ERR_MSG("Endian's type is not big/little endian");
+		PRINT_FILE_NAME(argv[i]);
+		continue;
+#endif
+
+		if (lstat64(argv[i], &buf) < 0) {
+			perror(NGMSG_FILE_INFO);
+			PRINT_FILE_NAME(argv[i]);
+			continue;
+		}
+
+		if (S_ISBLK(buf.st_mode)) {
+			/* Block device */
+			if (get_mount_point(argv[i], dir_name, PATH_MAX) < 0)
+				continue;
+			if (lstat64(dir_name, &buf) < 0) {
+				perror(NGMSG_FILE_INFO);
+				PRINT_FILE_NAME(argv[i]);
+				continue;
+			}
+			arg_type = DEVNAME;
+			if (!(mode_flag & STATISTIC))
+				printf("ext4 defragmentation for device(%s)\n",
+					argv[i]);
+		} else if (S_ISDIR(buf.st_mode)) {
+			/* Directory */
+			if (access(argv[i], R_OK) < 0) {
+				perror(argv[i]);
+				continue;
+			}
+			arg_type = DIRNAME;
+			strncpy(dir_name, argv[i], strnlen(argv[i], PATH_MAX));
+		} else if (S_ISREG(buf.st_mode)) {
+			/* Regular file */
+			arg_type = FILENAME;
+		} else {
+			/* Irregular file */
+			PRINT_ERR_MSG(NGMSG_FILE_UNREG);
+			PRINT_FILE_NAME(argv[i]);
+			continue;
+		}
+
+		/* Set blocksize */
+		block_size = buf.st_blksize;
+
+		/* For device case,
+		 * filesystem type checked in get_mount_point()
+		 */
+		if (arg_type == FILENAME || arg_type == DIRNAME) {
+			if (is_ext4(argv[i]) < 0)
+				continue;
+			if (realpath(argv[i], dir_name) == NULL) {
+				perror("Couldn't get full path");
+				PRINT_FILE_NAME(argv[i]);
+				continue;
+			}
+		}
+
+		if (current_uid == ROOT_UID) {
+			/* Get super block info */
+			memset(&sb, 0, sizeof(struct ext4_super_block));
+			if (get_superblock_info(dir_name, &sb) < 0) {
+				if (mode_flag & DETAIL) {
+					perror("Can't get super block info");
+					PRINT_FILE_NAME(argv[i]);
+				}
+				continue;
+			}
+
+			blocks_per_group = ext2fs_swab32(sb.s_blocks_per_group);
+			feature_incompat = ext2fs_swab32(sb.s_feature_incompat);
+			log_groups_per_flex = sb.s_log_groups_per_flex;
+		}
+
+		switch (arg_type) {
+		case DIRNAME:
+			if (!(mode_flag & STATISTIC))
+				printf("ext4 defragmentation "
+					"for directory(%s)\n", argv[i]);
+
+			int mount_dir_len = 0;
+			mount_dir_len = strnlen(lost_found_dir, PATH_MAX);
+
+			strncat(lost_found_dir, "/lost+found",
+				PATH_MAX - strnlen(lost_found_dir, PATH_MAX));
+
+			/* Not the case("e4defrag  mount_piont_dir") */
+			if (dir_name[mount_dir_len] != '\0') {
+				/*
+				 * "e4defrag mount_piont_dir/lost+found"
+				 * or "e4defrag mount_piont_dir/lost+found/"
+				 */
+				if (strncmp(lost_found_dir, dir_name,
+					    strnlen(lost_found_dir,
+						    PATH_MAX)) == 0 &&
+				    (dir_name[strnlen(lost_found_dir,
+						      PATH_MAX)] == '\0' ||
+				     dir_name[strnlen(lost_found_dir,
+						      PATH_MAX)] == '/')) {
+					PRINT_ERR_MSG(NGMSG_LOST_FOUND);
+					PRINT_FILE_NAME(argv[i]);
+					continue;
+				}
+
+				/* "e4defrag mount_piont_dir/else_dir" */
+				memset(lost_found_dir, 0, PATH_MAX + 1);
+			}
+		case DEVNAME:
+			if (arg_type == DEVNAME) {
+				strncpy(lost_found_dir, dir_name,
+					strnlen(dir_name, PATH_MAX));
+				strncat(lost_found_dir, "/lost+found/",
+					PATH_MAX - strnlen(lost_found_dir,
+							   PATH_MAX));
+			}
+
+			nftw64(dir_name, calc_entry_counts, FTW_OPEN_FD, flags);
+
+			if (mode_flag & STATISTIC) {
+				if (mode_flag & DETAIL)
+					printf("%-40s%10s/%-10s%9s\n",
+					"<File>", "now", "best", "ratio");
+
+				if (!(mode_flag & DETAIL) &&
+						current_uid != ROOT_UID) {
+					printf(" Done.\n");
+					continue;
+				}
+
+				nftw64(dir_name, file_statistic,
+							FTW_OPEN_FD, flags);
+
+				if (succeed_cnt != 0 &&
+					current_uid == ROOT_UID) {
+					if (mode_flag & DETAIL)
+						printf("\n");
+					printf("%-40s%10s/%-10s%9s\n",
+						"<Fragmented files>", "now",
+						"best", "ratio");
+					for (j = 0; j < SHOW_FRAG_FILES; j++) {
+						if (strlen(frag_rank[j].
+							msg_buffer) > 37) {
+							printf("%d. %s\n%50d/"
+							"%-10d%8.2f%%\n", j + 1,
+							frag_rank[j].msg_buffer,
+							frag_rank[j].now_count,
+							frag_rank[j].best_count,
+							frag_rank[j].ratio);
+						} else if (strlen(frag_rank[j].
+							msg_buffer) > 0) {
+							printf("%d. %-37s%10d/"
+							"%-10d%8.2f%%\n", j + 1,
+							frag_rank[j].msg_buffer,
+							frag_rank[j].now_count,
+							frag_rank[j].best_count,
+							frag_rank[j].ratio);
+						} else
+							break;
+					}
+				}
+				break;
+			}
+			/* File tree walk */
+			nftw64(dir_name, file_defrag, FTW_OPEN_FD, flags);
+			printf("\n\tSuccess:\t\t\t[ %u/%u ]\n", succeed_cnt,
+				total_count);
+			printf("\tFailure:\t\t\t[ %u/%u ]\n",
+				total_count - succeed_cnt, total_count);
+			if (mode_flag & DETAIL) {
+				printf("\tTotal extents:\t\t\t%4d->%d\n",
+					extents_before_defrag,
+					extents_after_defrag);
+				printf("\tFragmented percentage:\t\t"
+					"%3llu%%->%llu%%\n",
+					!regular_count ? 0 :
+					((unsigned long long)
+					frag_files_before_defrag * 100) /
+					regular_count,
+					!regular_count ? 0 :
+					((unsigned long long)
+					frag_files_after_defrag * 100) /
+					regular_count);
+			}
+			break;
+		case FILENAME:
+			total_count = 1;
+			regular_count = 1;
+			strncat(lost_found_dir, "/lost+found/",
+				PATH_MAX - strnlen(lost_found_dir,
+						   PATH_MAX));
+			if (strncmp(lost_found_dir, dir_name,
+				    strnlen(lost_found_dir,
+					    PATH_MAX)) == 0) {
+				PRINT_ERR_MSG(NGMSG_LOST_FOUND);
+				PRINT_FILE_NAME(argv[i]);
+				continue;
+			}
+
+			if (mode_flag & STATISTIC) {
+				file_statistic(argv[i], &buf, FTW_F, NULL);
+				break;
+			} else
+				printf("ext4 defragmentation for %s\n",
+								 argv[i]);
+			/* Defrag single file process */
+			file_defrag(argv[i], &buf, FTW_F, NULL);
+			if (succeed_cnt != 0)
+				printf(" Success:\t\t\t[1/1]\n");
+			else
+				printf(" Success:\t\t\t[0/1]\n");
+
+			break;
+		}
+
+		if (succeed_cnt != 0)
+			success_flag = 1;
+		if (mode_flag & STATISTIC) {
+			if (current_uid != ROOT_UID) {
+				printf(" Done.\n");
+				continue;
+			}
+
+			if (!succeed_cnt) {
+				if (mode_flag & DETAIL)
+					printf("\n");
+
+				if (arg_type == DEVNAME)
+					printf(" In this device(%s), "
+					"none can be defragmented.\n", argv[i]);
+				else if (arg_type == DIRNAME)
+					printf(" In this directory(%s), "
+					"none can be defragmented.\n", argv[i]);
+				else
+					printf(" This file(%s) "
+					"can't be defragmented.\n", argv[i]);
+			} else {
+				float files_ratio = 0.0;
+				float score = 0.0;
+				files_ratio = (float)(extents_before_defrag -
+						extents_after_defrag) *
+						100 / files_block_count;
+				score = CALC_SCORE(files_ratio);
+				printf("\n Total/best extents\t\t\t\t%d/%d\n"
+					" Fragmentation ratio\t\t\t\t%.2f%%\n"
+					" Fragmentation score\t\t\t\t%.2f\n",
+						extents_before_defrag,
+						extents_after_defrag,
+						files_ratio, score);
+				printf(" [0-30 no problem:"
+					" 31-55 a little bit fragmented:"
+					" 55- needs defrag]\n");
+
+				if (arg_type == DEVNAME)
+					printf(" This device(%s) ", argv[i]);
+				else if (arg_type == DIRNAME)
+					printf(" This directory(%s) ", argv[i]);
+				else
+					printf(" This file(%s) ", argv[i]);
+
+				if (score > BOUND_SCORE)
+					printf("needs defragmentation.\n");
+				else
+					printf("does not need "
+							"defragmentation.\n");
+			}
+			printf(" Done.\n");
+		}
+
+	}
+
+	if (success_flag)
+		return 0;
+
+	exit(1);
+
+out:
+	printf(MSG_USAGE);
+	exit(1);
+}
+
Index: e2fsprogs-1.41.8/misc/Makefile.in
===================================================================
--- e2fsprogs-1.41.8.orig/misc/Makefile.in
+++ e2fsprogs-1.41.8/misc/Makefile.in
@@ -25,10 +25,10 @@ INSTALL = @INSTALL@
 
 SPROGS=		mke2fs badblocks tune2fs dumpe2fs $(BLKID_PROG) logsave \
 			$(E2IMAGE_PROG) @FSCK_PROG@ e2undo
-USPROGS=	mklost+found filefrag $(UUIDD_PROG)
+USPROGS=	mklost+found filefrag e2freefrag $(UUIDD_PROG)
 SMANPAGES=	tune2fs.8 mklost+found.8 mke2fs.8 dumpe2fs.8 badblocks.8 \
 			e2label.8 $(FINDFS_MAN) $(BLKID_MAN) $(E2IMAGE_MAN) \
-			logsave.8 filefrag.8 e2undo.8 $(UUIDD_MAN) @FSCK_MAN@
+			logsave.8 filefrag.8 e2freefrag.8 e2undo.8 $(UUIDD_MAN) @FSCK_MAN@
 FMANPAGES=	mke2fs.conf.5
 
 UPROGS=		chattr lsattr @UUID_CMT@ uuidgen
@@ -50,6 +50,8 @@ FSCK_OBJS=	fsck.o base_device.o ismounte
 BLKID_OBJS=	blkid.o
 FILEFRAG_OBJS=	filefrag.o
 E2UNDO_OBJS=  e2undo.o
+E4DEFRAG_OBJS=  e4defrag.o
+E2FREEFRAG_OBJS= e2freefrag.o
 
 PROFILED_TUNE2FS_OBJS=	profiled/tune2fs.o profiled/util.o
 PROFILED_MKLPF_OBJS=	profiled/mklost+found.o
@@ -67,7 +69,7 @@ PROFILED_FSCK_OBJS=	profiled/fsck.o prof
 PROFILED_BLKID_OBJS=	profiled/blkid.o
 PROFILED_FILEFRAG_OBJS=	profiled/filefrag.o
 PROFILED_E2UNDO_OBJS=	profiled/e2undo.o
-
+PROFILED_E4DEFRAG_OBJS= profiled/e4defrag.o
 
 XTRA_CFLAGS=	-I$(srcdir)/../e2fsck -I.
 
@@ -77,7 +79,7 @@ SRCS=	$(srcdir)/tune2fs.c $(srcdir)/mklo
 		$(srcdir)/uuidgen.c $(srcdir)/blkid.c $(srcdir)/logsave.c \
 		$(srcdir)/filefrag.c $(srcdir)/base_device.c \
 		$(srcdir)/ismounted.c $(srcdir)/../e2fsck/profile.c \
-		$(srcdir)/e2undo.c
+		$(srcdir)/e2undo.c $(srcdir)/e2freefrag.c
 
 LIBS= $(LIBEXT2FS) $(LIBCOM_ERR) 
 DEPLIBS= $(LIBEXT2FS) $(DEPLIBCOM_ERR)
@@ -98,12 +100,12 @@ COMPILE_ET=$(top_builddir)/lib/et/compil
 @PROFILE_CMT@	$(Q) $(CC) $(ALL_CFLAGS) -g -pg -o profiled/$*.o -c $<
 
 all:: profiled $(SPROGS) $(UPROGS) $(USPROGS) $(SMANPAGES) $(UMANPAGES) \
-	$(FMANPAGES) $(LPROGS)
+	$(FMANPAGES) $(LPROGS) e4defrag
 
 @PROFILE_CMT@all:: tune2fs.profiled blkid.profiled e2image.profiled \
 	e2undo.profiled mke2fs.profiled dumpe2fs.profiled fsck.profiled \
 	logsave.profiled filefrag.profiled uuidgen.profiled uuidd.profiled \
-	e2image.profiled
+	e2image.profiled e4defrag.profiled
 
 profiled:
 @PROFILE_CMT@	$(E) "	MKDIR $@"
@@ -190,6 +192,15 @@ e2undo.profiled: $(PROFILED_E2UNDO_OBJS)
 	$(Q) $(CC) $(ALL_LDFLAGS) -g -pg -o e2undo.profiled \
 		$(PROFILED_E2UNDO_OBJS) $(PROFILED_LIBS) $(LIBINTL)
 
+e4defrag: $(E4DEFRAG_OBJS)
+	$(E) "  LD $@"
+	$(Q) $(CC) $(ALL_LDFLAGS) -o e4defrag $(E4DEFRAG_OBJS)
+
+e4defrag.profiled: $(PROFILED_E4DEFRAG_OBJS)
+	$(E) "  LD $@"
+	$(Q) $(CC) $(ALL_LDFLAGS) -g -pg -o e4defrag.profiled \
+		$(PROFILED_E4DEFRAG_OBJS)
+
 base_device: base_device.c
 	$(E) "	LD $@"
 	$(Q) $(CC) $(ALL_CFLAGS) $(ALL_LDFLAGS) $(srcdir)/base_device.c \
@@ -287,6 +298,10 @@ logsave.profiled: profiled/logsave.o
 	$(E) "	LD $@"
 	$(Q) $(CC) $(ALL_LDFLAGS) -g -pg -o logsave.profiled profiled/logsave.o
 
+e2freefrag: $(E2FREEFRAG_OBJS)
+	@echo " LD $@"
+	@$(CC) $(ALL_LDFLAGS) -o e2freefrag $(E2FREEFRAG_OBJS) $(LIBS)
+
 filefrag: $(FILEFRAG_OBJS)
 	$(E) "	LD $@"
 	$(Q) $(CC) $(ALL_LDFLAGS) -o filefrag $(FILEFRAG_OBJS) 
@@ -333,6 +348,10 @@ e2image.8: $(DEP_SUBSTITUTE) $(srcdir)/e
 	$(E) "	SUBST $@"
 	$(Q) $(SUBSTITUTE_UPTIME) $(srcdir)/e2image.8.in e2image.8
 
+e4defrag.8: $(DEP_SUBSTITUTE) $(srcdir)/e4defrag.8.in
+	$(E) "  SUBST $@"
+	$(Q) $(SUBSTITUTE_UPTIME) $(srcdir)/e4defrag.8.in e4defrag.8
+
 dumpe2fs.8: $(DEP_SUBSTITUTE) $(srcdir)/dumpe2fs.8.in 
 	$(E) "	SUBST $@"
 	$(Q) $(SUBSTITUTE_UPTIME) $(srcdir)/dumpe2fs.8.in dumpe2fs.8
@@ -373,6 +392,10 @@ blkid.1: $(DEP_SUBSTITUTE) $(srcdir)/blk
 	$(E) "	SUBST $@"
 	$(Q) $(SUBSTITUTE_UPTIME) $(srcdir)/blkid.1.in blkid.1 
 
+e2freefrag.8: $(DEP_SUBSTITUTE) $(srcdir)/e2freefrag.8.in
+	@echo " SUBST $@"
+	@$(SUBSTITUTE_UPTIME) $(srcdir)/e2freefrag.8.in e2freefrag.8
+
 filefrag.8: $(DEP_SUBSTITUTE) $(srcdir)/filefrag.8.in
 	$(E) "	SUBST $@"
 	$(Q) $(SUBSTITUTE_UPTIME) $(srcdir)/filefrag.8.in filefrag.8
@@ -385,6 +408,10 @@ installdirs:
 		$(DESTDIR)$(man1dir) $(DESTDIR)$(man5dir) \
 		$(DESTDIR)$(libdir) $(DESTDIR)/$(root_sysconfdir)
 
+install-e4defrag: e4defrag e4defrag.8 installdirs
+	$(INSTALL_PROGRAM) e4defrag $(DESTDIR)$(bindir)/e4defrag
+	$(INSTALL_DATA) e4defrag.8 $(DESTDIR)$(man8dir)/e4defrag.8
+
 install: all $(SMANPAGES) $(UMANPAGES) installdirs
 	$(Q) for i in $(SPROGS); do \
 		echo "	INSTALL $(root_sbindir)/$$i"; \
@@ -536,13 +563,13 @@ uninstall:
 clean:
 	$(RM) -f $(SPROGS) $(USPROGS) $(UPROGS) $(UMANPAGES) $(SMANPAGES) \
 		$(FMANPAGES) \
-		base_device base_device.out mke2fs.static filefrag \
+		base_device base_device.out mke2fs.static filefrag e2freefrag \
 		e2initrd_helper partinfo prof_err.[ch] default_profile.c \
 		uuidd e2image tune2fs.static tst_ismounted fsck.profiled \
 		blkid.profiled tune2fs.profiled e2image.profiled \
 		e2undo.profiled mke2fs.profiled dumpe2fs.profiled \
 		logsave.profiled filefrag.profiled uuidgen.profiled \
-		uuidd.profiled e2image.profiled \
+		uuidd.profiled e2image.profiled e4defrag \
 		profiled/*.o \#* *.s *.o *.a *~ core gmon.out
 
 mostlyclean: clean
@@ -617,6 +644,9 @@ uuidgen.o: $(srcdir)/uuidgen.c $(top_src
 blkid.o: $(srcdir)/blkid.c $(top_srcdir)/lib/blkid/blkid.h \
  $(top_builddir)/lib/blkid/blkid_types.h
 logsave.o: $(srcdir)/logsave.c
+e2freefrag.o: $(srcdir)/e2freefrag.c e2freefrag.h \
+ $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_srcdir)/lib/ext2fs/ext2fs.h \
+ $(top_srcdir)/lib/ext2fs/bitops.h
 filefrag.o: $(srcdir)/filefrag.c
 base_device.o: $(srcdir)/base_device.c $(srcdir)/fsck.h
 ismounted.o: $(srcdir)/ismounted.c $(top_srcdir)/lib/et/com_err.h
Index: e2fsprogs-1.41.8/misc/e2freefrag.8.in
===================================================================
--- /dev/null
+++ e2fsprogs-1.41.8/misc/e2freefrag.8.in
@@ -0,0 +1,99 @@
+.\" -*- nroff -*-
+.TH E2FREEFRAG 8
+.SH NAME
+e2freefrag \- report free space fragmentation information
+.SH SYNOPSIS
+.B e2freefrag
+[
+.B \-c chunk_kb
+]
+[
+.B \-h
+]
+.B filesys
+
+.SH DESCRIPTION
+.B e2freefrag
+is used to report free space fragmentation on ext2/3/4 file systems.
+.I filesys
+is the filesystem device name (e.g.
+.IR /dev/hdc1 ", " /dev/md0 ).
+The
+.B e2freefrag
+program will scan the block bitmap information to check how many free blocks
+are present as contiguous and aligned free space. The percentage of contiguous
+free blocks of size and of alignment
+.IR chunk_kb
+is reported.  It also displays the minimum/maximum/average free chunk size in
+the filesystem, along with a histogram of all free chunks.  This information
+can be used to gauge the level of free space fragmentation in the filesystem.
+.SH OPTIONS
+.TP
+.BI \-c " chunk_kb"
+Desired size of chunk. It is specified in units of kilobytes (KB). If no
+.I chunk_kb
+is specified on the command line, then the default value is 1024KB.
+.TP
+.BI \-h
+Print the usage of the program.
+.SH EXAMPLE
+# e2freefrag /dev/vgroot/lvhome
+.br
+Device: /dev/vgroot/lvhome
+.br
+Blocksize: 4096 bytes
+.br
+Total blocks: 1504085
+.br
+Free blocks: 292995 (19.5%)
+.br
+Chunk size: 1048576 bytes (256 blocks)
+.br
+Total chunks: 5876
+.br
+Free chunks: 463 (7.9%)
+.br
+
+Min free chunk: 4 KB
+.br
+Max free chunk: 24008 KB
+.br
+Avg free chunk: 252 KB
+.br
+
+HISTOGRAM OF FREE CHUNK SIZES:
+.br
+Chunk Size Range :   Free chunks   Free Blocks  Percent
+.br
+    4K...    8K- :           704           704     0.2%
+.br
+    8K...   16K- :           810          1979     0.7%
+.br
+   16K...   32K- :           843          4467     1.5%
+.br
+   32K...   64K- :           579          6263     2.1%
+.br
+   64K...  128K- :           493         11067     3.8%
+.br
+  128K...  256K- :           394         18097     6.2%
+.br
+  256K...  512K- :           281         25477     8.7%
+.br
+  512K... 1024K- :           253         44914    15.3%
+.br
+    1M...    2M- :           143         51897    17.7%
+.br
+    2M...    4M- :            73         50683    17.3%
+.br
+    4M...    8M- :            37         52417    17.9%
+.br
+    8M...   16M- :             7         19028     6.5%
+.br
+   16M...   32M- :             1          6002     2.0%
+.SH AUTHOR
+This version of e2freefrag was written by Rupesh Thakare, and modified by
+Andreas Dilger <adilger@sun.com>, and Kalpak Shah.
+.SH SEE ALSO
+.IR debugfs (8),
+.IR dumpe2fs (8),
+.IR e2fsck (8)
Index: e2fsprogs-1.41.8/misc/e2freefrag.c
===================================================================
--- /dev/null
+++ e2fsprogs-1.41.8/misc/e2freefrag.c
@@ -0,0 +1,284 @@
+/*
+ * e2freefrag - report filesystem free-space fragmentation
+ *
+ * Copyright (C) 2009 Sun Microsystems, Inc.
+ *
+ * Author: Rupesh Thakare <rupesh@sun.com>
+ *         Andreas Dilger <adilger@sun.com>
+ *
+ * %Begin-Header%
+ * This file may be redistributed under the terms of the GNU Public
+ * License version 2.
+ * %End-Header%
+ */
+#include <stdio.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+#ifdef HAVE_GETOPT_H
+#include <getopt.h>
+#else
+extern char *optarg;
+extern int optind;
+#endif
+
+#include "ext2fs/ext2_fs.h"
+#include "ext2fs/ext2fs.h"
+#include "e2freefrag.h"
+
+void usage(const char *prog)
+{
+	fprintf(stderr, "usage: %s [-c chunksize in kb] [-h] "
+		"device_name\n", prog);
+	exit(1);
+}
+
+static int ul_log2(unsigned long arg)
+{
+        int     l = 0;
+
+        arg >>= 1;
+        while (arg) {
+                l++;
+                arg >>= 1;
+        }
+        return l;
+}
+
+void init_chunk_info(ext2_filsys fs, struct chunk_info *info)
+{
+	int i;
+
+	info->chunkbits = ul_log2(info->chunkbytes);
+	info->blocksize_bits = ul_log2((unsigned long)fs->blocksize);
+	info->blks_in_chunk = info->chunkbytes >> info->blocksize_bits;
+
+	info->min = ~0UL;
+	info->max = info->avg = 0;
+	info->real_free_chunks = 0;
+
+	for (i = 0; i < MAX_HIST; i++) {
+		info->histogram.fc_chunks[i] = 0;
+		info->histogram.fc_blocks[i] = 0;
+	}
+}
+
+void scan_block_bitmap(ext2_filsys fs, struct chunk_info *info)
+{
+	unsigned long long blocks_count = fs->super->s_blocks_count;
+	unsigned long long chunks = (blocks_count + info->blks_in_chunk) >>
+				(info->chunkbits - info->blocksize_bits);
+	unsigned long long chunk_num;
+	unsigned long last_chunk_size = 0;
+	unsigned long long chunk_start_blk = 0;
+
+	for (chunk_num = 0; chunk_num < chunks; chunk_num++) {
+		unsigned long long blk, num_blks;
+		int chunk_free;
+
+		/* Last chunk may be smaller */
+		if (chunk_start_blk + info->blks_in_chunk > blocks_count)
+			num_blks = blocks_count - chunk_start_blk;
+		else
+			num_blks = info->blks_in_chunk;
+
+		chunk_free = 0;
+
+		/* Initialize starting block for first chunk correctly else
+		 * there is a segfault when blocksize = 1024 in which case
+		 * block_map->start = 1 */
+		for (blk = (chunk_num == 0 ? fs->super->s_first_data_block : 0);
+		     blk < num_blks; blk++, chunk_start_blk++) {
+			int used = ext2fs_fast_test_block_bitmap(fs->block_map,
+							       chunk_start_blk);
+			if (!used) {
+				last_chunk_size++;
+				chunk_free++;
+			}
+
+			if (used && last_chunk_size != 0) {
+				unsigned long index;
+
+				index = ul_log2(last_chunk_size) + 1;
+				info->histogram.fc_chunks[index]++;
+				info->histogram.fc_blocks[index] +=
+							last_chunk_size;
+
+				if (last_chunk_size > info->max)
+					info->max = last_chunk_size;
+				if (last_chunk_size < info->min)
+					info->min = last_chunk_size;
+				info->avg += last_chunk_size;
+
+				info->real_free_chunks++;
+				last_chunk_size = 0;
+			}
+		}
+
+		if (chunk_free == info->blks_in_chunk)
+			info->free_chunks++;
+	}
+}
+
+errcode_t get_chunk_info(ext2_filsys fs, struct chunk_info *info)
+{
+	unsigned long total_chunks;
+	char *unitp = "KMGTPEZY";
+	int units = 10;
+	unsigned long start = 0, end, cum;
+	int i, retval = 0;
+
+	scan_block_bitmap(fs, info);
+
+	printf("Total blocks: %u\nFree blocks: %u (%0.1f%%)\n",
+	       fs->super->s_blocks_count, fs->super->s_free_blocks_count,
+	       (double)fs->super->s_free_blocks_count * 100 /
+						fs->super->s_blocks_count);
+
+	printf("\nChunksize: %lu bytes (%u blocks)\n",
+	       info->chunkbytes, info->blks_in_chunk);
+	total_chunks = (fs->super->s_blocks_count + info->blks_in_chunk) >>
+				(info->chunkbits - info->blocksize_bits);
+	printf("Total chunks: %lu\nFree chunks: %lu (%0.1f%%)\n",
+	       total_chunks, info->free_chunks,
+	       (double)info->free_chunks * 100 / total_chunks);
+
+	/* Display chunk information in KB */
+	if (info->real_free_chunks) {
+		info->min = (info->min * fs->blocksize) >> 10;
+		info->max = (info->max * fs->blocksize) >> 10;
+		info->avg = (info->avg / info->real_free_chunks *
+			     fs->blocksize) >> 10;
+	} else {
+		info->min = 0;
+	}
+
+	printf("\nMin free chunk: %lu KB \nMax free chunk: %lu KB\n"
+	       "Avg free chunk: %lu KB\n", info->min, info->max, info->avg);
+
+	printf("\nHISTOGRAM OF FREE CHUNK SIZES:\n");
+	printf("%s :  %12s  %12s  %7s\n", "Chunk Size Range", "Free chunks",
+	       "Free Blocks", "Percent");
+	for (i = 0; i < MAX_HIST; i++) {
+		end = 1 << (i + info->blocksize_bits - units);
+		if (info->histogram.fc_chunks[i] != 0)
+			printf("%5lu%c...%5lu%c- :  %12lu  %12lu  %6.2f%%\n",
+			       start, *unitp, end, *unitp,
+			       info->histogram.fc_chunks[i],
+			       info->histogram.fc_blocks[i],
+			       (double)info->histogram.fc_blocks[i] * 100 /
+			       fs->super->s_free_blocks_count);
+		start = end;
+		if (start == 1<<10) {
+			start = 1;
+			units += 10;
+			unitp++;
+		}
+	}
+
+	return retval;
+}
+
+void close_device(char *device_name, ext2_filsys fs)
+{
+	int retval = ext2fs_close(fs);
+
+	if (retval)
+		com_err(device_name, retval, "while closing the filesystem.\n");
+}
+
+void collect_info(ext2_filsys fs, struct chunk_info *chunk_info)
+{
+	unsigned int retval = 0, i, free_blks;
+
+	printf("Device: %s\n", fs->device_name);
+	printf("Blocksize: %u bytes\n", fs->blocksize);
+
+	retval = ext2fs_read_block_bitmap(fs);
+	if (retval) {
+		com_err(fs->device_name, retval, "while reading block bitmap");
+		close_device(fs->device_name, fs);
+		exit(1);
+	}
+
+	init_chunk_info(fs, chunk_info);
+
+	retval = get_chunk_info(fs, chunk_info);
+	if (retval) {
+		com_err(fs->device_name, retval, "while collecting chunk info");
+                close_device(fs->device_name, fs);
+		exit(1);
+	}
+}
+
+void open_device(char *device_name, ext2_filsys *fs)
+{
+	int retval;
+	int flag = EXT2_FLAG_FORCE;
+
+	retval = ext2fs_open(device_name, flag, 0, 0, unix_io_manager, fs);
+	if (retval) {
+		com_err(device_name, retval, "while opening filesystem");
+		exit(1);
+	}
+}
+
+int main(int argc, char *argv[])
+{
+	struct chunk_info chunk_info = { .chunkbytes = DEFAULT_CHUNKSIZE };
+	errcode_t retval = 0;
+	ext2_filsys fs = NULL;
+	char *device_name;
+	char *progname;
+	char c, *end;
+
+	progname = argv[0];
+
+	while ((c = getopt(argc, argv, "c:h")) != EOF) {
+		switch (c) {
+		case 'c':
+			chunk_info.chunkbytes = strtoull(optarg, &end, 0);
+			if (*end != '\0') {
+				fprintf(stderr, "%s: bad chunk size '%s'\n",
+					progname, optarg);
+				usage(progname);
+			}
+			if (chunk_info.chunkbytes &
+			    (chunk_info.chunkbytes - 1)) {
+				fprintf(stderr, "%s: chunk size must be a "
+					"power of 2.", argv[0]);
+				usage(progname);
+			}
+			chunk_info.chunkbytes *= 1024;
+			break;
+		default:
+			fprintf(stderr, "%s: bad option '%c'\n",
+				progname, c);
+		case 'h':
+			usage(progname);
+			break;
+		}
+	}
+
+	if (optind == argc) {
+		fprintf(stderr, "%s: missing device name.\n", progname);
+		usage(progname);
+	}
+
+	device_name = argv[optind];
+
+	open_device(device_name, &fs);
+
+	if (chunk_info.chunkbytes < fs->blocksize) {
+		fprintf(stderr, "%s: chunksize must be greater than or equal "
+			"to filesystem blocksize.\n", progname);
+		exit(1);
+	}
+	collect_info(fs, &chunk_info);
+	close_device(device_name, fs);
+
+	return retval;
+}
Index: e2fsprogs-1.41.8/misc/e2freefrag.h
===================================================================
--- /dev/null
+++ e2fsprogs-1.41.8/misc/e2freefrag.h
@@ -0,0 +1,20 @@
+#include <sys/types.h>
+
+#define DEFAULT_CHUNKSIZE (1024*1024)
+
+#define MAX_HIST	32
+struct free_chunk_histogram {
+	unsigned long fc_chunks[MAX_HIST];
+	unsigned long fc_blocks[MAX_HIST];
+};
+
+struct chunk_info {
+	unsigned long chunkbytes;	/* chunk size in bytes */
+	int chunkbits;			/* chunk size in bits */
+	unsigned long free_chunks;	/* total free chunks of given size */
+	unsigned long real_free_chunks; /* free chunks of any size */
+	int blocksize_bits;		/* fs blocksize in bits */
+	int blks_in_chunk;		/* number of blocks in a chunk */
+	unsigned long min, max, avg;	/* chunk size stats */
+	struct free_chunk_histogram histogram; /* histogram of all chunk sizes*/
+};
Index: e2fsprogs-1.41.8/configure
===================================================================
--- e2fsprogs-1.41.8.orig/configure
+++ e2fsprogs-1.41.8/configure
@@ -15790,7 +15790,7 @@ fi
 
 
 
-for ac_func in chflags getrusage llseek lseek64 open64 fstat64 ftruncate64 getmntinfo strtoull strcasecmp srandom jrand48 fchown mallinfo fdatasync strnlen strptime strdup sysconf pathconf posix_memalign memalign valloc __secure_getenv prctl mmap utime setresuid setresgid usleep nanosleep getdtablesize getrlimit
+for ac_func in chflags getrusage llseek lseek64 open64 fstat64 ftruncate64 getmntinfo strtoull strcasecmp srandom jrand48 fchown mallinfo fdatasync strnlen strptime strdup sysconf pathconf posix_memalign memalign valloc __secure_getenv prctl mmap utime setresuid setresgid usleep nanosleep getdtablesize getrlimit sync_file_range posix_fadvise fallocate
 do
 as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
 { $as_echo "$as_me:$LINENO: checking for $ac_func" >&5
Index: e2fsprogs-1.41.8/configure.in
===================================================================
--- e2fsprogs-1.41.8.orig/configure.in
+++ e2fsprogs-1.41.8/configure.in
@@ -828,7 +828,7 @@ AC_CHECK_MEMBER(struct sockaddr.sa_len,
 	[#include <sys/types.h>
 	 #include <sys/socket.h>])
 dnl
-AC_CHECK_FUNCS(chflags getrusage llseek lseek64 open64 fstat64 ftruncate64 getmntinfo strtoull strcasecmp srandom jrand48 fchown mallinfo fdatasync strnlen strptime strdup sysconf pathconf posix_memalign memalign valloc __secure_getenv prctl mmap utime setresuid setresgid usleep nanosleep getdtablesize getrlimit)
+AC_CHECK_FUNCS(chflags getrusage llseek lseek64 open64 fstat64 ftruncate64 getmntinfo strtoull strcasecmp srandom jrand48 fchown mallinfo fdatasync strnlen strptime strdup sysconf pathconf posix_memalign memalign valloc __secure_getenv prctl mmap utime setresuid setresgid usleep nanosleep getdtablesize getrlimit sync_file_range posix_fadvise fallocate)
 dnl
 dnl Check to see if -lsocket is required (solaris) to make something
 dnl that uses socket() to compile; this is needed for the UUID library
Index: e2fsprogs-1.41.8/Makefile.in
===================================================================
--- e2fsprogs-1.41.8.orig/Makefile.in
+++ e2fsprogs-1.41.8/Makefile.in
@@ -57,6 +57,9 @@ clean-doc:
 distclean-doc:
 	-test -d doc && cd doc && $(MAKE) distclean
 
+install-e4defrag: subs all-libs-recursive
+	$(MAKE) -C misc install-e4defrag
+
 install: subs all-libs-recursive install-progs-recursive \
   install-shlibs-libs-recursive install-doc-libs
 	if test ! -d e2fsck && test ! -d debugfs && test ! -d misc && test ! -d ext2ed ; then $(MAKE) install-libs ; fi