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"
30 #include <sys/ioctl.h>
32 #include <sys/statvfs.h>
33 #include <sys/xattr.h>
36 #define _PATH_FSRLAST "/var/tmp/.fsrlast_xfs"
37 #define _PATH_PROC_MOUNTS "/proc/mounts"
45 /* static int nflag; */
47 /* static int sflag; */
49 extern int max_ext_size
;
50 static int npasses
= 10;
51 static int startpass
= 0;
53 struct getbmap
*outmap
= NULL
;
57 static int64_t minimumfree
= 2048;
59 #define MNTTYPE_XFS "xfs"
65 #define TARGETRANGE 10
69 #define BUFFER_SIZE (1<<16)
70 #define BUFFER_MAX (1<<24)
72 static time_t howlong
= 7200; /* default seconds of reorganizing */
73 static char *leftofffile
= _PATH_FSRLAST
; /* where we left off last */
74 static time_t endtime
;
75 static time_t starttime
;
76 static xfs_ino_t leftoffino
= 0;
80 static int fsrfile(char *fname
, xfs_ino_t ino
);
81 static int fsrfile_common( char *fname
, char *tname
, char *mnt
,
82 int fd
, xfs_bstat_t
*statp
);
83 static int packfile(char *fname
, char *tname
, int fd
,
84 xfs_bstat_t
*statp
, struct fsxattr
*fsxp
);
85 static void fsrdir(char *dirname
);
86 static int fsrfs(char *mntdir
, xfs_ino_t ino
, int targetrange
);
87 static void initallfs(char *mtab
);
88 static void fsrallfs(char *mtab
, int howlong
, char *leftofffile
);
89 static void fsrall_cleanup(int timeout
);
90 static int getnextents(int);
91 int xfsrtextsize(int fd
);
92 int xfs_getrt(int fd
, struct statvfs
*sfbp
);
93 char * gettmpname(char *fname
);
94 char * getparent(char *fname
);
95 int fsrprintf(const char *fmt
, ...);
96 int read_fd_bmap(int, xfs_bstat_t
*, int *);
97 int cmp(const void *, const void *);
98 static void tmp_init(char *mnt
);
99 static char * tmp_next(char *mnt
);
100 static void tmp_close(char *mnt
);
101 int xfs_getgeom(int , xfs_fsop_geom_v1_t
* );
103 xfs_fsop_geom_v1_t fsgeom
; /* geometry of active mounted system */
108 typedef struct fsdesc
{
114 fsdesc_t
*fs
, *fsbase
, *fsend
;
115 int fsbufsize
= 10; /* A starting value */
116 int nfrags
= 0; /* Debug option: Coerse into specific number
118 int openopts
= O_CREAT
|O_EXCL
|O_RDWR
|O_DIRECT
;
121 xfs_fsgeometry(int fd
, xfs_fsop_geom_v1_t
*geom
)
123 return ioctl(fd
, XFS_IOC_FSGEOMETRY_V1
, geom
);
127 xfs_bulkstat_single(int fd
, xfs_ino_t
*lastip
, xfs_bstat_t
*ubuffer
)
129 xfs_fsop_bulkreq_t bulkreq
;
131 bulkreq
.lastip
= (__u64
*)lastip
;
133 bulkreq
.ubuffer
= ubuffer
;
134 bulkreq
.ocount
= NULL
;
135 return ioctl(fd
, XFS_IOC_FSBULKSTAT_SINGLE
, &bulkreq
);
139 xfs_bulkstat(int fd
, xfs_ino_t
*lastip
, int icount
,
140 xfs_bstat_t
*ubuffer
, __s32
*ocount
)
142 xfs_fsop_bulkreq_t bulkreq
;
144 bulkreq
.lastip
= (__u64
*)lastip
;
145 bulkreq
.icount
= icount
;
146 bulkreq
.ubuffer
= ubuffer
;
147 bulkreq
.ocount
= ocount
;
148 return ioctl(fd
, XFS_IOC_FSBULKSTAT
, &bulkreq
);
152 xfs_swapext(int fd
, xfs_swapext_t
*sx
)
154 return ioctl(fd
, XFS_IOC_SWAPEXT
, sx
);
158 xfs_fscounts(int fd
, xfs_fsop_counts_t
*counts
)
160 return ioctl(fd
, XFS_IOC_FSCOUNTS
, counts
);
171 * Check if the argument is either the device name or mountpoint of an XFS
172 * filesystem. Note that we do not care about bind mounted regular files
173 * here - the code that handles defragmentation of invidual files takes care
177 find_mountpoint_check(struct stat
*sb
, struct mntent
*t
)
181 if (S_ISDIR(sb
->st_mode
)) { /* mount point */
182 if (stat(t
->mnt_dir
, &ms
) < 0)
184 if (sb
->st_ino
!= ms
.st_ino
)
186 if (sb
->st_dev
!= ms
.st_dev
)
188 if (strcmp(t
->mnt_type
, MNTTYPE_XFS
) != 0)
190 } else { /* device */
191 if (stat(t
->mnt_fsname
, &ms
) < 0)
193 if (sb
->st_rdev
!= ms
.st_rdev
)
195 if (strcmp(t
->mnt_type
, MNTTYPE_XFS
) != 0)
198 * Make sure the mountpoint given by mtab is accessible
201 if (stat(t
->mnt_dir
, &ms
) < 0)
209 find_mountpoint(char *mtab
, char *argname
, struct stat
*sb
)
211 struct mntent_cursor cursor
;
212 struct mntent
*t
= NULL
;
215 if (platform_mntent_open(&cursor
, mtab
) != 0){
216 fprintf(stderr
, "Error: can't get mntent entries.\n");
220 while ((t
= platform_mntent_next(&cursor
)) != NULL
) {
221 mntp
= find_mountpoint_check(sb
, t
);
226 platform_mntent_close(&cursor
);
231 main(int argc
, char **argv
)
240 progname
= basename(argv
[0]);
242 setlocale(LC_ALL
, "");
243 bindtextdomain(PACKAGE
, LOCALEDIR
);
248 while ((c
= getopt(argc
, argv
, "C:p:e:MgsdnvTt:f:m:b:N:FV")) != -1) {
265 case 's': /* frag stats only */
268 _("%s: Stats not yet supported for XFS\n"),
273 howlong
= atoi(optarg
);
276 leftofffile
= optarg
;
282 argv_blksz_dio
= atoi(optarg
);
285 npasses
= atoi(optarg
);
288 /* Testing opt: coerses frag count in result */
289 if (getenv("FSRXFSTEST") != NULL
) {
290 nfrags
= atoi(optarg
);
295 printf(_("%s version %s\n"), progname
, VERSION
);
303 * If the user did not specify an explicit mount table, try to use
304 * /proc/mounts if it is available, else /etc/mtab. We prefer
305 * /proc/mounts because it is kernel controlled, while /etc/mtab
306 * may contain garbage that userspace tools like pam_mounts wrote
310 if (access(_PATH_PROC_MOUNTS
, R_OK
) == 0)
311 mtab
= _PATH_PROC_MOUNTS
;
313 mtab
= _PATH_MOUNTED
;
317 setbuf(stdout
, NULL
);
321 /* Save the caller's real uid */
324 pagesize
= getpagesize();
327 for (; optind
< argc
; optind
++) {
328 argname
= argv
[optind
];
330 if (lstat(argname
, &sb
) < 0) {
332 _("%s: could not stat: %s: %s\n"),
333 progname
, argname
, strerror(errno
));
337 if (S_ISLNK(sb
.st_mode
)) {
340 if (stat(argname
, &sb2
) == 0 &&
341 (S_ISBLK(sb2
.st_mode
) ||
342 S_ISCHR(sb2
.st_mode
)))
346 mntp
= find_mountpoint(mtab
, argname
, &sb
);
349 } else if (S_ISCHR(sb
.st_mode
)) {
351 "%s: char special not supported: %s\n"),
354 } else if (S_ISDIR(sb
.st_mode
) || S_ISREG(sb
.st_mode
)) {
355 if (!platform_test_xfs_path(argname
)) {
357 "%s: cannot defragment: %s: Not XFS\n"),
361 if (S_ISDIR(sb
.st_mode
))
364 fsrfile(argname
, sb
.st_ino
);
367 _("%s: not fsys dev, dir, or reg file, ignoring\n"),
373 fsrallfs(mtab
, howlong
, leftofffile
);
382 "Usage: %s [-d] [-v] [-g] [-t time] [-p passes] [-f leftf] [-m mtab]\n"
383 " %s [-d] [-v] [-g] xfsdev | dir | file ...\n"
386 " -g Print to syslog (default if stdout not a tty).\n"
387 " -t time How long to run in seconds.\n"
388 " -p passes Number of passes before terminating global re-org.\n"
389 " -f leftoff Use this instead of %s.\n"
390 " -m mtab Use something other than /etc/mtab.\n"
391 " -d Debug, print even more.\n"
392 " -v Verbose, more -v's more verbose.\n"
393 " -V Print version number and exit.\n"
394 ), progname
, progname
, progname
, _PATH_FSRLAST
);
399 * initallfs -- read the mount table and set up an internal form
402 initallfs(char *mtab
)
404 struct mntent_cursor cursor
;
405 struct mntent
*mnt
= NULL
;
410 /* malloc a number of descriptors, increased later if needed */
411 if (!(fsbase
= (fsdesc_t
*)malloc(fsbufsize
* sizeof(fsdesc_t
)))) {
412 fsrprintf(_("out of memory: %s\n"), strerror(errno
));
415 fsend
= (fsbase
+ fsbufsize
- 1);
417 /* find all rw xfs file systems */
421 if (platform_mntent_open(&cursor
, mtab
) != 0){
422 fprintf(stderr
, "Error: can't get mntent entries.\n");
426 while ((mnt
= platform_mntent_next(&cursor
)) != NULL
) {
429 if (strcmp(mnt
->mnt_type
, MNTTYPE_XFS
) != 0 ||
430 stat(mnt
->mnt_fsname
, &sb
) == -1 ||
431 !S_ISBLK(sb
.st_mode
))
434 cp
= strtok(mnt
->mnt_opts
,",");
436 if (strcmp("rw", cp
) == 0)
438 } while ((cp
= strtok(NULL
, ",")) != NULL
);
441 fsrprintf(_("Skipping %s: not mounted rw\n"),
446 if (mi
== fsbufsize
) {
448 if ((fsbase
= (fsdesc_t
*)realloc((char *)fsbase
,
449 fsbufsize
* sizeof(fsdesc_t
))) == NULL
) {
450 fsrprintf(_("out of memory: %s\n"),
455 fsrprintf(_("out of memory on realloc: %s\n"),
459 fs
= (fsbase
+ mi
); /* Needed ? */
462 fs
->dev
= strdup(mnt
->mnt_fsname
);
463 fs
->mnt
= strdup(mnt
->mnt_dir
);
465 if (fs
->dev
== NULL
) {
466 fsrprintf(_("strdup(%s) failed\n"), mnt
->mnt_fsname
);
469 if (fs
->mnt
== NULL
) {
470 fsrprintf(_("strdup(%s) failed\n"), mnt
->mnt_dir
);
476 platform_mntent_close(&cursor
);
479 fsend
= (fsbase
+ numfs
);
481 fsrprintf(_("no rw xfs file systems in mtab: %s\n"), mtab
);
484 if (vflag
|| dflag
) {
485 fsrprintf(_("Found %d mounted, writable, XFS filesystems\n"),
488 for (fs
= fsbase
; fs
< fsend
; fs
++)
489 fsrprintf("\t%-30.30s%-30.30s\n", fs
->dev
, fs
->mnt
);
494 fsrallfs(char *mtab
, int howlong
, char *leftofffile
)
503 xfs_ino_t startino
= 0;
507 fsrprintf("xfs_fsr -m %s -t %d -f %s ...\n", mtab
, howlong
, leftofffile
);
509 endtime
= starttime
+ howlong
;
512 /* where'd we leave off last time? */
513 if (lstat(leftofffile
, &sb
) == 0) {
514 if ( (fd
= open(leftofffile
, O_RDONLY
)) == -1 ) {
515 fsrprintf(_("%s: open failed\n"), leftofffile
);
517 else if ( fstat(fd
, &sb2
) == 0) {
519 * Verify that lstat & fstat point to the
520 * same regular file (no links/no quick spoofs)
522 if ( (sb
.st_dev
!= sb2
.st_dev
) ||
523 (sb
.st_ino
!= sb2
.st_ino
) ||
524 ((sb
.st_mode
& S_IFMT
) != S_IFREG
) ||
525 ((sb2
.st_mode
& S_IFMT
) != S_IFREG
) ||
526 (sb2
.st_uid
!= ROOT
) ||
530 fsrprintf(_("Can't use %s: mode=0%o own=%d"
532 leftofffile
, sb
.st_mode
,
533 sb
.st_uid
, sb
.st_nlink
);
548 if (read(fd
, buf
, SMBUFSZ
) == -1) {
550 fsrprintf(_("could not read %s, starting with %s\n"),
551 leftofffile
, *fs
->dev
);
553 /* Ensure the buffer we read is null terminated */
554 buf
[SMBUFSZ
-1] = '\0';
555 for (fs
= fsbase
; fs
< fsend
; fs
++) {
557 if ((strncmp(buf
,fsname
,strlen(fsname
)) == 0)
558 && buf
[strlen(fsname
)] == ' ') {
566 ptr
= strchr(buf
, ' ');
568 startpass
= atoi(++ptr
);
569 ptr
= strchr(ptr
, ' ');
571 startino
= strtoull(++ptr
, NULL
, 10);
577 /* Init pass counts */
578 for (fsp
= fsbase
; fsp
< fs
; fsp
++) {
579 fsp
->npass
= startpass
+ 1;
581 for (fsp
= fs
; fsp
<= fsend
; fsp
++) {
582 fsp
->npass
= startpass
;
589 fsrprintf(_("START: pass=%d ino=%llu %s %s\n"),
590 fs
->npass
, (unsigned long long)startino
,
594 signal(SIGABRT
, aborter
);
595 signal(SIGHUP
, aborter
);
596 signal(SIGINT
, aborter
);
597 signal(SIGQUIT
, aborter
);
598 signal(SIGTERM
, aborter
);
600 /* reorg for 'howlong' -- checked in 'fsrfs' */
601 while (endtime
> time(0)) {
604 if (npasses
> 1 && !fs
->npass
)
611 fsrprintf(_("couldn't fork sub process:"));
615 error
= fsrfs(fs
->mnt
, startino
, TARGETRANGE
);
620 if (WIFEXITED(error
) && WEXITSTATUS(error
) == 1) {
621 /* child timed out & did fsrall_cleanup */
626 startino
= 0; /* reset after the first time through */
631 if (fs
->npass
== npasses
) {
632 fsrprintf(_("Completed all %d passes\n"), npasses
);
636 fsrall_cleanup(endtime
<= time(0));
640 * fsrall_cleanup -- close files, print next starting location, etc.
643 fsrall_cleanup(int timeout
)
652 fsrprintf(_("%s startpass %d, endpass %d, time %d seconds\n"),
653 progname
, startpass
, fs
->npass
,
654 time(0) - endtime
+ howlong
);
656 /* record where we left off */
657 fd
= open(leftofffile
, O_WRONLY
|O_CREAT
|O_EXCL
, 0644);
659 fsrprintf(_("open(%s) failed: %s\n"),
660 leftofffile
, strerror(errno
));
662 ret
= sprintf(buf
, "%s %d %llu\n", fs
->dev
,
663 fs
->npass
, (unsigned long long)leftoffino
);
664 if (write(fd
, buf
, ret
) < strlen(buf
))
665 fsrprintf(_("write(%s) failed: %s\n"),
666 leftofffile
, strerror(errno
));
673 * fsrfs -- reorganize a file system
676 fsrfs(char *mntdir
, xfs_ino_t startino
, int targetrange
)
683 xfs_bstat_t buf
[GRABSZ
];
686 jdm_fshandle_t
*fshandlep
;
687 xfs_ino_t lastino
= startino
;
689 fsrprintf(_("%s start inode=%llu\n"), mntdir
,
690 (unsigned long long)startino
);
692 fshandlep
= jdm_getfshandle( mntdir
);
694 fsrprintf(_("unable to get handle: %s: %s\n"),
695 mntdir
, strerror( errno
));
699 if ((fsfd
= open(mntdir
, O_RDONLY
)) < 0) {
700 fsrprintf(_("unable to open: %s: %s\n"),
701 mntdir
, strerror( errno
));
706 if (xfs_getgeom(fsfd
, &fsgeom
) < 0 ) {
707 fsrprintf(_("Skipping %s: could not get XFS geometry\n"),
716 while ((ret
= xfs_bulkstat(fsfd
,
717 &lastino
, GRABSZ
, &buf
[0], &buflenout
)) == 0) {
724 /* Each loop through, defrag targetrange percent of the files */
725 count
= (buflenout
* targetrange
) / 100;
727 qsort((char *)buf
, buflenout
, sizeof(struct xfs_bstat
), cmp
);
729 for (p
= buf
, endp
= (buf
+ buflenout
); p
< endp
; p
++) {
730 /* Do some obvious checks now */
731 if (((p
->bs_mode
& S_IFMT
) != S_IFREG
) ||
735 fd
= jdm_open(fshandlep
, p
, O_RDWR
|O_DIRECT
);
737 /* This probably means the file was
738 * removed while in progress of handling
739 * it. Just quietly ignore this file.
742 fsrprintf(_("could not open: "
743 "inode %llu\n"), p
->bs_ino
);
747 /* Don't know the pathname, so make up something */
748 sprintf(fname
, "ino=%lld", (long long)p
->bs_ino
);
750 /* Get a tmp file name */
751 tname
= tmp_next(mntdir
);
753 ret
= fsrfile_common(fname
, tname
, mntdir
, fd
, p
);
755 leftoffino
= p
->bs_ino
;
764 if (endtime
&& endtime
< time(0)) {
772 fsrprintf(_("%s: xfs_bulkstat: %s\n"), progname
, strerror(errno
));
781 * To compare bstat structs for qsort.
784 cmp(const void *s1
, const void *s2
)
786 return( ((xfs_bstat_t
*)s2
)->bs_extents
-
787 ((xfs_bstat_t
*)s1
)->bs_extents
);
792 * reorganize by directory hierarchy.
793 * Stay in dev (a restriction based on structure of this program -- either
794 * call efs_{n,u}mount() around each file, something smarter or this)
797 fsrdir(char *dirname
)
799 fsrprintf(_("%s: Directory defragmentation not supported\n"), dirname
);
803 * Sets up the defragmentation of a file based on the
804 * filepath. It collects the bstat information, does
805 * an open on the file and passes this all to fsrfile_common.
808 fsrfile(char *fname
, xfs_ino_t ino
)
811 jdm_fshandle_t
*fshandlep
;
812 int fd
= -1, fsfd
= -1;
816 fshandlep
= jdm_getfshandle(getparent (fname
) );
818 fsrprintf(_("unable to construct sys handle for %s: %s\n"),
819 fname
, strerror(errno
));
824 * Need to open something on the same filesystem as the
825 * file. Open the parent.
827 fsfd
= open(getparent(fname
), O_RDONLY
);
829 fsrprintf(_("unable to open sys handle for %s: %s\n"),
830 fname
, strerror(errno
));
834 if ((xfs_bulkstat_single(fsfd
, &ino
, &statbuf
)) < 0) {
835 fsrprintf(_("unable to get bstat on %s: %s\n"),
836 fname
, strerror(errno
));
840 fd
= jdm_open(fshandlep
, &statbuf
, O_RDWR
|O_DIRECT
);
842 fsrprintf(_("unable to open handle %s: %s\n"),
843 fname
, strerror(errno
));
847 /* Get the fs geometry */
848 if (xfs_getgeom(fsfd
, &fsgeom
) < 0 ) {
849 fsrprintf(_("Unable to get geom on fs for: %s\n"), fname
);
853 tname
= gettmpname(fname
);
856 error
= fsrfile_common(fname
, tname
, NULL
, fd
, &statbuf
);
870 * This is the common defrag code for either a full fs
871 * defragmentation or a single file. Check as much as
872 * possible with the file, fork a process to setuid to the
873 * target file owner's uid and defragment the file.
874 * This is done so the new extents created in a tmp file are
875 * reflected in the owners' quota without having to do any
876 * special code in the kernel. When the existing extents
877 * are removed, the quotas will be correct. It's ugly but
878 * it saves us from doing some quota re-construction in
879 * the extent swap. The price is that the defragmentation
880 * will fail if the owner of the target file is already at
897 fsrprintf("%s\n", fname
);
900 fsrprintf(_("sync failed: %s: %s\n"), fname
, strerror(errno
));
904 if (statp
->bs_size
== 0) {
906 fsrprintf(_("%s: zero size, ignoring\n"), fname
);
910 /* Check if a mandatory lock is set on the file to try and
911 * avoid blocking indefinitely on the reads later. Note that
912 * someone could still set a mandatory lock after this check
913 * but before all reads have completed to block fsr reads.
914 * This change just closes the window a bit.
916 if ( (statp
->bs_mode
& S_ISGID
) && ( ! (statp
->bs_mode
&S_IXGRP
) ) ) {
920 fl
.l_whence
= SEEK_SET
;
921 fl
.l_start
= (off_t
)0;
923 if ((fcntl(fd
, F_GETLK
, &fl
)) < 0 ) {
925 fsrprintf(_("locking check failed: %s\n"),
929 if (fl
.l_type
!= F_UNLCK
) {
930 /* Mandatory lock is set */
932 fsrprintf(_("mandatory lock: %s: ignoring\n"),
939 * Check if there is room to copy the file.
941 * Note that xfs_bstat.bs_blksize returns the filesystem blocksize,
942 * not the optimal I/O size as struct stat.
944 if (statvfs(fsname
? fsname
: fname
, &vfss
) < 0) {
945 fsrprintf(_("unable to get fs stat on %s: %s\n"),
946 fname
, strerror(errno
));
949 bsize
= vfss
.f_frsize
? vfss
.f_frsize
: vfss
.f_bsize
;
950 if (statp
->bs_blksize
* statp
->bs_blocks
>
951 vfss
.f_bfree
* bsize
- minimumfree
) {
952 fsrprintf(_("insufficient freespace for: %s: "
953 "size=%lld: ignoring\n"), fname
,
954 statp
->bs_blksize
* statp
->bs_blocks
);
958 if ((ioctl(fd
, FS_IOC_FSGETXATTR
, &fsx
)) < 0) {
959 fsrprintf(_("failed to get inode attrs: %s\n"), fname
);
962 if (fsx
.fsx_xflags
& (FS_XFLAG_IMMUTABLE
|FS_XFLAG_APPEND
)) {
964 fsrprintf(_("%s: immutable/append, ignoring\n"), fname
);
967 if (fsx
.fsx_xflags
& FS_XFLAG_NODEFRAG
) {
969 fsrprintf(_("%s: marked as don't defrag, ignoring\n"),
973 if (fsx
.fsx_xflags
& FS_XFLAG_REALTIME
) {
974 if (xfs_getrt(fd
, &vfss
) < 0) {
975 fsrprintf(_("cannot get realtime geometry for: %s\n"),
979 if (statp
->bs_size
> ((vfss
.f_bfree
* bsize
) - minimumfree
)) {
980 fsrprintf(_("low on realtime free space: %s: "
981 "ignoring file\n"), fname
);
986 if ((RealUid
!= ROOT
) && (RealUid
!= statp
->bs_uid
)) {
987 fsrprintf(_("cannot open: %s: Permission denied\n"), fname
);
992 * Previously the code forked here, & the child changed it's uid to
993 * that of the file's owner and then called packfile(), to keep
994 * quota counts correct. (defragged files could use fewer blocks).
996 * Instead, just fchown() the temp file to the uid,gid of the
997 * file we're defragging, in packfile().
1000 if ((error
= packfile(fname
, tname
, fd
, statp
, &fsx
)))
1002 return -1; /* no error */
1006 * Attempt to set the attr fork up correctly. This is simple for attr1
1007 * filesystems as they have a fixed inode fork offset. In that case
1008 * just create an attribute and that's all we need to do.
1010 * For attr2 filesystems, see if we have the actual fork offset in
1011 * the bstat structure. If so, just create additional attributes on
1012 * the temporary inode until the offset matches.
1014 * If it doesn't exist, we can only do best effort. Add an attribute at a time
1015 * to move the inode fork around, but take into account that the attribute
1016 * might be too small to move the fork every time we add one. This should
1017 * hopefully put the fork offset in the right place. It's not a big deal if we
1018 * don't get it right - the kernel will reject it when we try to swap extents.
1021 fsr_setup_attr_fork(
1024 xfs_bstat_t
*bstatp
)
1026 #ifdef HAVE_FSETXATTR
1027 struct stat tstatbuf
;
1030 int last_forkoff
= 0;
1031 int no_change_cnt
= 0;
1034 if (!(bstatp
->bs_xflags
& FS_XFLAG_HASATTR
))
1038 * use the old method if we have attr1 or the kernel does not yet
1039 * support passing the fork offset in the bulkstat data.
1041 if (!(fsgeom
.flags
& XFS_FSOP_GEOM_FLAGS_ATTR2
) ||
1042 bstatp
->bs_forkoff
== 0) {
1044 ret
= fsetxattr(tfd
, "user.X", "X", 1, XATTR_CREATE
);
1046 fsrprintf(_("could not set ATTR\n"));
1052 /* attr2 w/ fork offsets */
1054 if (fstat(tfd
, &tstatbuf
) < 0) {
1055 fsrprintf(_("unable to stat temp file: %s\n"),
1067 * bulkstat the temp inode to see what the forkoff is. Use
1068 * this to compare against the target and determine what we
1071 ino
= tstatbuf
.st_ino
;
1072 if ((xfs_bulkstat_single(tfd
, &ino
, &tbstat
)) < 0) {
1073 fsrprintf(_("unable to get bstat on temp file: %s\n"),
1078 fsrprintf(_("orig forkoff %d, temp forkoff %d\n"),
1079 bstatp
->bs_forkoff
, tbstat
.bs_forkoff
);
1080 diff
= tbstat
.bs_forkoff
- bstatp
->bs_forkoff
;
1082 /* if they are equal, we are done */
1086 snprintf(name
, sizeof(name
), "user.%d", i
);
1089 * If there is no attribute, then we need to create one to get
1090 * an attribute fork at the default location.
1092 if (!tbstat
.bs_forkoff
) {
1094 ret
= fsetxattr(tfd
, name
, "XX", 2, XATTR_CREATE
);
1096 fsrprintf(_("could not set ATTR\n"));
1100 } else if (i
== 0) {
1102 * First pass, and temp file already has an inline
1103 * xattr, probably due to selinux.
1105 * It's *possible* that the temp file attr area
1106 * is larger than the target file's:
1109 * +-------+ 0 +-------+ 0
1113 * | | v-------v forkoff
1115 * v-------v forkoff | Attr | local
1117 * +-------+ +-------+
1121 * If target attr area is less than the temp's
1122 * (diff < 0) write a big attr to the temp file to knock
1123 * the attr out of local format.
1124 * (This should actually *increase* the temp file's
1125 * forkoffset when the attr moves out of the inode)
1129 memset(val
, 'X', 2048);
1130 if (fsetxattr(tfd
, name
, val
, 2048, 0)) {
1131 fsrprintf(_("big ATTR set failed\n"));
1134 /* Go back & see where we're at now */
1140 * make a progress check so we don't get stuck trying to extend
1141 * a large btree form attribute fork.
1143 if (last_forkoff
== tbstat
.bs_forkoff
) {
1144 if (no_change_cnt
++ > 10)
1146 } else /* progress! */
1148 last_forkoff
= tbstat
.bs_forkoff
;
1150 /* work out which way to grow the fork */
1151 if (abs(diff
) > fsgeom
.inodesize
- sizeof(struct xfs_dinode
)) {
1152 fsrprintf(_("forkoff diff %d too large!\n"), diff
);
1157 * if the temp inode fork offset is still smaller then we have
1158 * to grow the data fork
1162 * create some temporary extents in the inode to move
1163 * the fork in the direction we need. This can be done
1164 * by preallocating some single block extents at
1165 * non-contiguous offsets.
1167 /* XXX: unimplemented! */
1169 printf(_("data fork growth unimplemented\n"));
1173 /* we need to grow the attr fork, so create another attr */
1174 ret
= fsetxattr(tfd
, name
, "XX", 2, XATTR_CREATE
);
1176 fsrprintf(_("could not set ATTR\n"));
1180 } while (++i
< 100); /* don't go forever */
1184 fsrprintf(_("set temp attr\n"));
1185 /* We failed to resolve the fork difference */
1187 fsrprintf(_("failed to match fork offset\n"));;
1189 #endif /* HAVE_FSETXATTR */
1194 * Do the defragmentation of a single file.
1195 * We already are pretty sure we can and want to
1196 * defragment the file. Create the tmp file, copy
1197 * the data (maintaining holes) and call the kernel
1198 * extent swap routine.
1201 * -1: Some error was encountered
1202 * 0: Successfully defragmented the file
1203 * 1: No change / No Error
1206 packfile(char *fname
, char *tname
, int fd
,
1207 xfs_bstat_t
*statp
, struct fsxattr
*fsxp
)
1211 int retval
= -1; /* Failure is the default */
1212 int nextents
, extent
, cur_nextents
, new_nextents
;
1216 static xfs_swapext_t sx
;
1217 struct xfs_flock64 space
;
1221 char ffname
[SMBUFSZ
];
1225 * Work out the extent map - nextents will be set to the
1226 * minimum number of extents needed for the file (taking
1227 * into account holes), cur_nextents is the current number
1230 nextents
= read_fd_bmap(fd
, statp
, &cur_nextents
);
1232 if (cur_nextents
== 1 || cur_nextents
<= nextents
) {
1234 fsrprintf(_("%s already fully defragmented.\n"), fname
);
1235 retval
= 1; /* indicates no change/no error */
1240 fsrprintf(_("%s extents=%d can_save=%d tmp=%s\n"),
1241 fname
, cur_nextents
, (cur_nextents
- nextents
),
1244 if ((tfd
= open(tname
, openopts
, 0666)) < 0) {
1246 fsrprintf(_("could not open tmp file: %s: %s\n"),
1247 tname
, strerror(errno
));
1252 /* Setup extended attributes */
1253 if (fsr_setup_attr_fork(fd
, tfd
, statp
) != 0) {
1254 fsrprintf(_("failed to set ATTR fork on tmp: %s:\n"), tname
);
1258 /* Setup extended inode flags, project identifier, etc */
1259 if (fsxp
->fsx_xflags
|| fsxp
->fsx_projid
) {
1260 if (ioctl(tfd
, FS_IOC_FSSETXATTR
, fsxp
) < 0) {
1261 fsrprintf(_("could not set inode attrs on tmp: %s\n"),
1267 if ((ioctl(tfd
, XFS_IOC_DIOINFO
, &dio
)) < 0 ) {
1268 fsrprintf(_("could not get DirectIO info on tmp: %s\n"), tname
);
1272 dio_min
= dio
.d_miniosz
;
1273 if (statp
->bs_size
<= dio_min
) {
1274 blksz_dio
= dio_min
;
1276 blksz_dio
= min(dio
.d_maxiosz
, BUFFER_MAX
- pagesize
);
1277 if (argv_blksz_dio
!= 0)
1278 blksz_dio
= min(argv_blksz_dio
, blksz_dio
);
1279 blksz_dio
= (min(statp
->bs_size
, blksz_dio
) / dio_min
) * dio_min
;
1283 fsrprintf(_("DEBUG: "
1284 "fsize=%lld blsz_dio=%d d_min=%d d_max=%d pgsz=%d\n"),
1285 statp
->bs_size
, blksz_dio
, dio
.d_miniosz
,
1286 dio
.d_maxiosz
, pagesize
);
1289 if (!(fbuf
= (char *)memalign(dio
.d_mem
, blksz_dio
))) {
1290 fsrprintf(_("could not allocate buf: %s\n"), tname
);
1295 /* Create new tmp file in same AG as first */
1296 sprintf(ffname
, "%s.frag", tname
);
1298 /* Open the new file for sync writes */
1299 if ((ffd
= open(ffname
, openopts
, 0666)) < 0) {
1300 fsrprintf(_("could not open fragfile: %s : %s\n"),
1301 ffname
, strerror(errno
));
1307 /* Loop through block map allocating new extents */
1308 for (extent
= 0; extent
< nextents
; extent
++) {
1309 pos
= outmap
[extent
].bmv_offset
;
1310 if (outmap
[extent
].bmv_block
== -1) {
1311 space
.l_whence
= SEEK_SET
;
1312 space
.l_start
= pos
;
1313 space
.l_len
= outmap
[extent
].bmv_length
;
1314 if (ioctl(tfd
, XFS_IOC_UNRESVSP64
, &space
) < 0) {
1315 fsrprintf(_("could not trunc tmp %s\n"),
1318 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1319 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1320 tname
, strerror(errno
));
1324 } else if (outmap
[extent
].bmv_length
== 0) {
1325 /* to catch holes at the beginning of the file */
1329 space
.l_whence
= SEEK_CUR
;
1331 space
.l_len
= outmap
[extent
].bmv_length
;
1333 if (ioctl(tfd
, XFS_IOC_RESVSP64
, &space
) < 0) {
1334 fsrprintf(_("could not pre-allocate tmp space:"
1338 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1339 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1340 tname
, strerror(errno
));
1344 } /* end of space allocation loop */
1346 if (lseek(tfd
, 0, SEEK_SET
)) {
1347 fsrprintf(_("Couldn't rewind on temporary file\n"));
1351 /* Check if the temporary file has fewer extents */
1352 new_nextents
= getnextents(tfd
);
1354 fsrprintf(_("Temporary file has %d extents (%d in original)\n"), new_nextents
, cur_nextents
);
1355 if (cur_nextents
<= new_nextents
) {
1357 fsrprintf(_("No improvement will be made (skipping): %s\n"), fname
);
1358 retval
= 1; /* no change/no error */
1362 /* Loop through block map copying the file. */
1363 for (extent
= 0; extent
< nextents
; extent
++) {
1364 pos
= outmap
[extent
].bmv_offset
;
1365 if (outmap
[extent
].bmv_block
== -1) {
1366 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1367 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1368 tname
, strerror(errno
));
1371 if (lseek(fd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1372 fsrprintf(_("could not lseek in file: %s : %s\n"),
1373 fname
, strerror(errno
));
1377 } else if (outmap
[extent
].bmv_length
== 0) {
1378 /* to catch holes at the beginning of the file */
1381 for (cnt
= outmap
[extent
].bmv_length
; cnt
> 0;
1382 cnt
-= ct
, pos
+= ct
) {
1383 if (nfrags
&& --nfrags
) {
1384 ct
= min(cnt
, dio_min
);
1385 } else if (cnt
% dio_min
== 0) {
1386 ct
= min(cnt
, blksz_dio
);
1388 ct
= min(cnt
+ dio_min
- (cnt
% dio_min
),
1391 ct
= read(fd
, fbuf
, ct
);
1393 /* EOF, stop trying to read */
1397 /* Ensure we do direct I/O to correct block
1400 if (ct
% dio_min
!= 0) {
1401 wc
= ct
+ dio_min
- (ct
% dio_min
);
1406 if (ct
< 0 || ((wc
= write(tfd
, fbuf
, wc
)) != wc_b4
)) {
1408 fsrprintf(_("bad read of %d bytes "
1409 "from %s: %s\n"), wc_b4
,
1410 fname
, strerror(errno
));
1412 fsrprintf(_("bad write of %d bytes "
1413 "to %s: %s\n"), wc_b4
,
1414 tname
, strerror(errno
));
1417 * Might be out of space
1419 * Try to finish write
1423 if ((wc
= write(tfd
, ((char *)fbuf
)+wc
,
1425 /* worked on second attempt? */
1429 fsrprintf(_("bad write2 of %d "
1430 "bytes to %s: %s\n"),
1434 fsrprintf(_("bad copy to %s\n"),
1441 /* Do a matching write to the tmp file */
1443 if (((wc
= write(ffd
, fbuf
, wc
)) != wc_b4
)) {
1444 fsrprintf(_("bad write of %d bytes "
1446 wc_b4
, ffname
, strerror(errno
));
1451 if (ftruncate(tfd
, statp
->bs_size
) < 0) {
1452 fsrprintf(_("could not truncate tmpfile: %s : %s\n"),
1453 fname
, strerror(errno
));
1456 if (fsync(tfd
) < 0) {
1457 fsrprintf(_("could not fsync tmpfile: %s : %s\n"),
1458 fname
, strerror(errno
));
1462 sx
.sx_stat
= *statp
; /* struct copy */
1463 sx
.sx_version
= XFS_SX_VERSION
;
1464 sx
.sx_fdtarget
= fd
;
1467 sx
.sx_length
= statp
->bs_size
;
1469 /* switch to the owner's id, to keep quota in line */
1470 if (fchown(tfd
, statp
->bs_uid
, statp
->bs_gid
) < 0) {
1472 fsrprintf(_("failed to fchown tmpfile %s: %s\n"),
1473 tname
, strerror(errno
));
1477 /* Swap the extents */
1478 srval
= xfs_swapext(fd
, &sx
);
1480 if (errno
== ENOTSUP
) {
1482 fsrprintf(_("%s: file type not supported\n"), fname
);
1483 } else if (errno
== EFAULT
) {
1484 /* The file has changed since we started the copy */
1486 fsrprintf(_("%s: file modified defrag aborted\n"),
1488 } else if (errno
== EBUSY
) {
1489 /* Timestamp has changed or mmap'ed file */
1491 fsrprintf(_("%s: file busy\n"), fname
);
1493 fsrprintf(_("XFS_IOC_SWAPEXT failed: %s: %s\n"),
1494 fname
, strerror(errno
));
1499 /* Report progress */
1501 fsrprintf(_("extents before:%d after:%d %s %s\n"),
1502 cur_nextents
, new_nextents
,
1503 (new_nextents
<= nextents
? "DONE" : " " ),
1517 gettmpname(char *fname
)
1519 static char buf
[PATH_MAX
+1];
1523 sprintf(sbuf
, "/.fsr%d", getpid());
1525 strncpy(buf
, fname
, PATH_MAX
);
1526 buf
[PATH_MAX
] = '\0';
1527 ptr
= strrchr(buf
, '/');
1534 if ((strlen(buf
) + strlen (sbuf
)) > PATH_MAX
) {
1535 fsrprintf(_("tmp file name too long: %s\n"), fname
);
1545 getparent(char *fname
)
1547 static char buf
[PATH_MAX
+1];
1550 strncpy(buf
, fname
, PATH_MAX
);
1551 buf
[PATH_MAX
] = '\0';
1552 ptr
= strrchr(buf
, '/');
1565 * Read in block map of the input file, coalesce contiguous
1566 * extents into a single range, keep all holes. Convert from 512 byte
1569 * This code was borrowed from mv.c with some minor mods.
1572 #define OUTMAP_SIZE_INCREMENT MAPSIZE
1574 int read_fd_bmap(int fd
, xfs_bstat_t
*sin
, int *cur_nextents
)
1577 struct getbmap map
[MAPSIZE
];
1580 if (++cnt >= outmap_size) { \
1581 outmap_size += OUTMAP_SIZE_INCREMENT; \
1582 outmap = (struct getbmap *)realloc(outmap, \
1583 outmap_size*sizeof(*outmap)); \
1584 if (outmap == NULL) { \
1585 fsrprintf(_("realloc failed: %s\n"), \
1591 /* Initialize the outmap array. It always grows - never shrinks.
1592 * Left-over memory allocation is saved for the next files.
1594 if (outmap_size
== 0) {
1595 outmap_size
= OUTMAP_SIZE_INCREMENT
; /* Initial size */
1596 outmap
= (struct getbmap
*)malloc(outmap_size
*sizeof(*outmap
));
1598 fsrprintf(_("malloc failed: %s\n"),
1604 outmap
[0].bmv_block
= 0;
1605 outmap
[0].bmv_offset
= 0;
1606 outmap
[0].bmv_length
= sin
->bs_size
;
1609 * If a non regular file is involved then forget holes
1612 if (!S_ISREG(sin
->bs_mode
))
1615 outmap
[0].bmv_length
= 0;
1617 map
[0].bmv_offset
= 0;
1618 map
[0].bmv_block
= 0;
1619 map
[0].bmv_entries
= 0;
1620 map
[0].bmv_count
= MAPSIZE
;
1621 map
[0].bmv_length
= -1;
1627 if (ioctl(fd
, XFS_IOC_GETBMAP
, map
) < 0) {
1628 fsrprintf(_("failed reading extents: inode %llu"),
1629 (unsigned long long)sin
->bs_ino
);
1633 /* Concatenate extents together and replicate holes into
1636 *cur_nextents
+= map
[0].bmv_entries
;
1637 for (i
= 0; i
< map
[0].bmv_entries
; i
++) {
1638 if (map
[i
+ 1].bmv_block
== -1) {
1640 outmap
[cnt
] = map
[i
+1];
1641 } else if (outmap
[cnt
].bmv_block
== -1) {
1643 outmap
[cnt
] = map
[i
+1];
1645 outmap
[cnt
].bmv_length
+= map
[i
+ 1].bmv_length
;
1648 } while (map
[0].bmv_entries
== (MAPSIZE
-1));
1649 for (i
= 0; i
<= cnt
; i
++) {
1650 outmap
[i
].bmv_offset
= BBTOB(outmap
[i
].bmv_offset
);
1651 outmap
[i
].bmv_length
= BBTOB(outmap
[i
].bmv_length
);
1654 outmap
[cnt
].bmv_length
= sin
->bs_size
- outmap
[cnt
].bmv_offset
;
1660 * Read the block map and return the number of extents.
1666 struct getbmap map
[MAPSIZE
];
1668 map
[0].bmv_offset
= 0;
1669 map
[0].bmv_block
= 0;
1670 map
[0].bmv_entries
= 0;
1671 map
[0].bmv_count
= MAPSIZE
;
1672 map
[0].bmv_length
= -1;
1677 if (ioctl(fd
,XFS_IOC_GETBMAP
, map
) < 0) {
1678 fsrprintf(_("failed reading extents"));
1682 nextents
+= map
[0].bmv_entries
;
1683 } while (map
[0].bmv_entries
== (MAPSIZE
-1));
1689 * Get the fs geometry
1692 xfs_getgeom(int fd
, xfs_fsop_geom_v1_t
* fsgeom
)
1694 if (xfs_fsgeometry(fd
, fsgeom
) < 0) {
1701 * Get xfs realtime space information
1704 xfs_getrt(int fd
, struct statvfs
*sfbp
)
1706 unsigned long bsize
;
1707 unsigned long factor
;
1708 xfs_fsop_counts_t cnt
;
1710 if (!fsgeom
.rtblocks
)
1713 if (xfs_fscounts(fd
, &cnt
) < 0) {
1717 bsize
= (sfbp
->f_frsize
? sfbp
->f_frsize
: sfbp
->f_bsize
);
1718 factor
= fsgeom
.blocksize
/ bsize
; /* currently this is == 1 */
1719 sfbp
->f_bfree
= (cnt
.freertx
* fsgeom
.rtextsize
) * factor
;
1724 fsrprintf(const char *fmt
, ...)
1730 static int didopenlog
;
1732 openlog("fsr", LOG_PID
, LOG_USER
);
1735 vsyslog(LOG_INFO
, fmt
, ap
);
1743 * Initialize a directory for tmp file use. This is used
1744 * by the full filesystem defragmentation when we're walking
1745 * the inodes and do not know the path for the individual
1746 * files. Multiple directories are used to spread out the
1747 * tmp data around to different ag's (since file data is
1748 * usually allocated to the same ag as the directory and
1749 * directories allocated round robin from the same
1750 * parent directory).
1756 static char buf
[SMBUFSZ
];
1760 sprintf(buf
, "%s/.fsr", mnt
);
1763 if (mkdir(buf
, 0700) < 0) {
1764 if (errno
== EEXIST
) {
1766 fsrprintf(_("tmpdir already exists: %s\n"),
1769 fsrprintf(_("could not create tmpdir: %s: %s\n"),
1770 buf
, strerror(errno
));
1774 for (i
=0; i
< fsgeom
.agcount
; i
++) {
1775 sprintf(buf
, "%s/.fsr/ag%d", mnt
, i
);
1776 if (mkdir(buf
, 0700) < 0) {
1777 if (errno
== EEXIST
) {
1780 _("tmpdir already exists: %s\n"), buf
);
1782 fsrprintf(_("cannot create tmpdir: %s: %s\n"),
1783 buf
, strerror(errno
));
1795 static char buf
[SMBUFSZ
];
1797 sprintf(buf
, "%s/.fsr/ag%d/tmp%d",
1798 ( (strcmp(mnt
, "/") == 0) ? "" : mnt
),
1802 if (++tmp_agi
== fsgeom
.agcount
)
1809 tmp_close(char *mnt
)
1811 static char buf
[SMBUFSZ
];
1814 /* No data is ever actually written so we can just do rmdir's */
1815 for (i
=0; i
< fsgeom
.agcount
; i
++) {
1816 sprintf(buf
, "%s/.fsr/ag%d", mnt
, i
);
1817 if (rmdir(buf
) < 0) {
1818 if (errno
!= ENOENT
) {
1820 _("could not remove tmpdir: %s: %s\n"),
1821 buf
, strerror(errno
));
1825 sprintf(buf
, "%s/.fsr", mnt
);
1826 if (rmdir(buf
) < 0) {
1827 if (errno
!= ENOENT
) {
1828 fsrprintf(_("could not remove tmpdir: %s: %s\n"),
1829 buf
, strerror(errno
));