1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (c) 2000-2002 Silicon Graphics, Inc.
11 #include "xfs_bmap_btree.h"
12 #include "xfs_attr_sf.h"
19 #include <sys/ioctl.h>
21 #include <sys/statvfs.h>
22 #include <sys/xattr.h>
25 #define _PATH_FSRLAST "/var/tmp/.fsrlast_xfs"
26 #define _PATH_PROC_MOUNTS "/proc/mounts"
34 /* static int nflag; */
36 /* static int sflag; */
38 extern int max_ext_size
;
39 static int npasses
= 10;
40 static int startpass
= 0;
42 struct getbmap
*outmap
= NULL
;
46 static int64_t minimumfree
= 2048;
48 #define MNTTYPE_XFS "xfs"
54 #define TARGETRANGE 10
55 #define BUFFER_MAX (1<<24)
57 static time_t howlong
= 7200; /* default seconds of reorganizing */
58 static char *leftofffile
= _PATH_FSRLAST
; /* where we left off last */
59 static time_t endtime
;
60 static time_t starttime
;
61 static xfs_ino_t leftoffino
= 0;
65 static int fsrfile(char *fname
, xfs_ino_t ino
);
66 static int fsrfile_common( char *fname
, char *tname
, char *mnt
,
67 int fd
, xfs_bstat_t
*statp
);
68 static int packfile(char *fname
, char *tname
, int fd
,
69 xfs_bstat_t
*statp
, struct fsxattr
*fsxp
);
70 static void fsrdir(char *dirname
);
71 static int fsrfs(char *mntdir
, xfs_ino_t ino
, int targetrange
);
72 static void initallfs(char *mtab
);
73 static void fsrallfs(char *mtab
, int howlong
, char *leftofffile
);
74 static void fsrall_cleanup(int timeout
);
75 static int getnextents(int);
76 int xfsrtextsize(int fd
);
77 int xfs_getrt(int fd
, struct statvfs
*sfbp
);
78 char * gettmpname(char *fname
);
79 char * getparent(char *fname
);
80 int fsrprintf(const char *fmt
, ...);
81 int read_fd_bmap(int, xfs_bstat_t
*, int *);
82 int cmp(const void *, const void *);
83 static void tmp_init(char *mnt
);
84 static char * tmp_next(char *mnt
);
85 static void tmp_close(char *mnt
);
86 int xfs_getgeom(int , xfs_fsop_geom_v1_t
* );
88 xfs_fsop_geom_v1_t fsgeom
; /* geometry of active mounted system */
93 typedef struct fsdesc
{
99 fsdesc_t
*fs
, *fsbase
, *fsend
;
100 int fsbufsize
= 10; /* A starting value */
101 int nfrags
= 0; /* Debug option: Coerse into specific number
103 int openopts
= O_CREAT
|O_EXCL
|O_RDWR
|O_DIRECT
;
106 xfs_fsgeometry(int fd
, xfs_fsop_geom_v1_t
*geom
)
108 return ioctl(fd
, XFS_IOC_FSGEOMETRY_V1
, geom
);
112 xfs_bulkstat_single(int fd
, xfs_ino_t
*lastip
, xfs_bstat_t
*ubuffer
)
114 xfs_fsop_bulkreq_t bulkreq
;
116 bulkreq
.lastip
= (__u64
*)lastip
;
118 bulkreq
.ubuffer
= ubuffer
;
119 bulkreq
.ocount
= NULL
;
120 return ioctl(fd
, XFS_IOC_FSBULKSTAT_SINGLE
, &bulkreq
);
124 xfs_bulkstat(int fd
, xfs_ino_t
*lastip
, int icount
,
125 xfs_bstat_t
*ubuffer
, __s32
*ocount
)
127 xfs_fsop_bulkreq_t bulkreq
;
129 bulkreq
.lastip
= (__u64
*)lastip
;
130 bulkreq
.icount
= icount
;
131 bulkreq
.ubuffer
= ubuffer
;
132 bulkreq
.ocount
= ocount
;
133 return ioctl(fd
, XFS_IOC_FSBULKSTAT
, &bulkreq
);
137 xfs_swapext(int fd
, xfs_swapext_t
*sx
)
139 return ioctl(fd
, XFS_IOC_SWAPEXT
, sx
);
143 xfs_fscounts(int fd
, xfs_fsop_counts_t
*counts
)
145 return ioctl(fd
, XFS_IOC_FSCOUNTS
, counts
);
156 main(int argc
, char **argv
)
165 progname
= basename(argv
[0]);
167 setlocale(LC_ALL
, "");
168 bindtextdomain(PACKAGE
, LOCALEDIR
);
173 while ((c
= getopt(argc
, argv
, "C:p:e:MgsdnvTt:f:m:b:N:FV")) != -1) {
190 case 's': /* frag stats only */
193 _("%s: Stats not yet supported for XFS\n"),
198 howlong
= atoi(optarg
);
201 leftofffile
= optarg
;
207 argv_blksz_dio
= atoi(optarg
);
210 npasses
= atoi(optarg
);
213 /* Testing opt: coerses frag count in result */
214 if (getenv("FSRXFSTEST") != NULL
) {
215 nfrags
= atoi(optarg
);
220 printf(_("%s version %s\n"), progname
, VERSION
);
228 * If the user did not specify an explicit mount table, try to use
229 * /proc/mounts if it is available, else /etc/mtab. We prefer
230 * /proc/mounts because it is kernel controlled, while /etc/mtab
231 * may contain garbage that userspace tools like pam_mounts wrote
235 if (access(_PATH_PROC_MOUNTS
, R_OK
) == 0)
236 mtab
= _PATH_PROC_MOUNTS
;
238 mtab
= _PATH_MOUNTED
;
242 setbuf(stdout
, NULL
);
244 starttime
= time(NULL
);
246 /* Save the caller's real uid */
249 pagesize
= getpagesize();
250 fs_table_initialise(0, NULL
, 0, NULL
);
252 for (; optind
< argc
; optind
++) {
253 argname
= argv
[optind
];
255 if (lstat(argname
, &sb
) < 0) {
257 _("%s: could not stat: %s: %s\n"),
258 progname
, argname
, strerror(errno
));
262 if (S_ISLNK(sb
.st_mode
)) {
265 if (stat(argname
, &sb2
) == 0 &&
266 (S_ISBLK(sb2
.st_mode
) ||
267 S_ISCHR(sb2
.st_mode
)))
271 fsp
= fs_table_lookup_mount(argname
);
273 fsp
= fs_table_lookup_blkdev(argname
);
275 fsrfs(fsp
->fs_dir
, 0, 100);
276 } else if (S_ISCHR(sb
.st_mode
)) {
278 "%s: char special not supported: %s\n"),
281 } else if (S_ISDIR(sb
.st_mode
) || S_ISREG(sb
.st_mode
)) {
282 if (!platform_test_xfs_path(argname
)) {
284 "%s: cannot defragment: %s: Not XFS\n"),
288 if (S_ISDIR(sb
.st_mode
))
291 fsrfile(argname
, sb
.st_ino
);
294 _("%s: not fsys dev, dir, or reg file, ignoring\n"),
300 fsrallfs(mtab
, howlong
, leftofffile
);
309 "Usage: %s [-d] [-v] [-g] [-t time] [-p passes] [-f leftf] [-m mtab]\n"
310 " %s [-d] [-v] [-g] xfsdev | dir | file ...\n"
313 " -g Print to syslog (default if stdout not a tty).\n"
314 " -t time How long to run in seconds.\n"
315 " -p passes Number of passes before terminating global re-org.\n"
316 " -f leftoff Use this instead of %s.\n"
317 " -m mtab Use something other than /etc/mtab.\n"
318 " -d Debug, print even more.\n"
319 " -v Verbose, more -v's more verbose.\n"
320 " -V Print version number and exit.\n"
321 ), progname
, progname
, progname
, _PATH_FSRLAST
);
326 * initallfs -- read the mount table and set up an internal form
329 initallfs(char *mtab
)
331 struct mntent_cursor cursor
;
332 struct mntent
*mnt
= NULL
;
337 /* malloc a number of descriptors, increased later if needed */
338 if (!(fsbase
= (fsdesc_t
*)malloc(fsbufsize
* sizeof(fsdesc_t
)))) {
339 fsrprintf(_("out of memory: %s\n"), strerror(errno
));
342 fsend
= (fsbase
+ fsbufsize
- 1);
344 /* find all rw xfs file systems */
348 if (platform_mntent_open(&cursor
, mtab
) != 0){
349 fprintf(stderr
, "Error: can't get mntent entries.\n");
353 while ((mnt
= platform_mntent_next(&cursor
)) != NULL
) {
356 if (strcmp(mnt
->mnt_type
, MNTTYPE_XFS
) != 0 ||
357 stat(mnt
->mnt_fsname
, &sb
) == -1 ||
358 !S_ISBLK(sb
.st_mode
))
361 cp
= strtok(mnt
->mnt_opts
,",");
363 if (strcmp("rw", cp
) == 0)
365 } while ((cp
= strtok(NULL
, ",")) != NULL
);
368 fsrprintf(_("Skipping %s: not mounted rw\n"),
373 if (mi
== fsbufsize
) {
375 if ((fsbase
= (fsdesc_t
*)realloc((char *)fsbase
,
376 fsbufsize
* sizeof(fsdesc_t
))) == NULL
) {
377 fsrprintf(_("out of memory: %s\n"),
382 fsrprintf(_("out of memory on realloc: %s\n"),
386 fs
= (fsbase
+ mi
); /* Needed ? */
389 fs
->dev
= strdup(mnt
->mnt_fsname
);
390 fs
->mnt
= strdup(mnt
->mnt_dir
);
392 if (fs
->dev
== NULL
) {
393 fsrprintf(_("strdup(%s) failed\n"), mnt
->mnt_fsname
);
396 if (fs
->mnt
== NULL
) {
397 fsrprintf(_("strdup(%s) failed\n"), mnt
->mnt_dir
);
403 platform_mntent_close(&cursor
);
406 fsend
= (fsbase
+ numfs
);
408 fsrprintf(_("no rw xfs file systems in mtab: %s\n"), mtab
);
411 if (vflag
|| dflag
) {
412 fsrprintf(_("Found %d mounted, writable, XFS filesystems\n"),
415 for (fs
= fsbase
; fs
< fsend
; fs
++)
416 fsrprintf("\t%-30.30s%-30.30s\n", fs
->dev
, fs
->mnt
);
421 fsrallfs(char *mtab
, int howlong
, char *leftofffile
)
430 xfs_ino_t startino
= 0;
434 fsrprintf("xfs_fsr -m %s -t %d -f %s ...\n", mtab
, howlong
, leftofffile
);
436 endtime
= starttime
+ howlong
;
439 /* where'd we leave off last time? */
440 if (lstat(leftofffile
, &sb
) == 0) {
441 if ( (fd
= open(leftofffile
, O_RDONLY
)) == -1 ) {
442 fsrprintf(_("%s: open failed\n"), leftofffile
);
444 else if ( fstat(fd
, &sb2
) == 0) {
446 * Verify that lstat & fstat point to the
447 * same regular file (no links/no quick spoofs)
449 if ( (sb
.st_dev
!= sb2
.st_dev
) ||
450 (sb
.st_ino
!= sb2
.st_ino
) ||
451 ((sb
.st_mode
& S_IFMT
) != S_IFREG
) ||
452 ((sb2
.st_mode
& S_IFMT
) != S_IFREG
) ||
453 (sb2
.st_uid
!= ROOT
) ||
457 fsrprintf(_("Can't use %s: mode=0%o own=%d"
459 leftofffile
, sb
.st_mode
,
460 sb
.st_uid
, sb
.st_nlink
);
475 if (read(fd
, buf
, SMBUFSZ
) == -1) {
477 fsrprintf(_("could not read %s, starting with %s\n"),
478 leftofffile
, *fs
->dev
);
480 /* Ensure the buffer we read is null terminated */
481 buf
[SMBUFSZ
-1] = '\0';
482 for (fs
= fsbase
; fs
< fsend
; fs
++) {
484 if ((strncmp(buf
,fsname
,strlen(fsname
)) == 0)
485 && buf
[strlen(fsname
)] == ' ') {
493 ptr
= strchr(buf
, ' ');
495 startpass
= atoi(++ptr
);
496 ptr
= strchr(ptr
, ' ');
498 startino
= strtoull(++ptr
, NULL
, 10);
504 /* Init pass counts */
505 for (fsp
= fsbase
; fsp
< fs
; fsp
++) {
506 fsp
->npass
= startpass
+ 1;
508 for (fsp
= fs
; fsp
<= fsend
; fsp
++) {
509 fsp
->npass
= startpass
;
516 fsrprintf(_("START: pass=%d ino=%llu %s %s\n"),
517 fs
->npass
, (unsigned long long)startino
,
521 signal(SIGABRT
, aborter
);
522 signal(SIGHUP
, aborter
);
523 signal(SIGINT
, aborter
);
524 signal(SIGQUIT
, aborter
);
525 signal(SIGTERM
, aborter
);
527 /* reorg for 'howlong' -- checked in 'fsrfs' */
528 while (endtime
> time(NULL
)) {
531 if (npasses
> 1 && !fs
->npass
)
538 fsrprintf(_("couldn't fork sub process:"));
542 error
= fsrfs(fs
->mnt
, startino
, TARGETRANGE
);
547 if (WIFEXITED(error
) && WEXITSTATUS(error
) == 1) {
548 /* child timed out & did fsrall_cleanup */
553 startino
= 0; /* reset after the first time through */
558 if (fs
->npass
== npasses
) {
559 fsrprintf(_("Completed all %d passes\n"), npasses
);
563 fsrall_cleanup(endtime
<= time(NULL
));
567 * fsrall_cleanup -- close files, print next starting location, etc.
570 fsrall_cleanup(int timeout
)
579 fsrprintf(_("%s startpass %d, endpass %d, time %d seconds\n"),
580 progname
, startpass
, fs
->npass
,
581 time(NULL
) - endtime
+ howlong
);
583 /* record where we left off */
584 fd
= open(leftofffile
, O_WRONLY
|O_CREAT
|O_EXCL
, 0644);
586 fsrprintf(_("open(%s) failed: %s\n"),
587 leftofffile
, strerror(errno
));
589 ret
= sprintf(buf
, "%s %d %llu\n", fs
->dev
,
590 fs
->npass
, (unsigned long long)leftoffino
);
591 if (write(fd
, buf
, ret
) < strlen(buf
))
592 fsrprintf(_("write(%s) failed: %s\n"),
593 leftofffile
, strerror(errno
));
600 * fsrfs -- reorganize a file system
603 fsrfs(char *mntdir
, xfs_ino_t startino
, int targetrange
)
610 xfs_bstat_t buf
[GRABSZ
];
613 jdm_fshandle_t
*fshandlep
;
614 xfs_ino_t lastino
= startino
;
616 fsrprintf(_("%s start inode=%llu\n"), mntdir
,
617 (unsigned long long)startino
);
619 fshandlep
= jdm_getfshandle( mntdir
);
621 fsrprintf(_("unable to get handle: %s: %s\n"),
622 mntdir
, strerror( errno
));
626 if ((fsfd
= open(mntdir
, O_RDONLY
)) < 0) {
627 fsrprintf(_("unable to open: %s: %s\n"),
628 mntdir
, strerror( errno
));
633 if (xfs_getgeom(fsfd
, &fsgeom
) < 0 ) {
634 fsrprintf(_("Skipping %s: could not get XFS geometry\n"),
643 while ((ret
= xfs_bulkstat(fsfd
,
644 &lastino
, GRABSZ
, &buf
[0], &buflenout
)) == 0) {
651 /* Each loop through, defrag targetrange percent of the files */
652 count
= (buflenout
* targetrange
) / 100;
654 qsort((char *)buf
, buflenout
, sizeof(struct xfs_bstat
), cmp
);
656 for (p
= buf
, endp
= (buf
+ buflenout
); p
< endp
; p
++) {
657 /* Do some obvious checks now */
658 if (((p
->bs_mode
& S_IFMT
) != S_IFREG
) ||
662 fd
= jdm_open(fshandlep
, p
, O_RDWR
|O_DIRECT
);
664 /* This probably means the file was
665 * removed while in progress of handling
666 * it. Just quietly ignore this file.
669 fsrprintf(_("could not open: "
670 "inode %llu\n"), p
->bs_ino
);
674 /* Don't know the pathname, so make up something */
675 sprintf(fname
, "ino=%lld", (long long)p
->bs_ino
);
677 /* Get a tmp file name */
678 tname
= tmp_next(mntdir
);
680 ret
= fsrfile_common(fname
, tname
, mntdir
, fd
, p
);
682 leftoffino
= p
->bs_ino
;
691 if (endtime
&& endtime
< time(NULL
)) {
699 fsrprintf(_("%s: xfs_bulkstat: %s\n"), progname
, strerror(errno
));
708 * To compare bstat structs for qsort.
711 cmp(const void *s1
, const void *s2
)
713 return( ((xfs_bstat_t
*)s2
)->bs_extents
-
714 ((xfs_bstat_t
*)s1
)->bs_extents
);
719 * reorganize by directory hierarchy.
720 * Stay in dev (a restriction based on structure of this program -- either
721 * call efs_{n,u}mount() around each file, something smarter or this)
724 fsrdir(char *dirname
)
726 fsrprintf(_("%s: Directory defragmentation not supported\n"), dirname
);
730 * Sets up the defragmentation of a file based on the
731 * filepath. It collects the bstat information, does
732 * an open on the file and passes this all to fsrfile_common.
735 fsrfile(char *fname
, xfs_ino_t ino
)
738 jdm_fshandle_t
*fshandlep
;
739 int fd
= -1, fsfd
= -1;
743 fshandlep
= jdm_getfshandle(getparent (fname
) );
745 fsrprintf(_("unable to construct sys handle for %s: %s\n"),
746 fname
, strerror(errno
));
751 * Need to open something on the same filesystem as the
752 * file. Open the parent.
754 fsfd
= open(getparent(fname
), O_RDONLY
);
756 fsrprintf(_("unable to open sys handle for %s: %s\n"),
757 fname
, strerror(errno
));
761 if ((xfs_bulkstat_single(fsfd
, &ino
, &statbuf
)) < 0) {
762 fsrprintf(_("unable to get bstat on %s: %s\n"),
763 fname
, strerror(errno
));
767 fd
= jdm_open(fshandlep
, &statbuf
, O_RDWR
|O_DIRECT
);
769 fsrprintf(_("unable to open handle %s: %s\n"),
770 fname
, strerror(errno
));
774 /* Get the fs geometry */
775 if (xfs_getgeom(fsfd
, &fsgeom
) < 0 ) {
776 fsrprintf(_("Unable to get geom on fs for: %s\n"), fname
);
780 tname
= gettmpname(fname
);
783 error
= fsrfile_common(fname
, tname
, NULL
, fd
, &statbuf
);
797 * This is the common defrag code for either a full fs
798 * defragmentation or a single file. Check as much as
799 * possible with the file, fork a process to setuid to the
800 * target file owner's uid and defragment the file.
801 * This is done so the new extents created in a tmp file are
802 * reflected in the owners' quota without having to do any
803 * special code in the kernel. When the existing extents
804 * are removed, the quotas will be correct. It's ugly but
805 * it saves us from doing some quota re-construction in
806 * the extent swap. The price is that the defragmentation
807 * will fail if the owner of the target file is already at
824 fsrprintf("%s\n", fname
);
827 fsrprintf(_("sync failed: %s: %s\n"), fname
, strerror(errno
));
831 if (statp
->bs_size
== 0) {
833 fsrprintf(_("%s: zero size, ignoring\n"), fname
);
837 /* Check if a mandatory lock is set on the file to try and
838 * avoid blocking indefinitely on the reads later. Note that
839 * someone could still set a mandatory lock after this check
840 * but before all reads have completed to block fsr reads.
841 * This change just closes the window a bit.
843 if ( (statp
->bs_mode
& S_ISGID
) && ( ! (statp
->bs_mode
&S_IXGRP
) ) ) {
847 fl
.l_whence
= SEEK_SET
;
848 fl
.l_start
= (off_t
)0;
850 if ((fcntl(fd
, F_GETLK
, &fl
)) < 0 ) {
852 fsrprintf(_("locking check failed: %s\n"),
856 if (fl
.l_type
!= F_UNLCK
) {
857 /* Mandatory lock is set */
859 fsrprintf(_("mandatory lock: %s: ignoring\n"),
866 * Check if there is room to copy the file.
868 * Note that xfs_bstat.bs_blksize returns the filesystem blocksize,
869 * not the optimal I/O size as struct stat.
871 if (statvfs(fsname
? fsname
: fname
, &vfss
) < 0) {
872 fsrprintf(_("unable to get fs stat on %s: %s\n"),
873 fname
, strerror(errno
));
876 bsize
= vfss
.f_frsize
? vfss
.f_frsize
: vfss
.f_bsize
;
877 if (statp
->bs_blksize
* statp
->bs_blocks
>
878 vfss
.f_bfree
* bsize
- minimumfree
) {
879 fsrprintf(_("insufficient freespace for: %s: "
880 "size=%lld: ignoring\n"), fname
,
881 statp
->bs_blksize
* statp
->bs_blocks
);
885 if ((ioctl(fd
, FS_IOC_FSGETXATTR
, &fsx
)) < 0) {
886 fsrprintf(_("failed to get inode attrs: %s\n"), fname
);
889 if (fsx
.fsx_xflags
& (FS_XFLAG_IMMUTABLE
|FS_XFLAG_APPEND
)) {
891 fsrprintf(_("%s: immutable/append, ignoring\n"), fname
);
894 if (fsx
.fsx_xflags
& FS_XFLAG_NODEFRAG
) {
896 fsrprintf(_("%s: marked as don't defrag, ignoring\n"),
900 if (fsx
.fsx_xflags
& FS_XFLAG_REALTIME
) {
901 if (xfs_getrt(fd
, &vfss
) < 0) {
902 fsrprintf(_("cannot get realtime geometry for: %s\n"),
906 if (statp
->bs_size
> ((vfss
.f_bfree
* bsize
) - minimumfree
)) {
907 fsrprintf(_("low on realtime free space: %s: "
908 "ignoring file\n"), fname
);
913 if ((RealUid
!= ROOT
) && (RealUid
!= statp
->bs_uid
)) {
914 fsrprintf(_("cannot open: %s: Permission denied\n"), fname
);
919 * Previously the code forked here, & the child changed it's uid to
920 * that of the file's owner and then called packfile(), to keep
921 * quota counts correct. (defragged files could use fewer blocks).
923 * Instead, just fchown() the temp file to the uid,gid of the
924 * file we're defragging, in packfile().
927 if ((error
= packfile(fname
, tname
, fd
, statp
, &fsx
)))
929 return -1; /* no error */
933 * Attempt to set the attr fork up correctly. This is simple for attr1
934 * filesystems as they have a fixed inode fork offset. In that case
935 * just create an attribute and that's all we need to do.
937 * For attr2 filesystems, see if we have the actual fork offset in
938 * the bstat structure. If so, just create additional attributes on
939 * the temporary inode until the offset matches.
941 * If it doesn't exist, we can only do best effort. Add an attribute at a time
942 * to move the inode fork around, but take into account that the attribute
943 * might be too small to move the fork every time we add one. This should
944 * hopefully put the fork offset in the right place. It's not a big deal if we
945 * don't get it right - the kernel will reject it when we try to swap extents.
953 #ifdef HAVE_FSETXATTR
954 struct stat tstatbuf
;
957 int last_forkoff
= 0;
958 int no_change_cnt
= 0;
961 if (!(bstatp
->bs_xflags
& FS_XFLAG_HASATTR
))
965 * use the old method if we have attr1 or the kernel does not yet
966 * support passing the fork offset in the bulkstat data.
968 if (!(fsgeom
.flags
& XFS_FSOP_GEOM_FLAGS_ATTR2
) ||
969 bstatp
->bs_forkoff
== 0) {
971 ret
= fsetxattr(tfd
, "user.X", "X", 1, XATTR_CREATE
);
973 fsrprintf(_("could not set ATTR\n"));
979 /* attr2 w/ fork offsets */
981 if (fstat(tfd
, &tstatbuf
) < 0) {
982 fsrprintf(_("unable to stat temp file: %s\n"),
994 * bulkstat the temp inode to see what the forkoff is. Use
995 * this to compare against the target and determine what we
998 ino
= tstatbuf
.st_ino
;
999 if ((xfs_bulkstat_single(tfd
, &ino
, &tbstat
)) < 0) {
1000 fsrprintf(_("unable to get bstat on temp file: %s\n"),
1005 fsrprintf(_("orig forkoff %d, temp forkoff %d\n"),
1006 bstatp
->bs_forkoff
, tbstat
.bs_forkoff
);
1007 diff
= tbstat
.bs_forkoff
- bstatp
->bs_forkoff
;
1009 /* if they are equal, we are done */
1013 snprintf(name
, sizeof(name
), "user.%d", i
);
1016 * If there is no attribute, then we need to create one to get
1017 * an attribute fork at the default location.
1019 if (!tbstat
.bs_forkoff
) {
1021 ret
= fsetxattr(tfd
, name
, "XX", 2, XATTR_CREATE
);
1023 fsrprintf(_("could not set ATTR\n"));
1027 } else if (i
== 0) {
1029 * First pass, and temp file already has an inline
1030 * xattr, probably due to selinux.
1032 * It's *possible* that the temp file attr area
1033 * is larger than the target file's:
1036 * +-------+ 0 +-------+ 0
1040 * | | v-------v forkoff
1042 * v-------v forkoff | Attr | local
1044 * +-------+ +-------+
1048 * If target attr area is less than the temp's
1049 * (diff < 0) write a big attr to the temp file to knock
1050 * the attr out of local format.
1051 * (This should actually *increase* the temp file's
1052 * forkoffset when the attr moves out of the inode)
1056 memset(val
, 'X', 2048);
1057 if (fsetxattr(tfd
, name
, val
, 2048, 0)) {
1058 fsrprintf(_("big ATTR set failed\n"));
1061 /* Go back & see where we're at now */
1067 * make a progress check so we don't get stuck trying to extend
1068 * a large btree form attribute fork.
1070 if (last_forkoff
== tbstat
.bs_forkoff
) {
1071 if (no_change_cnt
++ > 10)
1073 } else /* progress! */
1075 last_forkoff
= tbstat
.bs_forkoff
;
1077 /* work out which way to grow the fork */
1078 if (abs(diff
) > fsgeom
.inodesize
- sizeof(struct xfs_dinode
)) {
1079 fsrprintf(_("forkoff diff %d too large!\n"), diff
);
1084 * if the temp inode fork offset is still smaller then we have
1085 * to grow the data fork
1089 * create some temporary extents in the inode to move
1090 * the fork in the direction we need. This can be done
1091 * by preallocating some single block extents at
1092 * non-contiguous offsets.
1094 /* XXX: unimplemented! */
1096 printf(_("data fork growth unimplemented\n"));
1100 /* we need to grow the attr fork, so create another attr */
1101 ret
= fsetxattr(tfd
, name
, "XX", 2, XATTR_CREATE
);
1103 fsrprintf(_("could not set ATTR\n"));
1107 } while (++i
< 100); /* don't go forever */
1111 fsrprintf(_("set temp attr\n"));
1112 /* We failed to resolve the fork difference */
1114 fsrprintf(_("failed to match fork offset\n"));;
1116 #endif /* HAVE_FSETXATTR */
1121 * Do the defragmentation of a single file.
1122 * We already are pretty sure we can and want to
1123 * defragment the file. Create the tmp file, copy
1124 * the data (maintaining holes) and call the kernel
1125 * extent swap routine.
1128 * -1: Some error was encountered
1129 * 0: Successfully defragmented the file
1130 * 1: No change / No Error
1133 packfile(char *fname
, char *tname
, int fd
,
1134 xfs_bstat_t
*statp
, struct fsxattr
*fsxp
)
1138 int retval
= -1; /* Failure is the default */
1139 int nextents
, extent
, cur_nextents
, new_nextents
;
1143 static xfs_swapext_t sx
;
1144 struct xfs_flock64 space
;
1148 char ffname
[SMBUFSZ
];
1152 * Work out the extent map - nextents will be set to the
1153 * minimum number of extents needed for the file (taking
1154 * into account holes), cur_nextents is the current number
1157 nextents
= read_fd_bmap(fd
, statp
, &cur_nextents
);
1159 if (cur_nextents
== 1 || cur_nextents
<= nextents
) {
1161 fsrprintf(_("%s already fully defragmented.\n"), fname
);
1162 retval
= 1; /* indicates no change/no error */
1167 fsrprintf(_("%s extents=%d can_save=%d tmp=%s\n"),
1168 fname
, cur_nextents
, (cur_nextents
- nextents
),
1171 if ((tfd
= open(tname
, openopts
, 0666)) < 0) {
1173 fsrprintf(_("could not open tmp file: %s: %s\n"),
1174 tname
, strerror(errno
));
1179 /* Setup extended attributes */
1180 if (fsr_setup_attr_fork(fd
, tfd
, statp
) != 0) {
1181 fsrprintf(_("failed to set ATTR fork on tmp: %s:\n"), tname
);
1185 /* Setup extended inode flags, project identifier, etc */
1186 if (fsxp
->fsx_xflags
|| fsxp
->fsx_projid
) {
1187 if (ioctl(tfd
, FS_IOC_FSSETXATTR
, fsxp
) < 0) {
1188 fsrprintf(_("could not set inode attrs on tmp: %s\n"),
1194 if ((ioctl(tfd
, XFS_IOC_DIOINFO
, &dio
)) < 0 ) {
1195 fsrprintf(_("could not get DirectIO info on tmp: %s\n"), tname
);
1199 dio_min
= dio
.d_miniosz
;
1200 if (statp
->bs_size
<= dio_min
) {
1201 blksz_dio
= dio_min
;
1203 blksz_dio
= min(dio
.d_maxiosz
, BUFFER_MAX
- pagesize
);
1204 if (argv_blksz_dio
!= 0)
1205 blksz_dio
= min(argv_blksz_dio
, blksz_dio
);
1206 blksz_dio
= (min(statp
->bs_size
, blksz_dio
) / dio_min
) * dio_min
;
1210 fsrprintf(_("DEBUG: "
1211 "fsize=%lld blsz_dio=%d d_min=%d d_max=%d pgsz=%d\n"),
1212 statp
->bs_size
, blksz_dio
, dio
.d_miniosz
,
1213 dio
.d_maxiosz
, pagesize
);
1216 if (!(fbuf
= (char *)memalign(dio
.d_mem
, blksz_dio
))) {
1217 fsrprintf(_("could not allocate buf: %s\n"), tname
);
1222 /* Create new tmp file in same AG as first */
1223 sprintf(ffname
, "%s.frag", tname
);
1225 /* Open the new file for sync writes */
1226 if ((ffd
= open(ffname
, openopts
, 0666)) < 0) {
1227 fsrprintf(_("could not open fragfile: %s : %s\n"),
1228 ffname
, strerror(errno
));
1234 /* Loop through block map allocating new extents */
1235 for (extent
= 0; extent
< nextents
; extent
++) {
1236 pos
= outmap
[extent
].bmv_offset
;
1237 if (outmap
[extent
].bmv_block
== -1) {
1238 space
.l_whence
= SEEK_SET
;
1239 space
.l_start
= pos
;
1240 space
.l_len
= outmap
[extent
].bmv_length
;
1241 if (ioctl(tfd
, XFS_IOC_UNRESVSP64
, &space
) < 0) {
1242 fsrprintf(_("could not trunc tmp %s\n"),
1245 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1246 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1247 tname
, strerror(errno
));
1251 } else if (outmap
[extent
].bmv_length
== 0) {
1252 /* to catch holes at the beginning of the file */
1256 space
.l_whence
= SEEK_CUR
;
1258 space
.l_len
= outmap
[extent
].bmv_length
;
1260 if (ioctl(tfd
, XFS_IOC_RESVSP64
, &space
) < 0) {
1261 fsrprintf(_("could not pre-allocate tmp space:"
1265 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1266 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1267 tname
, strerror(errno
));
1271 } /* end of space allocation loop */
1273 if (lseek(tfd
, 0, SEEK_SET
)) {
1274 fsrprintf(_("Couldn't rewind on temporary file\n"));
1278 /* Check if the temporary file has fewer extents */
1279 new_nextents
= getnextents(tfd
);
1281 fsrprintf(_("Temporary file has %d extents (%d in original)\n"), new_nextents
, cur_nextents
);
1282 if (cur_nextents
<= new_nextents
) {
1284 fsrprintf(_("No improvement will be made (skipping): %s\n"), fname
);
1285 retval
= 1; /* no change/no error */
1289 /* Loop through block map copying the file. */
1290 for (extent
= 0; extent
< nextents
; extent
++) {
1291 pos
= outmap
[extent
].bmv_offset
;
1292 if (outmap
[extent
].bmv_block
== -1) {
1293 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1294 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1295 tname
, strerror(errno
));
1298 if (lseek(fd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1299 fsrprintf(_("could not lseek in file: %s : %s\n"),
1300 fname
, strerror(errno
));
1304 } else if (outmap
[extent
].bmv_length
== 0) {
1305 /* to catch holes at the beginning of the file */
1308 for (cnt
= outmap
[extent
].bmv_length
; cnt
> 0;
1309 cnt
-= ct
, pos
+= ct
) {
1310 if (nfrags
&& --nfrags
) {
1311 ct
= min(cnt
, dio_min
);
1312 } else if (cnt
% dio_min
== 0) {
1313 ct
= min(cnt
, blksz_dio
);
1315 ct
= min(cnt
+ dio_min
- (cnt
% dio_min
),
1318 ct
= read(fd
, fbuf
, ct
);
1320 /* EOF, stop trying to read */
1324 /* Ensure we do direct I/O to correct block
1327 if (ct
% dio_min
!= 0) {
1328 wc
= ct
+ dio_min
- (ct
% dio_min
);
1333 if (ct
< 0 || ((wc
= write(tfd
, fbuf
, wc
)) != wc_b4
)) {
1335 fsrprintf(_("bad read of %d bytes "
1336 "from %s: %s\n"), wc_b4
,
1337 fname
, strerror(errno
));
1339 fsrprintf(_("bad write of %d bytes "
1340 "to %s: %s\n"), wc_b4
,
1341 tname
, strerror(errno
));
1344 * Might be out of space
1346 * Try to finish write
1350 if ((wc
= write(tfd
, ((char *)fbuf
)+wc
,
1352 /* worked on second attempt? */
1356 fsrprintf(_("bad write2 of %d "
1357 "bytes to %s: %s\n"),
1361 fsrprintf(_("bad copy to %s\n"),
1368 /* Do a matching write to the tmp file */
1370 if (((wc
= write(ffd
, fbuf
, wc
)) != wc_b4
)) {
1371 fsrprintf(_("bad write of %d bytes "
1373 wc_b4
, ffname
, strerror(errno
));
1378 if (ftruncate(tfd
, statp
->bs_size
) < 0) {
1379 fsrprintf(_("could not truncate tmpfile: %s : %s\n"),
1380 fname
, strerror(errno
));
1383 if (fsync(tfd
) < 0) {
1384 fsrprintf(_("could not fsync tmpfile: %s : %s\n"),
1385 fname
, strerror(errno
));
1389 sx
.sx_stat
= *statp
; /* struct copy */
1390 sx
.sx_version
= XFS_SX_VERSION
;
1391 sx
.sx_fdtarget
= fd
;
1394 sx
.sx_length
= statp
->bs_size
;
1396 /* switch to the owner's id, to keep quota in line */
1397 if (fchown(tfd
, statp
->bs_uid
, statp
->bs_gid
) < 0) {
1399 fsrprintf(_("failed to fchown tmpfile %s: %s\n"),
1400 tname
, strerror(errno
));
1404 /* Swap the extents */
1405 srval
= xfs_swapext(fd
, &sx
);
1407 if (errno
== ENOTSUP
) {
1409 fsrprintf(_("%s: file type not supported\n"), fname
);
1410 } else if (errno
== EFAULT
) {
1411 /* The file has changed since we started the copy */
1413 fsrprintf(_("%s: file modified defrag aborted\n"),
1415 } else if (errno
== EBUSY
) {
1416 /* Timestamp has changed or mmap'ed file */
1418 fsrprintf(_("%s: file busy\n"), fname
);
1420 fsrprintf(_("XFS_IOC_SWAPEXT failed: %s: %s\n"),
1421 fname
, strerror(errno
));
1426 /* Report progress */
1428 fsrprintf(_("extents before:%d after:%d %s %s\n"),
1429 cur_nextents
, new_nextents
,
1430 (new_nextents
<= nextents
? "DONE" : " " ),
1444 gettmpname(char *fname
)
1446 static char buf
[PATH_MAX
+1];
1450 sprintf(sbuf
, "/.fsr%d", getpid());
1452 strncpy(buf
, fname
, PATH_MAX
);
1453 buf
[PATH_MAX
] = '\0';
1454 ptr
= strrchr(buf
, '/');
1461 if ((strlen(buf
) + strlen (sbuf
)) > PATH_MAX
) {
1462 fsrprintf(_("tmp file name too long: %s\n"), fname
);
1472 getparent(char *fname
)
1474 static char buf
[PATH_MAX
+1];
1477 strncpy(buf
, fname
, PATH_MAX
);
1478 buf
[PATH_MAX
] = '\0';
1479 ptr
= strrchr(buf
, '/');
1492 * Read in block map of the input file, coalesce contiguous
1493 * extents into a single range, keep all holes. Convert from 512 byte
1496 * This code was borrowed from mv.c with some minor mods.
1499 #define OUTMAP_SIZE_INCREMENT MAPSIZE
1501 int read_fd_bmap(int fd
, xfs_bstat_t
*sin
, int *cur_nextents
)
1504 struct getbmap map
[MAPSIZE
];
1507 if (++cnt >= outmap_size) { \
1508 outmap_size += OUTMAP_SIZE_INCREMENT; \
1509 outmap = (struct getbmap *)realloc(outmap, \
1510 outmap_size*sizeof(*outmap)); \
1511 if (outmap == NULL) { \
1512 fsrprintf(_("realloc failed: %s\n"), \
1518 /* Initialize the outmap array. It always grows - never shrinks.
1519 * Left-over memory allocation is saved for the next files.
1521 if (outmap_size
== 0) {
1522 outmap_size
= OUTMAP_SIZE_INCREMENT
; /* Initial size */
1523 outmap
= (struct getbmap
*)malloc(outmap_size
*sizeof(*outmap
));
1525 fsrprintf(_("malloc failed: %s\n"),
1531 outmap
[0].bmv_block
= 0;
1532 outmap
[0].bmv_offset
= 0;
1533 outmap
[0].bmv_length
= sin
->bs_size
;
1536 * If a non regular file is involved then forget holes
1539 if (!S_ISREG(sin
->bs_mode
))
1542 outmap
[0].bmv_length
= 0;
1544 map
[0].bmv_offset
= 0;
1545 map
[0].bmv_block
= 0;
1546 map
[0].bmv_entries
= 0;
1547 map
[0].bmv_count
= MAPSIZE
;
1548 map
[0].bmv_length
= -1;
1554 if (ioctl(fd
, XFS_IOC_GETBMAP
, map
) < 0) {
1555 fsrprintf(_("failed reading extents: inode %llu"),
1556 (unsigned long long)sin
->bs_ino
);
1560 /* Concatenate extents together and replicate holes into
1563 *cur_nextents
+= map
[0].bmv_entries
;
1564 for (i
= 0; i
< map
[0].bmv_entries
; i
++) {
1565 if (map
[i
+ 1].bmv_block
== -1) {
1567 outmap
[cnt
] = map
[i
+1];
1568 } else if (outmap
[cnt
].bmv_block
== -1) {
1570 outmap
[cnt
] = map
[i
+1];
1572 outmap
[cnt
].bmv_length
+= map
[i
+ 1].bmv_length
;
1575 } while (map
[0].bmv_entries
== (MAPSIZE
-1));
1576 for (i
= 0; i
<= cnt
; i
++) {
1577 outmap
[i
].bmv_offset
= BBTOB(outmap
[i
].bmv_offset
);
1578 outmap
[i
].bmv_length
= BBTOB(outmap
[i
].bmv_length
);
1581 outmap
[cnt
].bmv_length
= sin
->bs_size
- outmap
[cnt
].bmv_offset
;
1587 * Read the block map and return the number of extents.
1593 struct getbmap map
[MAPSIZE
];
1595 map
[0].bmv_offset
= 0;
1596 map
[0].bmv_block
= 0;
1597 map
[0].bmv_entries
= 0;
1598 map
[0].bmv_count
= MAPSIZE
;
1599 map
[0].bmv_length
= -1;
1604 if (ioctl(fd
,XFS_IOC_GETBMAP
, map
) < 0) {
1605 fsrprintf(_("failed reading extents"));
1609 nextents
+= map
[0].bmv_entries
;
1610 } while (map
[0].bmv_entries
== (MAPSIZE
-1));
1616 * Get the fs geometry
1619 xfs_getgeom(int fd
, xfs_fsop_geom_v1_t
* fsgeom
)
1621 if (xfs_fsgeometry(fd
, fsgeom
) < 0) {
1628 * Get xfs realtime space information
1631 xfs_getrt(int fd
, struct statvfs
*sfbp
)
1633 unsigned long bsize
;
1634 unsigned long factor
;
1635 xfs_fsop_counts_t cnt
;
1637 if (!fsgeom
.rtblocks
)
1640 if (xfs_fscounts(fd
, &cnt
) < 0) {
1644 bsize
= (sfbp
->f_frsize
? sfbp
->f_frsize
: sfbp
->f_bsize
);
1645 factor
= fsgeom
.blocksize
/ bsize
; /* currently this is == 1 */
1646 sfbp
->f_bfree
= (cnt
.freertx
* fsgeom
.rtextsize
) * factor
;
1651 fsrprintf(const char *fmt
, ...)
1657 static int didopenlog
;
1659 openlog("fsr", LOG_PID
, LOG_USER
);
1662 vsyslog(LOG_INFO
, fmt
, ap
);
1670 * Initialize a directory for tmp file use. This is used
1671 * by the full filesystem defragmentation when we're walking
1672 * the inodes and do not know the path for the individual
1673 * files. Multiple directories are used to spread out the
1674 * tmp data around to different ag's (since file data is
1675 * usually allocated to the same ag as the directory and
1676 * directories allocated round robin from the same
1677 * parent directory).
1683 static char buf
[SMBUFSZ
];
1687 sprintf(buf
, "%s/.fsr", mnt
);
1690 if (mkdir(buf
, 0700) < 0) {
1691 if (errno
== EEXIST
) {
1693 fsrprintf(_("tmpdir already exists: %s\n"),
1696 fsrprintf(_("could not create tmpdir: %s: %s\n"),
1697 buf
, strerror(errno
));
1701 for (i
=0; i
< fsgeom
.agcount
; i
++) {
1702 sprintf(buf
, "%s/.fsr/ag%d", mnt
, i
);
1703 if (mkdir(buf
, 0700) < 0) {
1704 if (errno
== EEXIST
) {
1707 _("tmpdir already exists: %s\n"), buf
);
1709 fsrprintf(_("cannot create tmpdir: %s: %s\n"),
1710 buf
, strerror(errno
));
1722 static char buf
[SMBUFSZ
];
1724 sprintf(buf
, "%s/.fsr/ag%d/tmp%d",
1725 ( (strcmp(mnt
, "/") == 0) ? "" : mnt
),
1729 if (++tmp_agi
== fsgeom
.agcount
)
1736 tmp_close(char *mnt
)
1738 static char buf
[SMBUFSZ
];
1741 /* No data is ever actually written so we can just do rmdir's */
1742 for (i
=0; i
< fsgeom
.agcount
; i
++) {
1743 sprintf(buf
, "%s/.fsr/ag%d", mnt
, i
);
1744 if (rmdir(buf
) < 0) {
1745 if (errno
!= ENOENT
) {
1747 _("could not remove tmpdir: %s: %s\n"),
1748 buf
, strerror(errno
));
1752 sprintf(buf
, "%s/.fsr", mnt
);
1753 if (rmdir(buf
) < 0) {
1754 if (errno
!= ENOENT
) {
1755 fsrprintf(_("could not remove tmpdir: %s: %s\n"),
1756 buf
, strerror(errno
));