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>
35 #ifndef XFS_XFLAG_NODEFRAG
36 #define XFS_XFLAG_NODEFRAG 0x00002000 /* src dependancy, remove later */
39 #define _PATH_FSRLAST "/var/tmp/.fsrlast_xfs"
40 #define _PATH_PROC_MOUNTS "/proc/mounts"
48 /* static int nflag; */
50 /* static int sflag; */
52 extern int max_ext_size
;
53 static int npasses
= 10;
54 static int startpass
= 0;
56 struct getbmap
*outmap
= NULL
;
60 static __int64_t minimumfree
= 2048;
62 #define MNTTYPE_XFS "xfs"
68 #define TARGETRANGE 10
72 #define BUFFER_SIZE (1<<16)
73 #define BUFFER_MAX (1<<24)
75 static time_t howlong
= 7200; /* default seconds of reorganizing */
76 static char *leftofffile
= _PATH_FSRLAST
; /* where we left off last */
77 static time_t endtime
;
78 static time_t starttime
;
79 static xfs_ino_t leftoffino
= 0;
83 static int fsrfile(char *fname
, xfs_ino_t ino
);
84 static int fsrfile_common( char *fname
, char *tname
, char *mnt
,
85 int fd
, xfs_bstat_t
*statp
);
86 static int packfile(char *fname
, char *tname
, int fd
,
87 xfs_bstat_t
*statp
, struct fsxattr
*fsxp
);
88 static void fsrdir(char *dirname
);
89 static int fsrfs(char *mntdir
, xfs_ino_t ino
, int targetrange
);
90 static void initallfs(char *mtab
);
91 static void fsrallfs(char *mtab
, int howlong
, char *leftofffile
);
92 static void fsrall_cleanup(int timeout
);
93 static int getnextents(int);
94 int xfsrtextsize(int fd
);
95 int xfs_getrt(int fd
, struct statvfs64
*sfbp
);
96 char * gettmpname(char *fname
);
97 char * getparent(char *fname
);
98 int fsrprintf(const char *fmt
, ...);
99 int read_fd_bmap(int, xfs_bstat_t
*, int *);
100 int cmp(const void *, const void *);
101 static void tmp_init(char *mnt
);
102 static char * tmp_next(char *mnt
);
103 static void tmp_close(char *mnt
);
104 int xfs_getgeom(int , xfs_fsop_geom_v1_t
* );
106 xfs_fsop_geom_v1_t fsgeom
; /* geometry of active mounted system */
111 typedef struct fsdesc
{
117 fsdesc_t
*fs
, *fsbase
, *fsend
;
118 int fsbufsize
= 10; /* A starting value */
119 int nfrags
= 0; /* Debug option: Coerse into specific number
121 int openopts
= O_CREAT
|O_EXCL
|O_RDWR
|O_DIRECT
;
124 xfs_fsgeometry(int fd
, xfs_fsop_geom_v1_t
*geom
)
126 return ioctl(fd
, XFS_IOC_FSGEOMETRY_V1
, geom
);
130 xfs_bulkstat_single(int fd
, xfs_ino_t
*lastip
, xfs_bstat_t
*ubuffer
)
132 xfs_fsop_bulkreq_t bulkreq
;
134 bulkreq
.lastip
= (__u64
*)lastip
;
136 bulkreq
.ubuffer
= ubuffer
;
137 bulkreq
.ocount
= NULL
;
138 return ioctl(fd
, XFS_IOC_FSBULKSTAT_SINGLE
, &bulkreq
);
142 xfs_bulkstat(int fd
, xfs_ino_t
*lastip
, int icount
,
143 xfs_bstat_t
*ubuffer
, __s32
*ocount
)
145 xfs_fsop_bulkreq_t bulkreq
;
147 bulkreq
.lastip
= (__u64
*)lastip
;
148 bulkreq
.icount
= icount
;
149 bulkreq
.ubuffer
= ubuffer
;
150 bulkreq
.ocount
= ocount
;
151 return ioctl(fd
, XFS_IOC_FSBULKSTAT
, &bulkreq
);
155 xfs_swapext(int fd
, xfs_swapext_t
*sx
)
157 return ioctl(fd
, XFS_IOC_SWAPEXT
, sx
);
161 xfs_fscounts(int fd
, xfs_fsop_counts_t
*counts
)
163 return ioctl(fd
, XFS_IOC_FSCOUNTS
, counts
);
174 * Check if the argument is either the device name or mountpoint of an XFS
175 * filesystem. Note that we do not care about bind mounted regular files
176 * here - the code that handles defragmentation of invidual files takes care
180 find_mountpoint_check(struct stat64
*sb
, struct mntent
*t
)
184 if (S_ISDIR(sb
->st_mode
)) { /* mount point */
185 if (stat64(t
->mnt_dir
, &ms
) < 0)
187 if (sb
->st_ino
!= ms
.st_ino
)
189 if (sb
->st_dev
!= ms
.st_dev
)
191 if (strcmp(t
->mnt_type
, MNTTYPE_XFS
) != 0)
193 } else { /* device */
194 if (stat64(t
->mnt_fsname
, &ms
) < 0)
196 if (sb
->st_rdev
!= ms
.st_rdev
)
198 if (strcmp(t
->mnt_type
, MNTTYPE_XFS
) != 0)
201 * Make sure the mountpoint given by mtab is accessible
204 if (stat64(t
->mnt_dir
, &ms
) < 0)
212 find_mountpoint(char *mtab
, char *argname
, struct stat64
*sb
)
214 struct mntent_cursor cursor
;
215 struct mntent
*t
= NULL
;
218 if (platform_mntent_open(&cursor
, mtab
) != 0){
219 fprintf(stderr
, "Error: can't get mntent entries.\n");
223 while ((t
= platform_mntent_next(&cursor
)) != NULL
) {
224 mntp
= find_mountpoint_check(sb
, t
);
229 platform_mntent_close(&cursor
);
234 main(int argc
, char **argv
)
243 progname
= basename(argv
[0]);
245 setlocale(LC_ALL
, "");
246 bindtextdomain(PACKAGE
, LOCALEDIR
);
251 while ((c
= getopt(argc
, argv
, "C:p:e:MgsdnvTt:f:m:b:N:FV")) != -1) {
268 case 's': /* frag stats only */
271 _("%s: Stats not yet supported for XFS\n"),
276 howlong
= atoi(optarg
);
279 leftofffile
= optarg
;
285 argv_blksz_dio
= atoi(optarg
);
288 npasses
= atoi(optarg
);
291 /* Testing opt: coerses frag count in result */
292 if (getenv("FSRXFSTEST") != NULL
) {
293 nfrags
= atoi(optarg
);
298 printf(_("%s version %s\n"), progname
, VERSION
);
306 * If the user did not specify an explicit mount table, try to use
307 * /proc/mounts if it is available, else /etc/mtab. We prefer
308 * /proc/mounts because it is kernel controlled, while /etc/mtab
309 * may contain garbage that userspace tools like pam_mounts wrote
313 if (access(_PATH_PROC_MOUNTS
, R_OK
) == 0)
314 mtab
= _PATH_PROC_MOUNTS
;
316 mtab
= _PATH_MOUNTED
;
320 setbuf(stdout
, NULL
);
324 /* Save the caller's real uid */
327 pagesize
= getpagesize();
330 for (; optind
< argc
; optind
++) {
331 argname
= argv
[optind
];
333 if (lstat64(argname
, &sb
) < 0) {
335 _("%s: could not stat: %s: %s\n"),
336 progname
, argname
, strerror(errno
));
340 if (S_ISLNK(sb
.st_mode
)) {
343 if (stat64(argname
, &sb2
) == 0 &&
344 (S_ISBLK(sb2
.st_mode
) ||
345 S_ISCHR(sb2
.st_mode
)))
349 mntp
= find_mountpoint(mtab
, argname
, &sb
);
352 } else if (S_ISCHR(sb
.st_mode
)) {
354 "%s: char special not supported: %s\n"),
357 } else if (S_ISDIR(sb
.st_mode
) || S_ISREG(sb
.st_mode
)) {
358 if (!platform_test_xfs_path(argname
)) {
360 "%s: cannot defragment: %s: Not XFS\n"),
364 if (S_ISDIR(sb
.st_mode
))
367 fsrfile(argname
, sb
.st_ino
);
370 _("%s: not fsys dev, dir, or reg file, ignoring\n"),
376 fsrallfs(mtab
, howlong
, leftofffile
);
385 "Usage: %s [-d] [-v] [-g] [-t time] [-p passes] [-f leftf] [-m mtab]\n"
386 " %s [-d] [-v] [-g] xfsdev | dir | file ...\n"
389 " -g Print to syslog (default if stdout not a tty).\n"
390 " -t time How long to run in seconds.\n"
391 " -p passes Number of passes before terminating global re-org.\n"
392 " -f leftoff Use this instead of %s.\n"
393 " -m mtab Use something other than /etc/mtab.\n"
394 " -d Debug, print even more.\n"
395 " -v Verbose, more -v's more verbose.\n"
396 " -V Print version number and exit.\n"
397 ), progname
, progname
, progname
, _PATH_FSRLAST
);
402 * initallfs -- read the mount table and set up an internal form
405 initallfs(char *mtab
)
407 struct mntent_cursor cursor
;
408 struct mntent
*mnt
= NULL
;
413 /* malloc a number of descriptors, increased later if needed */
414 if (!(fsbase
= (fsdesc_t
*)malloc(fsbufsize
* sizeof(fsdesc_t
)))) {
415 fsrprintf(_("out of memory: %s\n"), strerror(errno
));
418 fsend
= (fsbase
+ fsbufsize
- 1);
420 /* find all rw xfs file systems */
424 if (platform_mntent_open(&cursor
, mtab
) != 0){
425 fprintf(stderr
, "Error: can't get mntent entries.\n");
429 while ((mnt
= platform_mntent_next(&cursor
)) != NULL
) {
432 if (strcmp(mnt
->mnt_type
, MNTTYPE_XFS
) != 0 ||
433 stat64(mnt
->mnt_fsname
, &sb
) == -1 ||
434 !S_ISBLK(sb
.st_mode
))
437 cp
= strtok(mnt
->mnt_opts
,",");
439 if (strcmp("rw", cp
) == 0)
441 } while ((cp
= strtok(NULL
, ",")) != NULL
);
444 fsrprintf(_("Skipping %s: not mounted rw\n"),
449 if (mi
== fsbufsize
) {
451 if ((fsbase
= (fsdesc_t
*)realloc((char *)fsbase
,
452 fsbufsize
* sizeof(fsdesc_t
))) == NULL
) {
453 fsrprintf(_("out of memory: %s\n"),
458 fsrprintf(_("out of memory on realloc: %s\n"),
462 fs
= (fsbase
+ mi
); /* Needed ? */
465 fs
->dev
= strdup(mnt
->mnt_fsname
);
466 fs
->mnt
= strdup(mnt
->mnt_dir
);
468 if (fs
->dev
== NULL
) {
469 fsrprintf(_("strdup(%s) failed\n"), mnt
->mnt_fsname
);
472 if (fs
->mnt
== NULL
) {
473 fsrprintf(_("strdup(%s) failed\n"), mnt
->mnt_dir
);
479 platform_mntent_close(&cursor
);
482 fsend
= (fsbase
+ numfs
);
484 fsrprintf(_("no rw xfs file systems in mtab: %s\n"), mtab
);
487 if (vflag
|| dflag
) {
488 fsrprintf(_("Found %d mounted, writable, XFS filesystems\n"),
491 for (fs
= fsbase
; fs
< fsend
; fs
++)
492 fsrprintf("\t%-30.30s%-30.30s\n", fs
->dev
, fs
->mnt
);
497 fsrallfs(char *mtab
, int howlong
, char *leftofffile
)
506 xfs_ino_t startino
= 0;
508 struct stat64 sb
, sb2
;
510 fsrprintf("xfs_fsr -m %s -t %d -f %s ...\n", mtab
, howlong
, leftofffile
);
512 endtime
= starttime
+ howlong
;
515 /* where'd we leave off last time? */
516 if (lstat64(leftofffile
, &sb
) == 0) {
517 if ( (fd
= open(leftofffile
, O_RDONLY
)) == -1 ) {
518 fsrprintf(_("%s: open failed\n"), leftofffile
);
520 else if ( fstat64(fd
, &sb2
) == 0) {
522 * Verify that lstat & fstat point to the
523 * same regular file (no links/no quick spoofs)
525 if ( (sb
.st_dev
!= sb2
.st_dev
) ||
526 (sb
.st_ino
!= sb2
.st_ino
) ||
527 ((sb
.st_mode
& S_IFMT
) != S_IFREG
) ||
528 ((sb2
.st_mode
& S_IFMT
) != S_IFREG
) ||
529 (sb2
.st_uid
!= ROOT
) ||
533 fsrprintf(_("Can't use %s: mode=0%o own=%d"
535 leftofffile
, sb
.st_mode
,
536 sb
.st_uid
, sb
.st_nlink
);
551 if (read(fd
, buf
, SMBUFSZ
) == -1) {
553 fsrprintf(_("could not read %s, starting with %s\n"),
554 leftofffile
, *fs
->dev
);
556 /* Ensure the buffer we read is null terminated */
557 buf
[SMBUFSZ
-1] = '\0';
558 for (fs
= fsbase
; fs
< fsend
; fs
++) {
560 if ((strncmp(buf
,fsname
,strlen(fsname
)) == 0)
561 && buf
[strlen(fsname
)] == ' ') {
569 ptr
= strchr(buf
, ' ');
571 startpass
= atoi(++ptr
);
572 ptr
= strchr(ptr
, ' ');
574 startino
= strtoull(++ptr
, NULL
, 10);
580 /* Init pass counts */
581 for (fsp
= fsbase
; fsp
< fs
; fsp
++) {
582 fsp
->npass
= startpass
+ 1;
584 for (fsp
= fs
; fsp
<= fsend
; fsp
++) {
585 fsp
->npass
= startpass
;
592 fsrprintf(_("START: pass=%d ino=%llu %s %s\n"),
593 fs
->npass
, (unsigned long long)startino
,
597 signal(SIGABRT
, aborter
);
598 signal(SIGHUP
, aborter
);
599 signal(SIGINT
, aborter
);
600 signal(SIGQUIT
, aborter
);
601 signal(SIGTERM
, aborter
);
603 /* reorg for 'howlong' -- checked in 'fsrfs' */
604 while (endtime
> time(0)) {
608 if (fs
->npass
== npasses
) {
609 fsrprintf(_("Completed all %d passes\n"), npasses
);
612 if (npasses
> 1 && !fs
->npass
)
619 fsrprintf(_("couldn't fork sub process:"));
623 error
= fsrfs(fs
->mnt
, startino
, TARGETRANGE
);
628 if (WIFEXITED(error
) && WEXITSTATUS(error
) == 1) {
629 /* child timed out & did fsrall_cleanup */
634 startino
= 0; /* reset after the first time through */
638 fsrall_cleanup(endtime
<= time(0));
642 * fsrall_cleanup -- close files, print next starting location, etc.
645 fsrall_cleanup(int timeout
)
654 fsrprintf(_("%s startpass %d, endpass %d, time %d seconds\n"),
655 progname
, startpass
, fs
->npass
,
656 time(0) - endtime
+ howlong
);
658 /* record where we left off */
659 fd
= open(leftofffile
, O_WRONLY
|O_CREAT
|O_EXCL
, 0644);
661 fsrprintf(_("open(%s) failed: %s\n"),
662 leftofffile
, strerror(errno
));
664 ret
= sprintf(buf
, "%s %d %llu\n", fs
->dev
,
665 fs
->npass
, (unsigned long long)leftoffino
);
666 if (write(fd
, buf
, ret
) < strlen(buf
))
667 fsrprintf(_("write(%s) failed: %s\n"),
668 leftofffile
, strerror(errno
));
675 * fsrfs -- reorganize a file system
678 fsrfs(char *mntdir
, xfs_ino_t startino
, int targetrange
)
685 xfs_bstat_t buf
[GRABSZ
];
688 jdm_fshandle_t
*fshandlep
;
689 xfs_ino_t lastino
= startino
;
691 fsrprintf(_("%s start inode=%llu\n"), mntdir
,
692 (unsigned long long)startino
);
694 fshandlep
= jdm_getfshandle( mntdir
);
696 fsrprintf(_("unable to get handle: %s: %s\n"),
697 mntdir
, strerror( errno
));
701 if ((fsfd
= open(mntdir
, O_RDONLY
)) < 0) {
702 fsrprintf(_("unable to open: %s: %s\n"),
703 mntdir
, strerror( errno
));
708 if (xfs_getgeom(fsfd
, &fsgeom
) < 0 ) {
709 fsrprintf(_("Skipping %s: could not get XFS geometry\n"),
718 while ((ret
= xfs_bulkstat(fsfd
,
719 &lastino
, GRABSZ
, &buf
[0], &buflenout
)) == 0) {
726 /* Each loop through, defrag targetrange percent of the files */
727 count
= (buflenout
* targetrange
) / 100;
729 qsort((char *)buf
, buflenout
, sizeof(struct xfs_bstat
), cmp
);
731 for (p
= buf
, endp
= (buf
+ buflenout
); p
< endp
; p
++) {
732 /* Do some obvious checks now */
733 if (((p
->bs_mode
& S_IFMT
) != S_IFREG
) ||
737 fd
= jdm_open(fshandlep
, p
, O_RDWR
|O_DIRECT
);
739 /* This probably means the file was
740 * removed while in progress of handling
741 * it. Just quietly ignore this file.
744 fsrprintf(_("could not open: "
745 "inode %llu\n"), p
->bs_ino
);
749 /* Don't know the pathname, so make up something */
750 sprintf(fname
, "ino=%lld", (long long)p
->bs_ino
);
752 /* Get a tmp file name */
753 tname
= tmp_next(mntdir
);
755 ret
= fsrfile_common(fname
, tname
, mntdir
, fd
, p
);
757 leftoffino
= p
->bs_ino
;
766 if (endtime
&& endtime
< time(0)) {
774 fsrprintf(_("%s: xfs_bulkstat: %s\n"), progname
, strerror(errno
));
783 * To compare bstat structs for qsort.
786 cmp(const void *s1
, const void *s2
)
788 return( ((xfs_bstat_t
*)s2
)->bs_extents
-
789 ((xfs_bstat_t
*)s1
)->bs_extents
);
794 * reorganize by directory hierarchy.
795 * Stay in dev (a restriction based on structure of this program -- either
796 * call efs_{n,u}mount() around each file, something smarter or this)
799 fsrdir(char *dirname
)
801 fsrprintf(_("%s: Directory defragmentation not supported\n"), dirname
);
805 * Sets up the defragmentation of a file based on the
806 * filepath. It collects the bstat information, does
807 * an open on the file and passes this all to fsrfile_common.
810 fsrfile(char *fname
, xfs_ino_t ino
)
813 jdm_fshandle_t
*fshandlep
;
814 int fd
= -1, fsfd
= -1;
818 fshandlep
= jdm_getfshandle(getparent (fname
) );
820 fsrprintf(_("unable to construct sys handle for %s: %s\n"),
821 fname
, strerror(errno
));
826 * Need to open something on the same filesystem as the
827 * file. Open the parent.
829 fsfd
= open(getparent(fname
), O_RDONLY
);
831 fsrprintf(_("unable to open sys handle for %s: %s\n"),
832 fname
, strerror(errno
));
836 if ((xfs_bulkstat_single(fsfd
, &ino
, &statbuf
)) < 0) {
837 fsrprintf(_("unable to get bstat on %s: %s\n"),
838 fname
, strerror(errno
));
842 fd
= jdm_open(fshandlep
, &statbuf
, O_RDWR
|O_DIRECT
);
844 fsrprintf(_("unable to open handle %s: %s\n"),
845 fname
, strerror(errno
));
849 /* Get the fs geometry */
850 if (xfs_getgeom(fsfd
, &fsgeom
) < 0 ) {
851 fsrprintf(_("Unable to get geom on fs for: %s\n"), fname
);
855 tname
= gettmpname(fname
);
858 error
= fsrfile_common(fname
, tname
, NULL
, fd
, &statbuf
);
872 * This is the common defrag code for either a full fs
873 * defragmentation or a single file. Check as much as
874 * possible with the file, fork a process to setuid to the
875 * target file owner's uid and defragment the file.
876 * This is done so the new extents created in a tmp file are
877 * reflected in the owners' quota without having to do any
878 * special code in the kernel. When the existing extents
879 * are removed, the quotas will be correct. It's ugly but
880 * it saves us from doing some quota re-construction in
881 * the extent swap. The price is that the defragmentation
882 * will fail if the owner of the target file is already at
894 struct statvfs64 vfss
;
899 fsrprintf("%s\n", fname
);
902 fsrprintf(_("sync failed: %s: %s\n"), fname
, strerror(errno
));
906 if (statp
->bs_size
== 0) {
908 fsrprintf(_("%s: zero size, ignoring\n"), fname
);
912 /* Check if a mandatory lock is set on the file to try and
913 * avoid blocking indefinitely on the reads later. Note that
914 * someone could still set a mandatory lock after this check
915 * but before all reads have completed to block fsr reads.
916 * This change just closes the window a bit.
918 if ( (statp
->bs_mode
& S_ISGID
) && ( ! (statp
->bs_mode
&S_IXGRP
) ) ) {
922 fl
.l_whence
= SEEK_SET
;
923 fl
.l_start
= (off_t
)0;
925 if ((fcntl(fd
, F_GETLK
, &fl
)) < 0 ) {
927 fsrprintf(_("locking check failed: %s\n"),
931 if (fl
.l_type
!= F_UNLCK
) {
932 /* Mandatory lock is set */
934 fsrprintf(_("mandatory lock: %s: ignoring\n"),
941 * Check if there is room to copy the file.
943 * Note that xfs_bstat.bs_blksize returns the filesystem blocksize,
944 * not the optimal I/O size as struct stat.
946 if (statvfs64(fsname
? fsname
: fname
, &vfss
) < 0) {
947 fsrprintf(_("unable to get fs stat on %s: %s\n"),
948 fname
, strerror(errno
));
952 bsize
= vfss
.f_frsize
? vfss
.f_frsize
: vfss
.f_bsize
;
954 bsize
= vfss
.f_bsize
;
956 if (statp
->bs_blksize
* statp
->bs_blocks
>
957 vfss
.f_bfree
* bsize
- minimumfree
) {
958 fsrprintf(_("insufficient freespace for: %s: "
959 "size=%lld: ignoring\n"), fname
,
960 statp
->bs_blksize
* statp
->bs_blocks
);
964 if ((ioctl(fd
, XFS_IOC_FSGETXATTR
, &fsx
)) < 0) {
965 fsrprintf(_("failed to get inode attrs: %s\n"), fname
);
968 if (fsx
.fsx_xflags
& (XFS_XFLAG_IMMUTABLE
|XFS_XFLAG_APPEND
)) {
970 fsrprintf(_("%s: immutable/append, ignoring\n"), fname
);
973 if (fsx
.fsx_xflags
& XFS_XFLAG_NODEFRAG
) {
975 fsrprintf(_("%s: marked as don't defrag, ignoring\n"),
979 if (fsx
.fsx_xflags
& XFS_XFLAG_REALTIME
) {
980 if (xfs_getrt(fd
, &vfss
) < 0) {
981 fsrprintf(_("cannot get realtime geometry for: %s\n"),
985 if (statp
->bs_size
> ((vfss
.f_bfree
* bsize
) - minimumfree
)) {
986 fsrprintf(_("low on realtime free space: %s: "
987 "ignoring file\n"), fname
);
992 if ((RealUid
!= ROOT
) && (RealUid
!= statp
->bs_uid
)) {
993 fsrprintf(_("cannot open: %s: Permission denied\n"), fname
);
998 * Previously the code forked here, & the child changed it's uid to
999 * that of the file's owner and then called packfile(), to keep
1000 * quota counts correct. (defragged files could use fewer blocks).
1002 * Instead, just fchown() the temp file to the uid,gid of the
1003 * file we're defragging, in packfile().
1006 if ((error
= packfile(fname
, tname
, fd
, statp
, &fsx
)))
1008 return -1; /* no error */
1012 * Attempt to set the attr fork up correctly. This is simple for attr1
1013 * filesystems as they have a fixed inode fork offset. In that case
1014 * just create an attribute and that's all we need to do.
1016 * For attr2 filesystems, see if we have the actual fork offset in
1017 * the bstat structure. If so, just create additional attributes on
1018 * the temporary inode until the offset matches.
1020 * If it doesn't exist, we can only do best effort. Add an attribute at a time
1021 * to move the inode fork around, but take into account that the attribute
1022 * might be too small to move the fork every time we add one. This should
1023 * hopefully put the fork offset in the right place. It's not a big deal if we
1024 * don't get it right - the kernel will reject it when we try to swap extents.
1027 fsr_setup_attr_fork(
1030 xfs_bstat_t
*bstatp
)
1032 #ifdef HAVE_FSETXATTR
1033 struct stat64 tstatbuf
;
1036 int last_forkoff
= 0;
1037 int no_change_cnt
= 0;
1040 if (!(bstatp
->bs_xflags
& XFS_XFLAG_HASATTR
))
1044 * use the old method if we have attr1 or the kernel does not yet
1045 * support passing the fork offset in the bulkstat data.
1047 if (!(fsgeom
.flags
& XFS_FSOP_GEOM_FLAGS_ATTR2
) ||
1048 bstatp
->bs_forkoff
== 0) {
1050 ret
= fsetxattr(tfd
, "user.X", "X", 1, XATTR_CREATE
);
1052 fsrprintf(_("could not set ATTR\n"));
1058 /* attr2 w/ fork offsets */
1060 if (fstat64(tfd
, &tstatbuf
) < 0) {
1061 fsrprintf(_("unable to stat temp file: %s\n"),
1073 * bulkstat the temp inode to see what the forkoff is. Use
1074 * this to compare against the target and determine what we
1077 ino
= tstatbuf
.st_ino
;
1078 if ((xfs_bulkstat_single(tfd
, &ino
, &tbstat
)) < 0) {
1079 fsrprintf(_("unable to get bstat on temp file: %s\n"),
1084 fsrprintf(_("orig forkoff %d, temp forkoff %d\n"),
1085 bstatp
->bs_forkoff
, tbstat
.bs_forkoff
);
1086 diff
= tbstat
.bs_forkoff
- bstatp
->bs_forkoff
;
1088 /* if they are equal, we are done */
1092 snprintf(name
, sizeof(name
), "user.%d", i
);
1095 * If there is no attribute, then we need to create one to get
1096 * an attribute fork at the default location.
1098 if (!tbstat
.bs_forkoff
) {
1100 ret
= fsetxattr(tfd
, name
, "XX", 2, XATTR_CREATE
);
1102 fsrprintf(_("could not set ATTR\n"));
1106 } else if (i
== 0) {
1108 * First pass, and temp file already has an inline
1109 * xattr, probably due to selinux.
1111 * It's *possible* that the temp file attr area
1112 * is larger than the target file's:
1115 * +-------+ 0 +-------+ 0
1119 * | | v-------v forkoff
1121 * v-------v forkoff | Attr | local
1123 * +-------+ +-------+
1127 * If target attr area is less than the temp's
1128 * (diff < 0) write a big attr to the temp file to knock
1129 * the attr out of local format.
1130 * (This should actually *increase* the temp file's
1131 * forkoffset when the attr moves out of the inode)
1135 memset(val
, 'X', 2048);
1136 if (fsetxattr(tfd
, name
, val
, 2048, 0)) {
1137 fsrprintf(_("big ATTR set failed\n"));
1140 /* Go back & see where we're at now */
1146 * make a progress check so we don't get stuck trying to extend
1147 * a large btree form attribute fork.
1149 if (last_forkoff
== tbstat
.bs_forkoff
) {
1150 if (no_change_cnt
++ > 10)
1152 } else /* progress! */
1154 last_forkoff
= tbstat
.bs_forkoff
;
1156 /* work out which way to grow the fork */
1157 if (abs(diff
) > fsgeom
.inodesize
- sizeof(struct xfs_dinode
)) {
1158 fsrprintf(_("forkoff diff %d too large!\n"), diff
);
1163 * if the temp inode fork offset is still smaller then we have
1164 * to grow the data fork
1168 * create some temporary extents in the inode to move
1169 * the fork in the direction we need. This can be done
1170 * by preallocating some single block extents at
1171 * non-contiguous offsets.
1173 /* XXX: unimplemented! */
1175 printf(_("data fork growth unimplemented\n"));
1179 /* we need to grow the attr fork, so create another attr */
1180 ret
= fsetxattr(tfd
, name
, "XX", 2, XATTR_CREATE
);
1182 fsrprintf(_("could not set ATTR\n"));
1186 } while (++i
< 100); /* don't go forever */
1190 fsrprintf(_("set temp attr\n"));
1191 /* We failed to resolve the fork difference */
1193 fsrprintf(_("failed to match fork offset\n"));;
1195 #endif /* HAVE_FSETXATTR */
1200 * Do the defragmentation of a single file.
1201 * We already are pretty sure we can and want to
1202 * defragment the file. Create the tmp file, copy
1203 * the data (maintaining holes) and call the kernel
1204 * extent swap routine.
1207 * -1: Some error was encountered
1208 * 0: Successfully defragmented the file
1209 * 1: No change / No Error
1212 packfile(char *fname
, char *tname
, int fd
,
1213 xfs_bstat_t
*statp
, struct fsxattr
*fsxp
)
1217 int retval
= -1; /* Failure is the default */
1218 int nextents
, extent
, cur_nextents
, new_nextents
;
1222 static xfs_swapext_t sx
;
1223 struct xfs_flock64 space
;
1227 char ffname
[SMBUFSZ
];
1231 * Work out the extent map - nextents will be set to the
1232 * minimum number of extents needed for the file (taking
1233 * into account holes), cur_nextents is the current number
1236 nextents
= read_fd_bmap(fd
, statp
, &cur_nextents
);
1238 if (cur_nextents
== 1 || cur_nextents
<= nextents
) {
1240 fsrprintf(_("%s already fully defragmented.\n"), fname
);
1241 retval
= 1; /* indicates no change/no error */
1246 fsrprintf(_("%s extents=%d can_save=%d tmp=%s\n"),
1247 fname
, cur_nextents
, (cur_nextents
- nextents
),
1250 if ((tfd
= open(tname
, openopts
, 0666)) < 0) {
1252 fsrprintf(_("could not open tmp file: %s: %s\n"),
1253 tname
, strerror(errno
));
1258 /* Setup extended attributes */
1259 if (fsr_setup_attr_fork(fd
, tfd
, statp
) != 0) {
1260 fsrprintf(_("failed to set ATTR fork on tmp: %s:\n"), tname
);
1264 /* Setup extended inode flags, project identifier, etc */
1265 if (fsxp
->fsx_xflags
|| fsxp
->fsx_projid
) {
1266 if (ioctl(tfd
, XFS_IOC_FSSETXATTR
, fsxp
) < 0) {
1267 fsrprintf(_("could not set inode attrs on tmp: %s\n"),
1273 if ((ioctl(tfd
, XFS_IOC_DIOINFO
, &dio
)) < 0 ) {
1274 fsrprintf(_("could not get DirectIO info on tmp: %s\n"), tname
);
1278 dio_min
= dio
.d_miniosz
;
1279 if (statp
->bs_size
<= dio_min
) {
1280 blksz_dio
= dio_min
;
1282 blksz_dio
= min(dio
.d_maxiosz
, BUFFER_MAX
- pagesize
);
1283 if (argv_blksz_dio
!= 0)
1284 blksz_dio
= min(argv_blksz_dio
, blksz_dio
);
1285 blksz_dio
= (min(statp
->bs_size
, blksz_dio
) / dio_min
) * dio_min
;
1289 fsrprintf(_("DEBUG: "
1290 "fsize=%lld blsz_dio=%d d_min=%d d_max=%d pgsz=%d\n"),
1291 statp
->bs_size
, blksz_dio
, dio
.d_miniosz
,
1292 dio
.d_maxiosz
, pagesize
);
1295 if (!(fbuf
= (char *)memalign(dio
.d_mem
, blksz_dio
))) {
1296 fsrprintf(_("could not allocate buf: %s\n"), tname
);
1301 /* Create new tmp file in same AG as first */
1302 sprintf(ffname
, "%s.frag", tname
);
1304 /* Open the new file for sync writes */
1305 if ((ffd
= open(ffname
, openopts
, 0666)) < 0) {
1306 fsrprintf(_("could not open fragfile: %s : %s\n"),
1307 ffname
, strerror(errno
));
1313 /* Loop through block map allocating new extents */
1314 for (extent
= 0; extent
< nextents
; extent
++) {
1315 pos
= outmap
[extent
].bmv_offset
;
1316 if (outmap
[extent
].bmv_block
== -1) {
1317 space
.l_whence
= SEEK_SET
;
1318 space
.l_start
= pos
;
1319 space
.l_len
= outmap
[extent
].bmv_length
;
1320 if (ioctl(tfd
, XFS_IOC_UNRESVSP64
, &space
) < 0) {
1321 fsrprintf(_("could not trunc tmp %s\n"),
1324 if (lseek64(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1325 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1326 tname
, strerror(errno
));
1330 } else if (outmap
[extent
].bmv_length
== 0) {
1331 /* to catch holes at the beginning of the file */
1335 space
.l_whence
= SEEK_CUR
;
1337 space
.l_len
= outmap
[extent
].bmv_length
;
1339 if (ioctl(tfd
, XFS_IOC_RESVSP64
, &space
) < 0) {
1340 fsrprintf(_("could not pre-allocate tmp space:"
1344 if (lseek64(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1345 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1346 tname
, strerror(errno
));
1350 } /* end of space allocation loop */
1352 if (lseek64(tfd
, 0, SEEK_SET
)) {
1353 fsrprintf(_("Couldn't rewind on temporary file\n"));
1357 /* Check if the temporary file has fewer extents */
1358 new_nextents
= getnextents(tfd
);
1360 fsrprintf(_("Temporary file has %d extents (%d in original)\n"), new_nextents
, cur_nextents
);
1361 if (cur_nextents
<= new_nextents
) {
1363 fsrprintf(_("No improvement will be made (skipping): %s\n"), fname
);
1364 retval
= 1; /* no change/no error */
1368 /* Loop through block map copying the file. */
1369 for (extent
= 0; extent
< nextents
; extent
++) {
1370 pos
= outmap
[extent
].bmv_offset
;
1371 if (outmap
[extent
].bmv_block
== -1) {
1372 if (lseek64(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1373 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1374 tname
, strerror(errno
));
1377 if (lseek64(fd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1378 fsrprintf(_("could not lseek in file: %s : %s\n"),
1379 fname
, strerror(errno
));
1383 } else if (outmap
[extent
].bmv_length
== 0) {
1384 /* to catch holes at the beginning of the file */
1387 for (cnt
= outmap
[extent
].bmv_length
; cnt
> 0;
1388 cnt
-= ct
, pos
+= ct
) {
1389 if (nfrags
&& --nfrags
) {
1390 ct
= min(cnt
, dio_min
);
1391 } else if (cnt
% dio_min
== 0) {
1392 ct
= min(cnt
, blksz_dio
);
1394 ct
= min(cnt
+ dio_min
- (cnt
% dio_min
),
1397 ct
= read(fd
, fbuf
, ct
);
1399 /* EOF, stop trying to read */
1403 /* Ensure we do direct I/O to correct block
1406 if (ct
% dio_min
!= 0) {
1407 wc
= ct
+ dio_min
- (ct
% dio_min
);
1412 if (ct
< 0 || ((wc
= write(tfd
, fbuf
, wc
)) != wc_b4
)) {
1414 fsrprintf(_("bad read of %d bytes "
1415 "from %s: %s\n"), wc_b4
,
1416 fname
, strerror(errno
));
1418 fsrprintf(_("bad write of %d bytes "
1419 "to %s: %s\n"), wc_b4
,
1420 tname
, strerror(errno
));
1423 * Might be out of space
1425 * Try to finish write
1429 if ((wc
= write(tfd
, ((char *)fbuf
)+wc
,
1431 /* worked on second attempt? */
1435 fsrprintf(_("bad write2 of %d "
1436 "bytes to %s: %s\n"),
1440 fsrprintf(_("bad copy to %s\n"),
1447 /* Do a matching write to the tmp file */
1449 if (((wc
= write(ffd
, fbuf
, wc
)) != wc_b4
)) {
1450 fsrprintf(_("bad write of %d bytes "
1452 wc_b4
, ffname
, strerror(errno
));
1457 if (ftruncate64(tfd
, statp
->bs_size
) < 0) {
1458 fsrprintf(_("could not truncate tmpfile: %s : %s\n"),
1459 fname
, strerror(errno
));
1462 if (fsync(tfd
) < 0) {
1463 fsrprintf(_("could not fsync tmpfile: %s : %s\n"),
1464 fname
, strerror(errno
));
1468 sx
.sx_stat
= *statp
; /* struct copy */
1469 sx
.sx_version
= XFS_SX_VERSION
;
1470 sx
.sx_fdtarget
= fd
;
1473 sx
.sx_length
= statp
->bs_size
;
1475 /* switch to the owner's id, to keep quota in line */
1476 if (fchown(tfd
, statp
->bs_uid
, statp
->bs_gid
) < 0) {
1478 fsrprintf(_("failed to fchown tmpfile %s: %s\n"),
1479 tname
, strerror(errno
));
1483 /* Swap the extents */
1484 srval
= xfs_swapext(fd
, &sx
);
1486 if (errno
== ENOTSUP
) {
1488 fsrprintf(_("%s: file type not supported\n"), fname
);
1489 } else if (errno
== EFAULT
) {
1490 /* The file has changed since we started the copy */
1492 fsrprintf(_("%s: file modified defrag aborted\n"),
1494 } else if (errno
== EBUSY
) {
1495 /* Timestamp has changed or mmap'ed file */
1497 fsrprintf(_("%s: file busy\n"), fname
);
1499 fsrprintf(_("XFS_IOC_SWAPEXT failed: %s: %s\n"),
1500 fname
, strerror(errno
));
1505 /* Report progress */
1507 fsrprintf(_("extents before:%d after:%d %s %s\n"),
1508 cur_nextents
, new_nextents
,
1509 (new_nextents
<= nextents
? "DONE" : " " ),
1523 gettmpname(char *fname
)
1525 static char buf
[PATH_MAX
+1];
1529 sprintf(sbuf
, "/.fsr%d", getpid());
1531 strncpy(buf
, fname
, PATH_MAX
);
1532 buf
[PATH_MAX
] = '\0';
1533 ptr
= strrchr(buf
, '/');
1540 if ((strlen(buf
) + strlen (sbuf
)) > PATH_MAX
) {
1541 fsrprintf(_("tmp file name too long: %s\n"), fname
);
1551 getparent(char *fname
)
1553 static char buf
[PATH_MAX
+1];
1556 strncpy(buf
, fname
, PATH_MAX
);
1557 buf
[PATH_MAX
] = '\0';
1558 ptr
= strrchr(buf
, '/');
1571 * Read in block map of the input file, coalesce contiguous
1572 * extents into a single range, keep all holes. Convert from 512 byte
1575 * This code was borrowed from mv.c with some minor mods.
1578 #define OUTMAP_SIZE_INCREMENT MAPSIZE
1580 int read_fd_bmap(int fd
, xfs_bstat_t
*sin
, int *cur_nextents
)
1583 struct getbmap map
[MAPSIZE
];
1586 if (++cnt >= outmap_size) { \
1587 outmap_size += OUTMAP_SIZE_INCREMENT; \
1588 outmap = (struct getbmap *)realloc(outmap, \
1589 outmap_size*sizeof(*outmap)); \
1590 if (outmap == NULL) { \
1591 fsrprintf(_("realloc failed: %s\n"), \
1597 /* Initialize the outmap array. It always grows - never shrinks.
1598 * Left-over memory allocation is saved for the next files.
1600 if (outmap_size
== 0) {
1601 outmap_size
= OUTMAP_SIZE_INCREMENT
; /* Initial size */
1602 outmap
= (struct getbmap
*)malloc(outmap_size
*sizeof(*outmap
));
1604 fsrprintf(_("malloc failed: %s\n"),
1610 outmap
[0].bmv_block
= 0;
1611 outmap
[0].bmv_offset
= 0;
1612 outmap
[0].bmv_length
= sin
->bs_size
;
1615 * If a non regular file is involved then forget holes
1618 if (!S_ISREG(sin
->bs_mode
))
1621 outmap
[0].bmv_length
= 0;
1623 map
[0].bmv_offset
= 0;
1624 map
[0].bmv_block
= 0;
1625 map
[0].bmv_entries
= 0;
1626 map
[0].bmv_count
= MAPSIZE
;
1627 map
[0].bmv_length
= -1;
1633 if (ioctl(fd
, XFS_IOC_GETBMAP
, map
) < 0) {
1634 fsrprintf(_("failed reading extents: inode %llu"),
1635 (unsigned long long)sin
->bs_ino
);
1639 /* Concatenate extents together and replicate holes into
1642 *cur_nextents
+= map
[0].bmv_entries
;
1643 for (i
= 0; i
< map
[0].bmv_entries
; i
++) {
1644 if (map
[i
+ 1].bmv_block
== -1) {
1646 outmap
[cnt
] = map
[i
+1];
1647 } else if (outmap
[cnt
].bmv_block
== -1) {
1649 outmap
[cnt
] = map
[i
+1];
1651 outmap
[cnt
].bmv_length
+= map
[i
+ 1].bmv_length
;
1654 } while (map
[0].bmv_entries
== (MAPSIZE
-1));
1655 for (i
= 0; i
<= cnt
; i
++) {
1656 outmap
[i
].bmv_offset
= BBTOB(outmap
[i
].bmv_offset
);
1657 outmap
[i
].bmv_length
= BBTOB(outmap
[i
].bmv_length
);
1660 outmap
[cnt
].bmv_length
= sin
->bs_size
- outmap
[cnt
].bmv_offset
;
1666 * Read the block map and return the number of extents.
1672 struct getbmap map
[MAPSIZE
];
1674 map
[0].bmv_offset
= 0;
1675 map
[0].bmv_block
= 0;
1676 map
[0].bmv_entries
= 0;
1677 map
[0].bmv_count
= MAPSIZE
;
1678 map
[0].bmv_length
= -1;
1683 if (ioctl(fd
,XFS_IOC_GETBMAP
, map
) < 0) {
1684 fsrprintf(_("failed reading extents"));
1688 nextents
+= map
[0].bmv_entries
;
1689 } while (map
[0].bmv_entries
== (MAPSIZE
-1));
1695 * Get the fs geometry
1698 xfs_getgeom(int fd
, xfs_fsop_geom_v1_t
* fsgeom
)
1700 if (xfs_fsgeometry(fd
, fsgeom
) < 0) {
1707 * Get xfs realtime space information
1710 xfs_getrt(int fd
, struct statvfs64
*sfbp
)
1712 unsigned long bsize
;
1713 unsigned long factor
;
1714 xfs_fsop_counts_t cnt
;
1716 if (!fsgeom
.rtblocks
)
1719 if (xfs_fscounts(fd
, &cnt
) < 0) {
1724 bsize
= (sfbp
->f_frsize
? sfbp
->f_frsize
: sfbp
->f_bsize
);
1726 bsize
= sfbp
->f_bsize
;
1728 factor
= fsgeom
.blocksize
/ bsize
; /* currently this is == 1 */
1729 sfbp
->f_bfree
= (cnt
.freertx
* fsgeom
.rtextsize
) * factor
;
1734 fsrprintf(const char *fmt
, ...)
1740 static int didopenlog
;
1742 openlog("fsr", LOG_PID
, LOG_USER
);
1745 vsyslog(LOG_INFO
, fmt
, ap
);
1753 * Initialize a directory for tmp file use. This is used
1754 * by the full filesystem defragmentation when we're walking
1755 * the inodes and do not know the path for the individual
1756 * files. Multiple directories are used to spread out the
1757 * tmp data around to different ag's (since file data is
1758 * usually allocated to the same ag as the directory and
1759 * directories allocated round robin from the same
1760 * parent directory).
1766 static char buf
[SMBUFSZ
];
1770 sprintf(buf
, "%s/.fsr", mnt
);
1773 if (mkdir(buf
, 0700) < 0) {
1774 if (errno
== EEXIST
) {
1776 fsrprintf(_("tmpdir already exists: %s\n"),
1779 fsrprintf(_("could not create tmpdir: %s: %s\n"),
1780 buf
, strerror(errno
));
1784 for (i
=0; i
< fsgeom
.agcount
; i
++) {
1785 sprintf(buf
, "%s/.fsr/ag%d", mnt
, i
);
1786 if (mkdir(buf
, 0700) < 0) {
1787 if (errno
== EEXIST
) {
1790 _("tmpdir already exists: %s\n"), buf
);
1792 fsrprintf(_("cannot create tmpdir: %s: %s\n"),
1793 buf
, strerror(errno
));
1805 static char buf
[SMBUFSZ
];
1807 sprintf(buf
, "%s/.fsr/ag%d/tmp%d",
1808 ( (strcmp(mnt
, "/") == 0) ? "" : mnt
),
1812 if (++tmp_agi
== fsgeom
.agcount
)
1819 tmp_close(char *mnt
)
1821 static char buf
[SMBUFSZ
];
1824 /* No data is ever actually written so we can just do rmdir's */
1825 for (i
=0; i
< fsgeom
.agcount
; i
++) {
1826 sprintf(buf
, "%s/.fsr/ag%d", mnt
, i
);
1827 if (rmdir(buf
) < 0) {
1828 if (errno
!= ENOENT
) {
1830 _("could not remove tmpdir: %s: %s\n"),
1831 buf
, strerror(errno
));
1835 sprintf(buf
, "%s/.fsr", mnt
);
1836 if (rmdir(buf
) < 0) {
1837 if (errno
!= ENOENT
) {
1838 fsrprintf(_("could not remove tmpdir: %s: %s\n"),
1839 buf
, strerror(errno
));