2 * Copyright (c) 2000-2002 Silicon Graphics, Inc.
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation.
9 * This program is distributed in the hope that it would be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write the Free Software Foundation,
16 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 #include "xfs_types.h"
23 #include "xfs_bmap_btree.h"
24 #include "xfs_attr_sf.h"
31 #include <sys/ioctl.h>
33 #include <sys/statvfs.h>
34 #include <sys/xattr.h>
37 #define _PATH_FSRLAST "/var/tmp/.fsrlast_xfs"
38 #define _PATH_PROC_MOUNTS "/proc/mounts"
46 /* static int nflag; */
48 /* static int sflag; */
50 extern int max_ext_size
;
51 static int npasses
= 10;
52 static int startpass
= 0;
54 struct getbmap
*outmap
= NULL
;
58 static int64_t minimumfree
= 2048;
60 #define MNTTYPE_XFS "xfs"
66 #define TARGETRANGE 10
70 #define BUFFER_SIZE (1<<16)
71 #define BUFFER_MAX (1<<24)
73 static time_t howlong
= 7200; /* default seconds of reorganizing */
74 static char *leftofffile
= _PATH_FSRLAST
; /* where we left off last */
75 static time_t endtime
;
76 static time_t starttime
;
77 static xfs_ino_t leftoffino
= 0;
81 static int fsrfile(char *fname
, xfs_ino_t ino
);
82 static int fsrfile_common( char *fname
, char *tname
, char *mnt
,
83 int fd
, xfs_bstat_t
*statp
);
84 static int packfile(char *fname
, char *tname
, int fd
,
85 xfs_bstat_t
*statp
, struct fsxattr
*fsxp
);
86 static void fsrdir(char *dirname
);
87 static int fsrfs(char *mntdir
, xfs_ino_t ino
, int targetrange
);
88 static void initallfs(char *mtab
);
89 static void fsrallfs(char *mtab
, int howlong
, char *leftofffile
);
90 static void fsrall_cleanup(int timeout
);
91 static int getnextents(int);
92 int xfsrtextsize(int fd
);
93 int xfs_getrt(int fd
, struct statvfs
*sfbp
);
94 char * gettmpname(char *fname
);
95 char * getparent(char *fname
);
96 int fsrprintf(const char *fmt
, ...);
97 int read_fd_bmap(int, xfs_bstat_t
*, int *);
98 int cmp(const void *, const void *);
99 static void tmp_init(char *mnt
);
100 static char * tmp_next(char *mnt
);
101 static void tmp_close(char *mnt
);
102 int xfs_getgeom(int , xfs_fsop_geom_v1_t
* );
104 xfs_fsop_geom_v1_t fsgeom
; /* geometry of active mounted system */
109 typedef struct fsdesc
{
115 fsdesc_t
*fs
, *fsbase
, *fsend
;
116 int fsbufsize
= 10; /* A starting value */
117 int nfrags
= 0; /* Debug option: Coerse into specific number
119 int openopts
= O_CREAT
|O_EXCL
|O_RDWR
|O_DIRECT
;
122 xfs_fsgeometry(int fd
, xfs_fsop_geom_v1_t
*geom
)
124 return ioctl(fd
, XFS_IOC_FSGEOMETRY_V1
, geom
);
128 xfs_bulkstat_single(int fd
, xfs_ino_t
*lastip
, xfs_bstat_t
*ubuffer
)
130 xfs_fsop_bulkreq_t bulkreq
;
132 bulkreq
.lastip
= (__u64
*)lastip
;
134 bulkreq
.ubuffer
= ubuffer
;
135 bulkreq
.ocount
= NULL
;
136 return ioctl(fd
, XFS_IOC_FSBULKSTAT_SINGLE
, &bulkreq
);
140 xfs_bulkstat(int fd
, xfs_ino_t
*lastip
, int icount
,
141 xfs_bstat_t
*ubuffer
, __s32
*ocount
)
143 xfs_fsop_bulkreq_t bulkreq
;
145 bulkreq
.lastip
= (__u64
*)lastip
;
146 bulkreq
.icount
= icount
;
147 bulkreq
.ubuffer
= ubuffer
;
148 bulkreq
.ocount
= ocount
;
149 return ioctl(fd
, XFS_IOC_FSBULKSTAT
, &bulkreq
);
153 xfs_swapext(int fd
, xfs_swapext_t
*sx
)
155 return ioctl(fd
, XFS_IOC_SWAPEXT
, sx
);
159 xfs_fscounts(int fd
, xfs_fsop_counts_t
*counts
)
161 return ioctl(fd
, XFS_IOC_FSCOUNTS
, counts
);
172 main(int argc
, char **argv
)
181 progname
= basename(argv
[0]);
183 setlocale(LC_ALL
, "");
184 bindtextdomain(PACKAGE
, LOCALEDIR
);
189 while ((c
= getopt(argc
, argv
, "C:p:e:MgsdnvTt:f:m:b:N:FV")) != -1) {
206 case 's': /* frag stats only */
209 _("%s: Stats not yet supported for XFS\n"),
214 howlong
= atoi(optarg
);
217 leftofffile
= optarg
;
223 argv_blksz_dio
= atoi(optarg
);
226 npasses
= atoi(optarg
);
229 /* Testing opt: coerses frag count in result */
230 if (getenv("FSRXFSTEST") != NULL
) {
231 nfrags
= atoi(optarg
);
236 printf(_("%s version %s\n"), progname
, VERSION
);
244 * If the user did not specify an explicit mount table, try to use
245 * /proc/mounts if it is available, else /etc/mtab. We prefer
246 * /proc/mounts because it is kernel controlled, while /etc/mtab
247 * may contain garbage that userspace tools like pam_mounts wrote
251 if (access(_PATH_PROC_MOUNTS
, R_OK
) == 0)
252 mtab
= _PATH_PROC_MOUNTS
;
254 mtab
= _PATH_MOUNTED
;
258 setbuf(stdout
, NULL
);
262 /* Save the caller's real uid */
265 pagesize
= getpagesize();
266 fs_table_initialise(0, NULL
, 0, NULL
);
268 for (; optind
< argc
; optind
++) {
269 argname
= argv
[optind
];
271 if (lstat(argname
, &sb
) < 0) {
273 _("%s: could not stat: %s: %s\n"),
274 progname
, argname
, strerror(errno
));
278 if (S_ISLNK(sb
.st_mode
)) {
281 if (stat(argname
, &sb2
) == 0 &&
282 (S_ISBLK(sb2
.st_mode
) ||
283 S_ISCHR(sb2
.st_mode
)))
287 fsp
= fs_table_lookup_mount(argname
);
289 fsp
= fs_table_lookup_blkdev(argname
);
291 fsrfs(fsp
->fs_dir
, 0, 100);
292 } else if (S_ISCHR(sb
.st_mode
)) {
294 "%s: char special not supported: %s\n"),
297 } else if (S_ISDIR(sb
.st_mode
) || S_ISREG(sb
.st_mode
)) {
298 if (!platform_test_xfs_path(argname
)) {
300 "%s: cannot defragment: %s: Not XFS\n"),
304 if (S_ISDIR(sb
.st_mode
))
307 fsrfile(argname
, sb
.st_ino
);
310 _("%s: not fsys dev, dir, or reg file, ignoring\n"),
316 fsrallfs(mtab
, howlong
, leftofffile
);
325 "Usage: %s [-d] [-v] [-g] [-t time] [-p passes] [-f leftf] [-m mtab]\n"
326 " %s [-d] [-v] [-g] xfsdev | dir | file ...\n"
329 " -g Print to syslog (default if stdout not a tty).\n"
330 " -t time How long to run in seconds.\n"
331 " -p passes Number of passes before terminating global re-org.\n"
332 " -f leftoff Use this instead of %s.\n"
333 " -m mtab Use something other than /etc/mtab.\n"
334 " -d Debug, print even more.\n"
335 " -v Verbose, more -v's more verbose.\n"
336 " -V Print version number and exit.\n"
337 ), progname
, progname
, progname
, _PATH_FSRLAST
);
342 * initallfs -- read the mount table and set up an internal form
345 initallfs(char *mtab
)
347 struct mntent_cursor cursor
;
348 struct mntent
*mnt
= NULL
;
353 /* malloc a number of descriptors, increased later if needed */
354 if (!(fsbase
= (fsdesc_t
*)malloc(fsbufsize
* sizeof(fsdesc_t
)))) {
355 fsrprintf(_("out of memory: %s\n"), strerror(errno
));
358 fsend
= (fsbase
+ fsbufsize
- 1);
360 /* find all rw xfs file systems */
364 if (platform_mntent_open(&cursor
, mtab
) != 0){
365 fprintf(stderr
, "Error: can't get mntent entries.\n");
369 while ((mnt
= platform_mntent_next(&cursor
)) != NULL
) {
372 if (strcmp(mnt
->mnt_type
, MNTTYPE_XFS
) != 0 ||
373 stat(mnt
->mnt_fsname
, &sb
) == -1 ||
374 !S_ISBLK(sb
.st_mode
))
377 cp
= strtok(mnt
->mnt_opts
,",");
379 if (strcmp("rw", cp
) == 0)
381 } while ((cp
= strtok(NULL
, ",")) != NULL
);
384 fsrprintf(_("Skipping %s: not mounted rw\n"),
389 if (mi
== fsbufsize
) {
391 if ((fsbase
= (fsdesc_t
*)realloc((char *)fsbase
,
392 fsbufsize
* sizeof(fsdesc_t
))) == NULL
) {
393 fsrprintf(_("out of memory: %s\n"),
398 fsrprintf(_("out of memory on realloc: %s\n"),
402 fs
= (fsbase
+ mi
); /* Needed ? */
405 fs
->dev
= strdup(mnt
->mnt_fsname
);
406 fs
->mnt
= strdup(mnt
->mnt_dir
);
408 if (fs
->dev
== NULL
) {
409 fsrprintf(_("strdup(%s) failed\n"), mnt
->mnt_fsname
);
412 if (fs
->mnt
== NULL
) {
413 fsrprintf(_("strdup(%s) failed\n"), mnt
->mnt_dir
);
419 platform_mntent_close(&cursor
);
422 fsend
= (fsbase
+ numfs
);
424 fsrprintf(_("no rw xfs file systems in mtab: %s\n"), mtab
);
427 if (vflag
|| dflag
) {
428 fsrprintf(_("Found %d mounted, writable, XFS filesystems\n"),
431 for (fs
= fsbase
; fs
< fsend
; fs
++)
432 fsrprintf("\t%-30.30s%-30.30s\n", fs
->dev
, fs
->mnt
);
437 fsrallfs(char *mtab
, int howlong
, char *leftofffile
)
446 xfs_ino_t startino
= 0;
450 fsrprintf("xfs_fsr -m %s -t %d -f %s ...\n", mtab
, howlong
, leftofffile
);
452 endtime
= starttime
+ howlong
;
455 /* where'd we leave off last time? */
456 if (lstat(leftofffile
, &sb
) == 0) {
457 if ( (fd
= open(leftofffile
, O_RDONLY
)) == -1 ) {
458 fsrprintf(_("%s: open failed\n"), leftofffile
);
460 else if ( fstat(fd
, &sb2
) == 0) {
462 * Verify that lstat & fstat point to the
463 * same regular file (no links/no quick spoofs)
465 if ( (sb
.st_dev
!= sb2
.st_dev
) ||
466 (sb
.st_ino
!= sb2
.st_ino
) ||
467 ((sb
.st_mode
& S_IFMT
) != S_IFREG
) ||
468 ((sb2
.st_mode
& S_IFMT
) != S_IFREG
) ||
469 (sb2
.st_uid
!= ROOT
) ||
473 fsrprintf(_("Can't use %s: mode=0%o own=%d"
475 leftofffile
, sb
.st_mode
,
476 sb
.st_uid
, sb
.st_nlink
);
491 if (read(fd
, buf
, SMBUFSZ
) == -1) {
493 fsrprintf(_("could not read %s, starting with %s\n"),
494 leftofffile
, *fs
->dev
);
496 /* Ensure the buffer we read is null terminated */
497 buf
[SMBUFSZ
-1] = '\0';
498 for (fs
= fsbase
; fs
< fsend
; fs
++) {
500 if ((strncmp(buf
,fsname
,strlen(fsname
)) == 0)
501 && buf
[strlen(fsname
)] == ' ') {
509 ptr
= strchr(buf
, ' ');
511 startpass
= atoi(++ptr
);
512 ptr
= strchr(ptr
, ' ');
514 startino
= strtoull(++ptr
, NULL
, 10);
520 /* Init pass counts */
521 for (fsp
= fsbase
; fsp
< fs
; fsp
++) {
522 fsp
->npass
= startpass
+ 1;
524 for (fsp
= fs
; fsp
<= fsend
; fsp
++) {
525 fsp
->npass
= startpass
;
532 fsrprintf(_("START: pass=%d ino=%llu %s %s\n"),
533 fs
->npass
, (unsigned long long)startino
,
537 signal(SIGABRT
, aborter
);
538 signal(SIGHUP
, aborter
);
539 signal(SIGINT
, aborter
);
540 signal(SIGQUIT
, aborter
);
541 signal(SIGTERM
, aborter
);
543 /* reorg for 'howlong' -- checked in 'fsrfs' */
544 while (endtime
> time(0)) {
547 if (npasses
> 1 && !fs
->npass
)
554 fsrprintf(_("couldn't fork sub process:"));
558 error
= fsrfs(fs
->mnt
, startino
, TARGETRANGE
);
563 if (WIFEXITED(error
) && WEXITSTATUS(error
) == 1) {
564 /* child timed out & did fsrall_cleanup */
569 startino
= 0; /* reset after the first time through */
574 if (fs
->npass
== npasses
) {
575 fsrprintf(_("Completed all %d passes\n"), npasses
);
579 fsrall_cleanup(endtime
<= time(0));
583 * fsrall_cleanup -- close files, print next starting location, etc.
586 fsrall_cleanup(int timeout
)
595 fsrprintf(_("%s startpass %d, endpass %d, time %d seconds\n"),
596 progname
, startpass
, fs
->npass
,
597 time(0) - endtime
+ howlong
);
599 /* record where we left off */
600 fd
= open(leftofffile
, O_WRONLY
|O_CREAT
|O_EXCL
, 0644);
602 fsrprintf(_("open(%s) failed: %s\n"),
603 leftofffile
, strerror(errno
));
605 ret
= sprintf(buf
, "%s %d %llu\n", fs
->dev
,
606 fs
->npass
, (unsigned long long)leftoffino
);
607 if (write(fd
, buf
, ret
) < strlen(buf
))
608 fsrprintf(_("write(%s) failed: %s\n"),
609 leftofffile
, strerror(errno
));
616 * fsrfs -- reorganize a file system
619 fsrfs(char *mntdir
, xfs_ino_t startino
, int targetrange
)
626 xfs_bstat_t buf
[GRABSZ
];
629 jdm_fshandle_t
*fshandlep
;
630 xfs_ino_t lastino
= startino
;
632 fsrprintf(_("%s start inode=%llu\n"), mntdir
,
633 (unsigned long long)startino
);
635 fshandlep
= jdm_getfshandle( mntdir
);
637 fsrprintf(_("unable to get handle: %s: %s\n"),
638 mntdir
, strerror( errno
));
642 if ((fsfd
= open(mntdir
, O_RDONLY
)) < 0) {
643 fsrprintf(_("unable to open: %s: %s\n"),
644 mntdir
, strerror( errno
));
649 if (xfs_getgeom(fsfd
, &fsgeom
) < 0 ) {
650 fsrprintf(_("Skipping %s: could not get XFS geometry\n"),
659 while ((ret
= xfs_bulkstat(fsfd
,
660 &lastino
, GRABSZ
, &buf
[0], &buflenout
)) == 0) {
667 /* Each loop through, defrag targetrange percent of the files */
668 count
= (buflenout
* targetrange
) / 100;
670 qsort((char *)buf
, buflenout
, sizeof(struct xfs_bstat
), cmp
);
672 for (p
= buf
, endp
= (buf
+ buflenout
); p
< endp
; p
++) {
673 /* Do some obvious checks now */
674 if (((p
->bs_mode
& S_IFMT
) != S_IFREG
) ||
678 fd
= jdm_open(fshandlep
, p
, O_RDWR
|O_DIRECT
);
680 /* This probably means the file was
681 * removed while in progress of handling
682 * it. Just quietly ignore this file.
685 fsrprintf(_("could not open: "
686 "inode %llu\n"), p
->bs_ino
);
690 /* Don't know the pathname, so make up something */
691 sprintf(fname
, "ino=%lld", (long long)p
->bs_ino
);
693 /* Get a tmp file name */
694 tname
= tmp_next(mntdir
);
696 ret
= fsrfile_common(fname
, tname
, mntdir
, fd
, p
);
698 leftoffino
= p
->bs_ino
;
707 if (endtime
&& endtime
< time(0)) {
715 fsrprintf(_("%s: xfs_bulkstat: %s\n"), progname
, strerror(errno
));
724 * To compare bstat structs for qsort.
727 cmp(const void *s1
, const void *s2
)
729 return( ((xfs_bstat_t
*)s2
)->bs_extents
-
730 ((xfs_bstat_t
*)s1
)->bs_extents
);
735 * reorganize by directory hierarchy.
736 * Stay in dev (a restriction based on structure of this program -- either
737 * call efs_{n,u}mount() around each file, something smarter or this)
740 fsrdir(char *dirname
)
742 fsrprintf(_("%s: Directory defragmentation not supported\n"), dirname
);
746 * Sets up the defragmentation of a file based on the
747 * filepath. It collects the bstat information, does
748 * an open on the file and passes this all to fsrfile_common.
751 fsrfile(char *fname
, xfs_ino_t ino
)
754 jdm_fshandle_t
*fshandlep
;
755 int fd
= -1, fsfd
= -1;
759 fshandlep
= jdm_getfshandle(getparent (fname
) );
761 fsrprintf(_("unable to construct sys handle for %s: %s\n"),
762 fname
, strerror(errno
));
767 * Need to open something on the same filesystem as the
768 * file. Open the parent.
770 fsfd
= open(getparent(fname
), O_RDONLY
);
772 fsrprintf(_("unable to open sys handle for %s: %s\n"),
773 fname
, strerror(errno
));
777 if ((xfs_bulkstat_single(fsfd
, &ino
, &statbuf
)) < 0) {
778 fsrprintf(_("unable to get bstat on %s: %s\n"),
779 fname
, strerror(errno
));
783 fd
= jdm_open(fshandlep
, &statbuf
, O_RDWR
|O_DIRECT
);
785 fsrprintf(_("unable to open handle %s: %s\n"),
786 fname
, strerror(errno
));
790 /* Get the fs geometry */
791 if (xfs_getgeom(fsfd
, &fsgeom
) < 0 ) {
792 fsrprintf(_("Unable to get geom on fs for: %s\n"), fname
);
796 tname
= gettmpname(fname
);
799 error
= fsrfile_common(fname
, tname
, NULL
, fd
, &statbuf
);
813 * This is the common defrag code for either a full fs
814 * defragmentation or a single file. Check as much as
815 * possible with the file, fork a process to setuid to the
816 * target file owner's uid and defragment the file.
817 * This is done so the new extents created in a tmp file are
818 * reflected in the owners' quota without having to do any
819 * special code in the kernel. When the existing extents
820 * are removed, the quotas will be correct. It's ugly but
821 * it saves us from doing some quota re-construction in
822 * the extent swap. The price is that the defragmentation
823 * will fail if the owner of the target file is already at
840 fsrprintf("%s\n", fname
);
843 fsrprintf(_("sync failed: %s: %s\n"), fname
, strerror(errno
));
847 if (statp
->bs_size
== 0) {
849 fsrprintf(_("%s: zero size, ignoring\n"), fname
);
853 /* Check if a mandatory lock is set on the file to try and
854 * avoid blocking indefinitely on the reads later. Note that
855 * someone could still set a mandatory lock after this check
856 * but before all reads have completed to block fsr reads.
857 * This change just closes the window a bit.
859 if ( (statp
->bs_mode
& S_ISGID
) && ( ! (statp
->bs_mode
&S_IXGRP
) ) ) {
863 fl
.l_whence
= SEEK_SET
;
864 fl
.l_start
= (off_t
)0;
866 if ((fcntl(fd
, F_GETLK
, &fl
)) < 0 ) {
868 fsrprintf(_("locking check failed: %s\n"),
872 if (fl
.l_type
!= F_UNLCK
) {
873 /* Mandatory lock is set */
875 fsrprintf(_("mandatory lock: %s: ignoring\n"),
882 * Check if there is room to copy the file.
884 * Note that xfs_bstat.bs_blksize returns the filesystem blocksize,
885 * not the optimal I/O size as struct stat.
887 if (statvfs(fsname
? fsname
: fname
, &vfss
) < 0) {
888 fsrprintf(_("unable to get fs stat on %s: %s\n"),
889 fname
, strerror(errno
));
892 bsize
= vfss
.f_frsize
? vfss
.f_frsize
: vfss
.f_bsize
;
893 if (statp
->bs_blksize
* statp
->bs_blocks
>
894 vfss
.f_bfree
* bsize
- minimumfree
) {
895 fsrprintf(_("insufficient freespace for: %s: "
896 "size=%lld: ignoring\n"), fname
,
897 statp
->bs_blksize
* statp
->bs_blocks
);
901 if ((ioctl(fd
, FS_IOC_FSGETXATTR
, &fsx
)) < 0) {
902 fsrprintf(_("failed to get inode attrs: %s\n"), fname
);
905 if (fsx
.fsx_xflags
& (FS_XFLAG_IMMUTABLE
|FS_XFLAG_APPEND
)) {
907 fsrprintf(_("%s: immutable/append, ignoring\n"), fname
);
910 if (fsx
.fsx_xflags
& FS_XFLAG_NODEFRAG
) {
912 fsrprintf(_("%s: marked as don't defrag, ignoring\n"),
916 if (fsx
.fsx_xflags
& FS_XFLAG_REALTIME
) {
917 if (xfs_getrt(fd
, &vfss
) < 0) {
918 fsrprintf(_("cannot get realtime geometry for: %s\n"),
922 if (statp
->bs_size
> ((vfss
.f_bfree
* bsize
) - minimumfree
)) {
923 fsrprintf(_("low on realtime free space: %s: "
924 "ignoring file\n"), fname
);
929 if ((RealUid
!= ROOT
) && (RealUid
!= statp
->bs_uid
)) {
930 fsrprintf(_("cannot open: %s: Permission denied\n"), fname
);
935 * Previously the code forked here, & the child changed it's uid to
936 * that of the file's owner and then called packfile(), to keep
937 * quota counts correct. (defragged files could use fewer blocks).
939 * Instead, just fchown() the temp file to the uid,gid of the
940 * file we're defragging, in packfile().
943 if ((error
= packfile(fname
, tname
, fd
, statp
, &fsx
)))
945 return -1; /* no error */
949 * Attempt to set the attr fork up correctly. This is simple for attr1
950 * filesystems as they have a fixed inode fork offset. In that case
951 * just create an attribute and that's all we need to do.
953 * For attr2 filesystems, see if we have the actual fork offset in
954 * the bstat structure. If so, just create additional attributes on
955 * the temporary inode until the offset matches.
957 * If it doesn't exist, we can only do best effort. Add an attribute at a time
958 * to move the inode fork around, but take into account that the attribute
959 * might be too small to move the fork every time we add one. This should
960 * hopefully put the fork offset in the right place. It's not a big deal if we
961 * don't get it right - the kernel will reject it when we try to swap extents.
969 #ifdef HAVE_FSETXATTR
970 struct stat tstatbuf
;
973 int last_forkoff
= 0;
974 int no_change_cnt
= 0;
977 if (!(bstatp
->bs_xflags
& FS_XFLAG_HASATTR
))
981 * use the old method if we have attr1 or the kernel does not yet
982 * support passing the fork offset in the bulkstat data.
984 if (!(fsgeom
.flags
& XFS_FSOP_GEOM_FLAGS_ATTR2
) ||
985 bstatp
->bs_forkoff
== 0) {
987 ret
= fsetxattr(tfd
, "user.X", "X", 1, XATTR_CREATE
);
989 fsrprintf(_("could not set ATTR\n"));
995 /* attr2 w/ fork offsets */
997 if (fstat(tfd
, &tstatbuf
) < 0) {
998 fsrprintf(_("unable to stat temp file: %s\n"),
1010 * bulkstat the temp inode to see what the forkoff is. Use
1011 * this to compare against the target and determine what we
1014 ino
= tstatbuf
.st_ino
;
1015 if ((xfs_bulkstat_single(tfd
, &ino
, &tbstat
)) < 0) {
1016 fsrprintf(_("unable to get bstat on temp file: %s\n"),
1021 fsrprintf(_("orig forkoff %d, temp forkoff %d\n"),
1022 bstatp
->bs_forkoff
, tbstat
.bs_forkoff
);
1023 diff
= tbstat
.bs_forkoff
- bstatp
->bs_forkoff
;
1025 /* if they are equal, we are done */
1029 snprintf(name
, sizeof(name
), "user.%d", i
);
1032 * If there is no attribute, then we need to create one to get
1033 * an attribute fork at the default location.
1035 if (!tbstat
.bs_forkoff
) {
1037 ret
= fsetxattr(tfd
, name
, "XX", 2, XATTR_CREATE
);
1039 fsrprintf(_("could not set ATTR\n"));
1043 } else if (i
== 0) {
1045 * First pass, and temp file already has an inline
1046 * xattr, probably due to selinux.
1048 * It's *possible* that the temp file attr area
1049 * is larger than the target file's:
1052 * +-------+ 0 +-------+ 0
1056 * | | v-------v forkoff
1058 * v-------v forkoff | Attr | local
1060 * +-------+ +-------+
1064 * If target attr area is less than the temp's
1065 * (diff < 0) write a big attr to the temp file to knock
1066 * the attr out of local format.
1067 * (This should actually *increase* the temp file's
1068 * forkoffset when the attr moves out of the inode)
1072 memset(val
, 'X', 2048);
1073 if (fsetxattr(tfd
, name
, val
, 2048, 0)) {
1074 fsrprintf(_("big ATTR set failed\n"));
1077 /* Go back & see where we're at now */
1083 * make a progress check so we don't get stuck trying to extend
1084 * a large btree form attribute fork.
1086 if (last_forkoff
== tbstat
.bs_forkoff
) {
1087 if (no_change_cnt
++ > 10)
1089 } else /* progress! */
1091 last_forkoff
= tbstat
.bs_forkoff
;
1093 /* work out which way to grow the fork */
1094 if (abs(diff
) > fsgeom
.inodesize
- sizeof(struct xfs_dinode
)) {
1095 fsrprintf(_("forkoff diff %d too large!\n"), diff
);
1100 * if the temp inode fork offset is still smaller then we have
1101 * to grow the data fork
1105 * create some temporary extents in the inode to move
1106 * the fork in the direction we need. This can be done
1107 * by preallocating some single block extents at
1108 * non-contiguous offsets.
1110 /* XXX: unimplemented! */
1112 printf(_("data fork growth unimplemented\n"));
1116 /* we need to grow the attr fork, so create another attr */
1117 ret
= fsetxattr(tfd
, name
, "XX", 2, XATTR_CREATE
);
1119 fsrprintf(_("could not set ATTR\n"));
1123 } while (++i
< 100); /* don't go forever */
1127 fsrprintf(_("set temp attr\n"));
1128 /* We failed to resolve the fork difference */
1130 fsrprintf(_("failed to match fork offset\n"));;
1132 #endif /* HAVE_FSETXATTR */
1137 * Do the defragmentation of a single file.
1138 * We already are pretty sure we can and want to
1139 * defragment the file. Create the tmp file, copy
1140 * the data (maintaining holes) and call the kernel
1141 * extent swap routine.
1144 * -1: Some error was encountered
1145 * 0: Successfully defragmented the file
1146 * 1: No change / No Error
1149 packfile(char *fname
, char *tname
, int fd
,
1150 xfs_bstat_t
*statp
, struct fsxattr
*fsxp
)
1154 int retval
= -1; /* Failure is the default */
1155 int nextents
, extent
, cur_nextents
, new_nextents
;
1159 static xfs_swapext_t sx
;
1160 struct xfs_flock64 space
;
1164 char ffname
[SMBUFSZ
];
1168 * Work out the extent map - nextents will be set to the
1169 * minimum number of extents needed for the file (taking
1170 * into account holes), cur_nextents is the current number
1173 nextents
= read_fd_bmap(fd
, statp
, &cur_nextents
);
1175 if (cur_nextents
== 1 || cur_nextents
<= nextents
) {
1177 fsrprintf(_("%s already fully defragmented.\n"), fname
);
1178 retval
= 1; /* indicates no change/no error */
1183 fsrprintf(_("%s extents=%d can_save=%d tmp=%s\n"),
1184 fname
, cur_nextents
, (cur_nextents
- nextents
),
1187 if ((tfd
= open(tname
, openopts
, 0666)) < 0) {
1189 fsrprintf(_("could not open tmp file: %s: %s\n"),
1190 tname
, strerror(errno
));
1195 /* Setup extended attributes */
1196 if (fsr_setup_attr_fork(fd
, tfd
, statp
) != 0) {
1197 fsrprintf(_("failed to set ATTR fork on tmp: %s:\n"), tname
);
1201 /* Setup extended inode flags, project identifier, etc */
1202 if (fsxp
->fsx_xflags
|| fsxp
->fsx_projid
) {
1203 if (ioctl(tfd
, FS_IOC_FSSETXATTR
, fsxp
) < 0) {
1204 fsrprintf(_("could not set inode attrs on tmp: %s\n"),
1210 if ((ioctl(tfd
, XFS_IOC_DIOINFO
, &dio
)) < 0 ) {
1211 fsrprintf(_("could not get DirectIO info on tmp: %s\n"), tname
);
1215 dio_min
= dio
.d_miniosz
;
1216 if (statp
->bs_size
<= dio_min
) {
1217 blksz_dio
= dio_min
;
1219 blksz_dio
= min(dio
.d_maxiosz
, BUFFER_MAX
- pagesize
);
1220 if (argv_blksz_dio
!= 0)
1221 blksz_dio
= min(argv_blksz_dio
, blksz_dio
);
1222 blksz_dio
= (min(statp
->bs_size
, blksz_dio
) / dio_min
) * dio_min
;
1226 fsrprintf(_("DEBUG: "
1227 "fsize=%lld blsz_dio=%d d_min=%d d_max=%d pgsz=%d\n"),
1228 statp
->bs_size
, blksz_dio
, dio
.d_miniosz
,
1229 dio
.d_maxiosz
, pagesize
);
1232 if (!(fbuf
= (char *)memalign(dio
.d_mem
, blksz_dio
))) {
1233 fsrprintf(_("could not allocate buf: %s\n"), tname
);
1238 /* Create new tmp file in same AG as first */
1239 sprintf(ffname
, "%s.frag", tname
);
1241 /* Open the new file for sync writes */
1242 if ((ffd
= open(ffname
, openopts
, 0666)) < 0) {
1243 fsrprintf(_("could not open fragfile: %s : %s\n"),
1244 ffname
, strerror(errno
));
1250 /* Loop through block map allocating new extents */
1251 for (extent
= 0; extent
< nextents
; extent
++) {
1252 pos
= outmap
[extent
].bmv_offset
;
1253 if (outmap
[extent
].bmv_block
== -1) {
1254 space
.l_whence
= SEEK_SET
;
1255 space
.l_start
= pos
;
1256 space
.l_len
= outmap
[extent
].bmv_length
;
1257 if (ioctl(tfd
, XFS_IOC_UNRESVSP64
, &space
) < 0) {
1258 fsrprintf(_("could not trunc tmp %s\n"),
1261 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1262 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1263 tname
, strerror(errno
));
1267 } else if (outmap
[extent
].bmv_length
== 0) {
1268 /* to catch holes at the beginning of the file */
1272 space
.l_whence
= SEEK_CUR
;
1274 space
.l_len
= outmap
[extent
].bmv_length
;
1276 if (ioctl(tfd
, XFS_IOC_RESVSP64
, &space
) < 0) {
1277 fsrprintf(_("could not pre-allocate tmp space:"
1281 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1282 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1283 tname
, strerror(errno
));
1287 } /* end of space allocation loop */
1289 if (lseek(tfd
, 0, SEEK_SET
)) {
1290 fsrprintf(_("Couldn't rewind on temporary file\n"));
1294 /* Check if the temporary file has fewer extents */
1295 new_nextents
= getnextents(tfd
);
1297 fsrprintf(_("Temporary file has %d extents (%d in original)\n"), new_nextents
, cur_nextents
);
1298 if (cur_nextents
<= new_nextents
) {
1300 fsrprintf(_("No improvement will be made (skipping): %s\n"), fname
);
1301 retval
= 1; /* no change/no error */
1305 /* Loop through block map copying the file. */
1306 for (extent
= 0; extent
< nextents
; extent
++) {
1307 pos
= outmap
[extent
].bmv_offset
;
1308 if (outmap
[extent
].bmv_block
== -1) {
1309 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1310 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1311 tname
, strerror(errno
));
1314 if (lseek(fd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1315 fsrprintf(_("could not lseek in file: %s : %s\n"),
1316 fname
, strerror(errno
));
1320 } else if (outmap
[extent
].bmv_length
== 0) {
1321 /* to catch holes at the beginning of the file */
1324 for (cnt
= outmap
[extent
].bmv_length
; cnt
> 0;
1325 cnt
-= ct
, pos
+= ct
) {
1326 if (nfrags
&& --nfrags
) {
1327 ct
= min(cnt
, dio_min
);
1328 } else if (cnt
% dio_min
== 0) {
1329 ct
= min(cnt
, blksz_dio
);
1331 ct
= min(cnt
+ dio_min
- (cnt
% dio_min
),
1334 ct
= read(fd
, fbuf
, ct
);
1336 /* EOF, stop trying to read */
1340 /* Ensure we do direct I/O to correct block
1343 if (ct
% dio_min
!= 0) {
1344 wc
= ct
+ dio_min
- (ct
% dio_min
);
1349 if (ct
< 0 || ((wc
= write(tfd
, fbuf
, wc
)) != wc_b4
)) {
1351 fsrprintf(_("bad read of %d bytes "
1352 "from %s: %s\n"), wc_b4
,
1353 fname
, strerror(errno
));
1355 fsrprintf(_("bad write of %d bytes "
1356 "to %s: %s\n"), wc_b4
,
1357 tname
, strerror(errno
));
1360 * Might be out of space
1362 * Try to finish write
1366 if ((wc
= write(tfd
, ((char *)fbuf
)+wc
,
1368 /* worked on second attempt? */
1372 fsrprintf(_("bad write2 of %d "
1373 "bytes to %s: %s\n"),
1377 fsrprintf(_("bad copy to %s\n"),
1384 /* Do a matching write to the tmp file */
1386 if (((wc
= write(ffd
, fbuf
, wc
)) != wc_b4
)) {
1387 fsrprintf(_("bad write of %d bytes "
1389 wc_b4
, ffname
, strerror(errno
));
1394 if (ftruncate(tfd
, statp
->bs_size
) < 0) {
1395 fsrprintf(_("could not truncate tmpfile: %s : %s\n"),
1396 fname
, strerror(errno
));
1399 if (fsync(tfd
) < 0) {
1400 fsrprintf(_("could not fsync tmpfile: %s : %s\n"),
1401 fname
, strerror(errno
));
1405 sx
.sx_stat
= *statp
; /* struct copy */
1406 sx
.sx_version
= XFS_SX_VERSION
;
1407 sx
.sx_fdtarget
= fd
;
1410 sx
.sx_length
= statp
->bs_size
;
1412 /* switch to the owner's id, to keep quota in line */
1413 if (fchown(tfd
, statp
->bs_uid
, statp
->bs_gid
) < 0) {
1415 fsrprintf(_("failed to fchown tmpfile %s: %s\n"),
1416 tname
, strerror(errno
));
1420 /* Swap the extents */
1421 srval
= xfs_swapext(fd
, &sx
);
1423 if (errno
== ENOTSUP
) {
1425 fsrprintf(_("%s: file type not supported\n"), fname
);
1426 } else if (errno
== EFAULT
) {
1427 /* The file has changed since we started the copy */
1429 fsrprintf(_("%s: file modified defrag aborted\n"),
1431 } else if (errno
== EBUSY
) {
1432 /* Timestamp has changed or mmap'ed file */
1434 fsrprintf(_("%s: file busy\n"), fname
);
1436 fsrprintf(_("XFS_IOC_SWAPEXT failed: %s: %s\n"),
1437 fname
, strerror(errno
));
1442 /* Report progress */
1444 fsrprintf(_("extents before:%d after:%d %s %s\n"),
1445 cur_nextents
, new_nextents
,
1446 (new_nextents
<= nextents
? "DONE" : " " ),
1460 gettmpname(char *fname
)
1462 static char buf
[PATH_MAX
+1];
1466 sprintf(sbuf
, "/.fsr%d", getpid());
1468 strncpy(buf
, fname
, PATH_MAX
);
1469 buf
[PATH_MAX
] = '\0';
1470 ptr
= strrchr(buf
, '/');
1477 if ((strlen(buf
) + strlen (sbuf
)) > PATH_MAX
) {
1478 fsrprintf(_("tmp file name too long: %s\n"), fname
);
1488 getparent(char *fname
)
1490 static char buf
[PATH_MAX
+1];
1493 strncpy(buf
, fname
, PATH_MAX
);
1494 buf
[PATH_MAX
] = '\0';
1495 ptr
= strrchr(buf
, '/');
1508 * Read in block map of the input file, coalesce contiguous
1509 * extents into a single range, keep all holes. Convert from 512 byte
1512 * This code was borrowed from mv.c with some minor mods.
1515 #define OUTMAP_SIZE_INCREMENT MAPSIZE
1517 int read_fd_bmap(int fd
, xfs_bstat_t
*sin
, int *cur_nextents
)
1520 struct getbmap map
[MAPSIZE
];
1523 if (++cnt >= outmap_size) { \
1524 outmap_size += OUTMAP_SIZE_INCREMENT; \
1525 outmap = (struct getbmap *)realloc(outmap, \
1526 outmap_size*sizeof(*outmap)); \
1527 if (outmap == NULL) { \
1528 fsrprintf(_("realloc failed: %s\n"), \
1534 /* Initialize the outmap array. It always grows - never shrinks.
1535 * Left-over memory allocation is saved for the next files.
1537 if (outmap_size
== 0) {
1538 outmap_size
= OUTMAP_SIZE_INCREMENT
; /* Initial size */
1539 outmap
= (struct getbmap
*)malloc(outmap_size
*sizeof(*outmap
));
1541 fsrprintf(_("malloc failed: %s\n"),
1547 outmap
[0].bmv_block
= 0;
1548 outmap
[0].bmv_offset
= 0;
1549 outmap
[0].bmv_length
= sin
->bs_size
;
1552 * If a non regular file is involved then forget holes
1555 if (!S_ISREG(sin
->bs_mode
))
1558 outmap
[0].bmv_length
= 0;
1560 map
[0].bmv_offset
= 0;
1561 map
[0].bmv_block
= 0;
1562 map
[0].bmv_entries
= 0;
1563 map
[0].bmv_count
= MAPSIZE
;
1564 map
[0].bmv_length
= -1;
1570 if (ioctl(fd
, XFS_IOC_GETBMAP
, map
) < 0) {
1571 fsrprintf(_("failed reading extents: inode %llu"),
1572 (unsigned long long)sin
->bs_ino
);
1576 /* Concatenate extents together and replicate holes into
1579 *cur_nextents
+= map
[0].bmv_entries
;
1580 for (i
= 0; i
< map
[0].bmv_entries
; i
++) {
1581 if (map
[i
+ 1].bmv_block
== -1) {
1583 outmap
[cnt
] = map
[i
+1];
1584 } else if (outmap
[cnt
].bmv_block
== -1) {
1586 outmap
[cnt
] = map
[i
+1];
1588 outmap
[cnt
].bmv_length
+= map
[i
+ 1].bmv_length
;
1591 } while (map
[0].bmv_entries
== (MAPSIZE
-1));
1592 for (i
= 0; i
<= cnt
; i
++) {
1593 outmap
[i
].bmv_offset
= BBTOB(outmap
[i
].bmv_offset
);
1594 outmap
[i
].bmv_length
= BBTOB(outmap
[i
].bmv_length
);
1597 outmap
[cnt
].bmv_length
= sin
->bs_size
- outmap
[cnt
].bmv_offset
;
1603 * Read the block map and return the number of extents.
1609 struct getbmap map
[MAPSIZE
];
1611 map
[0].bmv_offset
= 0;
1612 map
[0].bmv_block
= 0;
1613 map
[0].bmv_entries
= 0;
1614 map
[0].bmv_count
= MAPSIZE
;
1615 map
[0].bmv_length
= -1;
1620 if (ioctl(fd
,XFS_IOC_GETBMAP
, map
) < 0) {
1621 fsrprintf(_("failed reading extents"));
1625 nextents
+= map
[0].bmv_entries
;
1626 } while (map
[0].bmv_entries
== (MAPSIZE
-1));
1632 * Get the fs geometry
1635 xfs_getgeom(int fd
, xfs_fsop_geom_v1_t
* fsgeom
)
1637 if (xfs_fsgeometry(fd
, fsgeom
) < 0) {
1644 * Get xfs realtime space information
1647 xfs_getrt(int fd
, struct statvfs
*sfbp
)
1649 unsigned long bsize
;
1650 unsigned long factor
;
1651 xfs_fsop_counts_t cnt
;
1653 if (!fsgeom
.rtblocks
)
1656 if (xfs_fscounts(fd
, &cnt
) < 0) {
1660 bsize
= (sfbp
->f_frsize
? sfbp
->f_frsize
: sfbp
->f_bsize
);
1661 factor
= fsgeom
.blocksize
/ bsize
; /* currently this is == 1 */
1662 sfbp
->f_bfree
= (cnt
.freertx
* fsgeom
.rtextsize
) * factor
;
1667 fsrprintf(const char *fmt
, ...)
1673 static int didopenlog
;
1675 openlog("fsr", LOG_PID
, LOG_USER
);
1678 vsyslog(LOG_INFO
, fmt
, ap
);
1686 * Initialize a directory for tmp file use. This is used
1687 * by the full filesystem defragmentation when we're walking
1688 * the inodes and do not know the path for the individual
1689 * files. Multiple directories are used to spread out the
1690 * tmp data around to different ag's (since file data is
1691 * usually allocated to the same ag as the directory and
1692 * directories allocated round robin from the same
1693 * parent directory).
1699 static char buf
[SMBUFSZ
];
1703 sprintf(buf
, "%s/.fsr", mnt
);
1706 if (mkdir(buf
, 0700) < 0) {
1707 if (errno
== EEXIST
) {
1709 fsrprintf(_("tmpdir already exists: %s\n"),
1712 fsrprintf(_("could not create tmpdir: %s: %s\n"),
1713 buf
, strerror(errno
));
1717 for (i
=0; i
< fsgeom
.agcount
; i
++) {
1718 sprintf(buf
, "%s/.fsr/ag%d", mnt
, i
);
1719 if (mkdir(buf
, 0700) < 0) {
1720 if (errno
== EEXIST
) {
1723 _("tmpdir already exists: %s\n"), buf
);
1725 fsrprintf(_("cannot create tmpdir: %s: %s\n"),
1726 buf
, strerror(errno
));
1738 static char buf
[SMBUFSZ
];
1740 sprintf(buf
, "%s/.fsr/ag%d/tmp%d",
1741 ( (strcmp(mnt
, "/") == 0) ? "" : mnt
),
1745 if (++tmp_agi
== fsgeom
.agcount
)
1752 tmp_close(char *mnt
)
1754 static char buf
[SMBUFSZ
];
1757 /* No data is ever actually written so we can just do rmdir's */
1758 for (i
=0; i
< fsgeom
.agcount
; i
++) {
1759 sprintf(buf
, "%s/.fsr/ag%d", mnt
, i
);
1760 if (rmdir(buf
) < 0) {
1761 if (errno
!= ENOENT
) {
1763 _("could not remove tmpdir: %s: %s\n"),
1764 buf
, strerror(errno
));
1768 sprintf(buf
, "%s/.fsr", mnt
);
1769 if (rmdir(buf
) < 0) {
1770 if (errno
!= ENOENT
) {
1771 fsrprintf(_("could not remove tmpdir: %s: %s\n"),
1772 buf
, strerror(errno
));