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"
15 #include "libfrog/bulkstat.h"
21 #include <sys/ioctl.h>
23 #include <sys/statvfs.h>
24 #include <sys/xattr.h>
27 #define _PATH_FSRLAST "/var/tmp/.fsrlast_xfs"
28 #define _PATH_PROC_MOUNTS "/proc/mounts"
36 /* static int nflag; */
38 /* static int sflag; */
39 static int argv_blksz_dio
;
40 extern int max_ext_size
;
41 static int npasses
= 10;
42 static int startpass
= 0;
44 static struct getbmap
*outmap
= NULL
;
45 static int outmap_size
= 0;
48 static int64_t minimumfree
= 2048;
50 #define MNTTYPE_XFS "xfs"
56 #define TARGETRANGE 10
57 #define BUFFER_MAX (1<<24)
59 static time_t howlong
= 7200; /* default seconds of reorganizing */
60 static char *leftofffile
= _PATH_FSRLAST
; /* where we left off last */
61 static time_t endtime
;
62 static time_t starttime
;
63 static xfs_ino_t leftoffino
= 0;
67 static int fsrfile(char *fname
, xfs_ino_t ino
);
68 static int fsrfile_common( char *fname
, char *tname
, char *mnt
,
69 int fd
, struct xfs_bstat
*statp
);
70 static int packfile(char *fname
, char *tname
, int fd
,
71 struct xfs_bstat
*statp
, struct fsxattr
*fsxp
);
72 static void fsrdir(char *dirname
);
73 static int fsrfs(char *mntdir
, xfs_ino_t ino
, int targetrange
);
74 static void initallfs(char *mtab
);
75 static void fsrallfs(char *mtab
, int howlong
, char *leftofffile
);
76 static void fsrall_cleanup(int timeout
);
77 static int getnextents(int);
78 int xfsrtextsize(int fd
);
79 int xfs_getrt(int fd
, struct statvfs
*sfbp
);
80 char * gettmpname(char *fname
);
81 char * getparent(char *fname
);
82 int fsrprintf(const char *fmt
, ...);
83 int read_fd_bmap(int, struct xfs_bstat
*, int *);
84 int cmp(const void *, const void *);
85 static void tmp_init(char *mnt
);
86 static char * tmp_next(char *mnt
);
87 static void tmp_close(char *mnt
);
89 static struct xfs_fsop_geom fsgeom
; /* geometry of active mounted system */
94 typedef struct fsdesc
{
100 static fsdesc_t
*fs
, *fsbase
, *fsend
;
101 static int fsbufsize
= 10; /* A starting value */
102 static int nfrags
= 0; /* Debug option: Coerse into specific number
104 static int openopts
= O_CREAT
|O_EXCL
|O_RDWR
|O_DIRECT
;
107 xfs_swapext(int fd
, xfs_swapext_t
*sx
)
109 return ioctl(fd
, XFS_IOC_SWAPEXT
, sx
);
113 xfs_fscounts(int fd
, xfs_fsop_counts_t
*counts
)
115 return ioctl(fd
, XFS_IOC_FSCOUNTS
, counts
);
126 main(int argc
, char **argv
)
135 progname
= basename(argv
[0]);
137 setlocale(LC_ALL
, "");
138 bindtextdomain(PACKAGE
, LOCALEDIR
);
143 while ((c
= getopt(argc
, argv
, "C:p:e:MgsdnvTt:f:m:b:N:FV")) != -1) {
160 case 's': /* frag stats only */
163 _("%s: Stats not yet supported for XFS\n"),
168 howlong
= atoi(optarg
);
171 leftofffile
= optarg
;
177 argv_blksz_dio
= atoi(optarg
);
180 npasses
= atoi(optarg
);
183 /* Testing opt: coerses frag count in result */
184 if (getenv("FSRXFSTEST") != NULL
) {
185 nfrags
= atoi(optarg
);
190 printf(_("%s version %s\n"), progname
, VERSION
);
198 * If the user did not specify an explicit mount table, try to use
199 * /proc/mounts if it is available, else /etc/mtab. We prefer
200 * /proc/mounts because it is kernel controlled, while /etc/mtab
201 * may contain garbage that userspace tools like pam_mounts wrote
205 if (access(_PATH_PROC_MOUNTS
, R_OK
) == 0)
206 mtab
= _PATH_PROC_MOUNTS
;
208 mtab
= _PATH_MOUNTED
;
212 setbuf(stdout
, NULL
);
214 starttime
= time(NULL
);
216 /* Save the caller's real uid */
219 pagesize
= getpagesize();
220 fs_table_initialise(0, NULL
, 0, NULL
);
222 for (; optind
< argc
; optind
++) {
223 argname
= argv
[optind
];
225 if (lstat(argname
, &sb
) < 0) {
227 _("%s: could not stat: %s: %s\n"),
228 progname
, argname
, strerror(errno
));
232 if (S_ISLNK(sb
.st_mode
)) {
235 if (stat(argname
, &sb2
) == 0 &&
236 (S_ISBLK(sb2
.st_mode
) ||
237 S_ISCHR(sb2
.st_mode
)))
241 fsp
= fs_table_lookup_mount(argname
);
243 fsp
= fs_table_lookup_blkdev(argname
);
245 fsrfs(fsp
->fs_dir
, 0, 100);
246 } else if (S_ISCHR(sb
.st_mode
)) {
248 "%s: char special not supported: %s\n"),
251 } else if (S_ISDIR(sb
.st_mode
) || S_ISREG(sb
.st_mode
)) {
252 if (!platform_test_xfs_path(argname
)) {
254 "%s: cannot defragment: %s: Not XFS\n"),
258 if (S_ISDIR(sb
.st_mode
))
261 fsrfile(argname
, sb
.st_ino
);
264 _("%s: not fsys dev, dir, or reg file, ignoring\n"),
270 fsrallfs(mtab
, howlong
, leftofffile
);
279 "Usage: %s [-d] [-v] [-g] [-t time] [-p passes] [-f leftf] [-m mtab]\n"
280 " %s [-d] [-v] [-g] xfsdev | dir | file ...\n"
283 " -g Print to syslog (default if stdout not a tty).\n"
284 " -t time How long to run in seconds.\n"
285 " -p passes Number of passes before terminating global re-org.\n"
286 " -f leftoff Use this instead of %s.\n"
287 " -m mtab Use something other than /etc/mtab.\n"
288 " -d Debug, print even more.\n"
289 " -v Verbose, more -v's more verbose.\n"
290 " -V Print version number and exit.\n"
291 ), progname
, progname
, progname
, _PATH_FSRLAST
);
296 * initallfs -- read the mount table and set up an internal form
299 initallfs(char *mtab
)
301 struct mntent_cursor cursor
;
302 struct mntent
*mnt
= NULL
;
307 /* malloc a number of descriptors, increased later if needed */
308 if (!(fsbase
= (fsdesc_t
*)malloc(fsbufsize
* sizeof(fsdesc_t
)))) {
309 fsrprintf(_("out of memory: %s\n"), strerror(errno
));
312 fsend
= (fsbase
+ fsbufsize
- 1);
314 /* find all rw xfs file systems */
318 if (platform_mntent_open(&cursor
, mtab
) != 0){
319 fprintf(stderr
, "Error: can't get mntent entries.\n");
323 while ((mnt
= platform_mntent_next(&cursor
)) != NULL
) {
326 if (strcmp(mnt
->mnt_type
, MNTTYPE_XFS
) != 0 ||
327 stat(mnt
->mnt_fsname
, &sb
) == -1 ||
328 !S_ISBLK(sb
.st_mode
))
331 cp
= strtok(mnt
->mnt_opts
,",");
333 if (strcmp("rw", cp
) == 0)
335 } while ((cp
= strtok(NULL
, ",")) != NULL
);
338 fsrprintf(_("Skipping %s: not mounted rw\n"),
343 if (mi
== fsbufsize
) {
345 if ((fsbase
= (fsdesc_t
*)realloc((char *)fsbase
,
346 fsbufsize
* sizeof(fsdesc_t
))) == NULL
) {
347 fsrprintf(_("out of memory: %s\n"),
352 fsrprintf(_("out of memory on realloc: %s\n"),
356 fs
= (fsbase
+ mi
); /* Needed ? */
359 fs
->dev
= strdup(mnt
->mnt_fsname
);
360 fs
->mnt
= strdup(mnt
->mnt_dir
);
362 if (fs
->dev
== NULL
) {
363 fsrprintf(_("strdup(%s) failed\n"), mnt
->mnt_fsname
);
366 if (fs
->mnt
== NULL
) {
367 fsrprintf(_("strdup(%s) failed\n"), mnt
->mnt_dir
);
373 platform_mntent_close(&cursor
);
376 fsend
= (fsbase
+ numfs
);
378 fsrprintf(_("no rw xfs file systems in mtab: %s\n"), mtab
);
381 if (vflag
|| dflag
) {
382 fsrprintf(_("Found %d mounted, writable, XFS filesystems\n"),
385 for (fs
= fsbase
; fs
< fsend
; fs
++)
386 fsrprintf("\t%-30.30s%-30.30s\n", fs
->dev
, fs
->mnt
);
391 fsrallfs(char *mtab
, int howlong
, char *leftofffile
)
400 xfs_ino_t startino
= 0;
404 fsrprintf("xfs_fsr -m %s -t %d -f %s ...\n", mtab
, howlong
, leftofffile
);
406 endtime
= starttime
+ howlong
;
409 /* where'd we leave off last time? */
410 if (lstat(leftofffile
, &sb
) == 0) {
411 if ( (fd
= open(leftofffile
, O_RDONLY
)) == -1 ) {
412 fsrprintf(_("%s: open failed\n"), leftofffile
);
414 else if ( fstat(fd
, &sb2
) == 0) {
416 * Verify that lstat & fstat point to the
417 * same regular file (no links/no quick spoofs)
419 if ( (sb
.st_dev
!= sb2
.st_dev
) ||
420 (sb
.st_ino
!= sb2
.st_ino
) ||
421 ((sb
.st_mode
& S_IFMT
) != S_IFREG
) ||
422 ((sb2
.st_mode
& S_IFMT
) != S_IFREG
) ||
423 (sb2
.st_uid
!= ROOT
) ||
427 fsrprintf(_("Can't use %s: mode=0%o own=%d"
429 leftofffile
, sb
.st_mode
,
430 sb
.st_uid
, sb
.st_nlink
);
445 if (read(fd
, buf
, SMBUFSZ
) == -1) {
447 fsrprintf(_("could not read %s, starting with %s\n"),
448 leftofffile
, *fs
->dev
);
450 /* Ensure the buffer we read is null terminated */
451 buf
[SMBUFSZ
-1] = '\0';
452 for (fs
= fsbase
; fs
< fsend
; fs
++) {
454 if ((strncmp(buf
,fsname
,strlen(fsname
)) == 0)
455 && buf
[strlen(fsname
)] == ' ') {
463 ptr
= strchr(buf
, ' ');
465 startpass
= atoi(++ptr
);
466 ptr
= strchr(ptr
, ' ');
468 startino
= strtoull(++ptr
, NULL
, 10);
474 /* Init pass counts */
475 for (fsp
= fsbase
; fsp
< fs
; fsp
++) {
476 fsp
->npass
= startpass
+ 1;
478 for (fsp
= fs
; fsp
<= fsend
; fsp
++) {
479 fsp
->npass
= startpass
;
486 fsrprintf(_("START: pass=%d ino=%llu %s %s\n"),
487 fs
->npass
, (unsigned long long)startino
,
491 signal(SIGABRT
, aborter
);
492 signal(SIGHUP
, aborter
);
493 signal(SIGINT
, aborter
);
494 signal(SIGQUIT
, aborter
);
495 signal(SIGTERM
, aborter
);
497 /* reorg for 'howlong' -- checked in 'fsrfs' */
498 while (endtime
> time(NULL
)) {
501 if (npasses
> 1 && !fs
->npass
)
508 fsrprintf(_("couldn't fork sub process:"));
512 error
= fsrfs(fs
->mnt
, startino
, TARGETRANGE
);
517 if (WIFEXITED(error
) && WEXITSTATUS(error
) == 1) {
518 /* child timed out & did fsrall_cleanup */
523 startino
= 0; /* reset after the first time through */
528 if (fs
->npass
== npasses
) {
529 fsrprintf(_("Completed all %d passes\n"), npasses
);
533 fsrall_cleanup(endtime
<= time(NULL
));
537 * fsrall_cleanup -- close files, print next starting location, etc.
540 fsrall_cleanup(int timeout
)
549 fsrprintf(_("%s startpass %d, endpass %d, time %d seconds\n"),
550 progname
, startpass
, fs
->npass
,
551 time(NULL
) - endtime
+ howlong
);
553 /* record where we left off */
554 fd
= open(leftofffile
, O_WRONLY
|O_CREAT
|O_EXCL
, 0644);
556 fsrprintf(_("open(%s) failed: %s\n"),
557 leftofffile
, strerror(errno
));
559 ret
= sprintf(buf
, "%s %d %llu\n", fs
->dev
,
560 fs
->npass
, (unsigned long long)leftoffino
);
561 if (write(fd
, buf
, ret
) < strlen(buf
))
562 fsrprintf(_("write(%s) failed: %s\n"),
563 leftofffile
, strerror(errno
));
570 * fsrfs -- reorganize a file system
573 fsrfs(char *mntdir
, xfs_ino_t startino
, int targetrange
)
575 struct xfs_fd fsxfd
= XFS_FD_INIT_EMPTY
;
580 struct xfs_bstat buf
[GRABSZ
];
583 jdm_fshandle_t
*fshandlep
;
584 xfs_ino_t lastino
= startino
;
586 fsrprintf(_("%s start inode=%llu\n"), mntdir
,
587 (unsigned long long)startino
);
589 fshandlep
= jdm_getfshandle( mntdir
);
591 fsrprintf(_("unable to get handle: %s: %s\n"),
592 mntdir
, strerror( errno
));
596 if ((fsxfd
.fd
= open(mntdir
, O_RDONLY
)) < 0) {
597 fsrprintf(_("unable to open: %s: %s\n"),
598 mntdir
, strerror( errno
));
603 ret
= xfd_prepare_geometry(&fsxfd
);
605 fsrprintf(_("Skipping %s: could not get XFS geometry\n"),
611 memcpy(&fsgeom
, &fsxfd
.fsgeom
, sizeof(fsgeom
));
615 while ((ret
= xfrog_bulkstat(&fsxfd
, &lastino
, GRABSZ
, &buf
[0],
618 struct xfs_bstat
*endp
;
623 /* Each loop through, defrag targetrange percent of the files */
624 count
= (buflenout
* targetrange
) / 100;
626 qsort((char *)buf
, buflenout
, sizeof(struct xfs_bstat
), cmp
);
628 for (p
= buf
, endp
= (buf
+ buflenout
); p
< endp
; p
++) {
629 /* Do some obvious checks now */
630 if (((p
->bs_mode
& S_IFMT
) != S_IFREG
) ||
634 fd
= jdm_open(fshandlep
, p
, O_RDWR
|O_DIRECT
);
636 /* This probably means the file was
637 * removed while in progress of handling
638 * it. Just quietly ignore this file.
641 fsrprintf(_("could not open: "
642 "inode %llu\n"), p
->bs_ino
);
646 /* Don't know the pathname, so make up something */
647 sprintf(fname
, "ino=%lld", (long long)p
->bs_ino
);
649 /* Get a tmp file name */
650 tname
= tmp_next(mntdir
);
652 ret
= fsrfile_common(fname
, tname
, mntdir
, fd
, p
);
654 leftoffino
= p
->bs_ino
;
663 if (endtime
&& endtime
< time(NULL
)) {
671 fsrprintf(_("%s: bulkstat: %s\n"), progname
, strerror(ret
));
680 * To compare bstat structs for qsort.
683 cmp(const void *s1
, const void *s2
)
685 return( ((struct xfs_bstat
*)s2
)->bs_extents
-
686 ((struct xfs_bstat
*)s1
)->bs_extents
);
691 * reorganize by directory hierarchy.
692 * Stay in dev (a restriction based on structure of this program -- either
693 * call efs_{n,u}mount() around each file, something smarter or this)
696 fsrdir(char *dirname
)
698 fsrprintf(_("%s: Directory defragmentation not supported\n"), dirname
);
702 * Sets up the defragmentation of a file based on the
703 * filepath. It collects the bstat information, does
704 * an open on the file and passes this all to fsrfile_common.
711 struct xfs_fd fsxfd
= XFS_FD_INIT_EMPTY
;
712 struct xfs_bstat statbuf
;
713 jdm_fshandle_t
*fshandlep
;
718 fshandlep
= jdm_getfshandle(getparent (fname
) );
720 fsrprintf(_("unable to construct sys handle for %s: %s\n"),
721 fname
, strerror(errno
));
726 * Need to open something on the same filesystem as the
727 * file. Open the parent.
729 fsxfd
.fd
= open(getparent(fname
), O_RDONLY
);
731 fsrprintf(_("unable to open sys handle for %s: %s\n"),
732 fname
, strerror(errno
));
736 error
= xfd_prepare_geometry(&fsxfd
);
738 fsrprintf(_("Unable to get geom on fs for: %s\n"), fname
);
742 error
= xfrog_bulkstat_single(&fsxfd
, ino
, &statbuf
);
744 fsrprintf(_("unable to get bstat on %s: %s\n"),
745 fname
, strerror(error
));
749 fd
= jdm_open(fshandlep
, &statbuf
, O_RDWR
|O_DIRECT
);
751 fsrprintf(_("unable to open handle %s: %s\n"),
752 fname
, strerror(errno
));
756 /* Stash the fs geometry for general use. */
757 memcpy(&fsgeom
, &fsxfd
.fsgeom
, sizeof(fsgeom
));
759 tname
= gettmpname(fname
);
762 error
= fsrfile_common(fname
, tname
, NULL
, fd
, &statbuf
);
775 * This is the common defrag code for either a full fs
776 * defragmentation or a single file. Check as much as
777 * possible with the file, fork a process to setuid to the
778 * target file owner's uid and defragment the file.
779 * This is done so the new extents created in a tmp file are
780 * reflected in the owners' quota without having to do any
781 * special code in the kernel. When the existing extents
782 * are removed, the quotas will be correct. It's ugly but
783 * it saves us from doing some quota re-construction in
784 * the extent swap. The price is that the defragmentation
785 * will fail if the owner of the target file is already at
794 struct xfs_bstat
*statp
)
802 fsrprintf("%s\n", fname
);
805 fsrprintf(_("sync failed: %s: %s\n"), fname
, strerror(errno
));
809 if (statp
->bs_size
== 0) {
811 fsrprintf(_("%s: zero size, ignoring\n"), fname
);
815 /* Check if a mandatory lock is set on the file to try and
816 * avoid blocking indefinitely on the reads later. Note that
817 * someone could still set a mandatory lock after this check
818 * but before all reads have completed to block fsr reads.
819 * This change just closes the window a bit.
821 if ( (statp
->bs_mode
& S_ISGID
) && ( ! (statp
->bs_mode
&S_IXGRP
) ) ) {
825 fl
.l_whence
= SEEK_SET
;
826 fl
.l_start
= (off_t
)0;
828 if ((fcntl(fd
, F_GETLK
, &fl
)) < 0 ) {
830 fsrprintf(_("locking check failed: %s\n"),
834 if (fl
.l_type
!= F_UNLCK
) {
835 /* Mandatory lock is set */
837 fsrprintf(_("mandatory lock: %s: ignoring\n"),
844 * Check if there is room to copy the file.
846 * Note that xfs_bstat.bs_blksize returns the filesystem blocksize,
847 * not the optimal I/O size as struct stat.
849 if (statvfs(fsname
? fsname
: fname
, &vfss
) < 0) {
850 fsrprintf(_("unable to get fs stat on %s: %s\n"),
851 fname
, strerror(errno
));
854 bsize
= vfss
.f_frsize
? vfss
.f_frsize
: vfss
.f_bsize
;
855 if (statp
->bs_blksize
* statp
->bs_blocks
>
856 vfss
.f_bfree
* bsize
- minimumfree
) {
857 fsrprintf(_("insufficient freespace for: %s: "
858 "size=%lld: ignoring\n"), fname
,
859 statp
->bs_blksize
* statp
->bs_blocks
);
863 if ((ioctl(fd
, FS_IOC_FSGETXATTR
, &fsx
)) < 0) {
864 fsrprintf(_("failed to get inode attrs: %s\n"), fname
);
867 if (fsx
.fsx_xflags
& (FS_XFLAG_IMMUTABLE
|FS_XFLAG_APPEND
)) {
869 fsrprintf(_("%s: immutable/append, ignoring\n"), fname
);
872 if (fsx
.fsx_xflags
& FS_XFLAG_NODEFRAG
) {
874 fsrprintf(_("%s: marked as don't defrag, ignoring\n"),
878 if (fsx
.fsx_xflags
& FS_XFLAG_REALTIME
) {
879 if (xfs_getrt(fd
, &vfss
) < 0) {
880 fsrprintf(_("cannot get realtime geometry for: %s\n"),
884 if (statp
->bs_size
> ((vfss
.f_bfree
* bsize
) - minimumfree
)) {
885 fsrprintf(_("low on realtime free space: %s: "
886 "ignoring file\n"), fname
);
891 if ((RealUid
!= ROOT
) && (RealUid
!= statp
->bs_uid
)) {
892 fsrprintf(_("cannot open: %s: Permission denied\n"), fname
);
897 * Previously the code forked here, & the child changed it's uid to
898 * that of the file's owner and then called packfile(), to keep
899 * quota counts correct. (defragged files could use fewer blocks).
901 * Instead, just fchown() the temp file to the uid,gid of the
902 * file we're defragging, in packfile().
905 if ((error
= packfile(fname
, tname
, fd
, statp
, &fsx
)))
907 return -1; /* no error */
911 * Attempt to set the attr fork up correctly. This is simple for attr1
912 * filesystems as they have a fixed inode fork offset. In that case
913 * just create an attribute and that's all we need to do.
915 * For attr2 filesystems, see if we have the actual fork offset in
916 * the bstat structure. If so, just create additional attributes on
917 * the temporary inode until the offset matches.
919 * If it doesn't exist, we can only do best effort. Add an attribute at a time
920 * to move the inode fork around, but take into account that the attribute
921 * might be too small to move the fork every time we add one. This should
922 * hopefully put the fork offset in the right place. It's not a big deal if we
923 * don't get it right - the kernel will reject it when we try to swap extents.
929 struct xfs_bstat
*bstatp
)
931 #ifdef HAVE_FSETXATTR
932 struct xfs_fd txfd
= XFS_FD_INIT(tfd
);
933 struct stat tstatbuf
;
936 int last_forkoff
= 0;
937 int no_change_cnt
= 0;
940 if (!(bstatp
->bs_xflags
& FS_XFLAG_HASATTR
))
944 * use the old method if we have attr1 or the kernel does not yet
945 * support passing the fork offset in the bulkstat data.
947 if (!(fsgeom
.flags
& XFS_FSOP_GEOM_FLAGS_ATTR2
) ||
948 bstatp
->bs_forkoff
== 0) {
950 ret
= fsetxattr(txfd
.fd
, "user.X", "X", 1, XATTR_CREATE
);
952 fsrprintf(_("could not set ATTR\n"));
958 /* attr2 w/ fork offsets */
960 if (fstat(txfd
.fd
, &tstatbuf
) < 0) {
961 fsrprintf(_("unable to stat temp file: %s\n"),
968 struct xfs_bstat tbstat
;
973 * bulkstat the temp inode to see what the forkoff is. Use
974 * this to compare against the target and determine what we
977 ret
= xfrog_bulkstat_single(&txfd
, tstatbuf
.st_ino
, &tbstat
);
979 fsrprintf(_("unable to get bstat on temp file: %s\n"),
984 fsrprintf(_("orig forkoff %d, temp forkoff %d\n"),
985 bstatp
->bs_forkoff
, tbstat
.bs_forkoff
);
986 diff
= tbstat
.bs_forkoff
- bstatp
->bs_forkoff
;
988 /* if they are equal, we are done */
992 snprintf(name
, sizeof(name
), "user.%d", i
);
995 * If there is no attribute, then we need to create one to get
996 * an attribute fork at the default location.
998 if (!tbstat
.bs_forkoff
) {
1000 ret
= fsetxattr(txfd
.fd
, name
, "XX", 2, XATTR_CREATE
);
1002 fsrprintf(_("could not set ATTR\n"));
1006 } else if (i
== 0) {
1008 * First pass, and temp file already has an inline
1009 * xattr, probably due to selinux.
1011 * It's *possible* that the temp file attr area
1012 * is larger than the target file's:
1015 * +-------+ 0 +-------+ 0
1019 * | | v-------v forkoff
1021 * v-------v forkoff | Attr | local
1023 * +-------+ +-------+
1027 * If target attr area is less than the temp's
1028 * (diff < 0) write a big attr to the temp file to knock
1029 * the attr out of local format.
1030 * (This should actually *increase* the temp file's
1031 * forkoffset when the attr moves out of the inode)
1035 memset(val
, 'X', 2048);
1036 if (fsetxattr(txfd
.fd
, name
, val
, 2048, 0)) {
1037 fsrprintf(_("big ATTR set failed\n"));
1040 /* Go back & see where we're at now */
1046 * make a progress check so we don't get stuck trying to extend
1047 * a large btree form attribute fork.
1049 if (last_forkoff
== tbstat
.bs_forkoff
) {
1050 if (no_change_cnt
++ > 10)
1052 } else /* progress! */
1054 last_forkoff
= tbstat
.bs_forkoff
;
1056 /* work out which way to grow the fork */
1057 if (abs(diff
) > fsgeom
.inodesize
- sizeof(struct xfs_dinode
)) {
1058 fsrprintf(_("forkoff diff %d too large!\n"), diff
);
1063 * if the temp inode fork offset is still smaller then we have
1064 * to grow the data fork
1068 * create some temporary extents in the inode to move
1069 * the fork in the direction we need. This can be done
1070 * by preallocating some single block extents at
1071 * non-contiguous offsets.
1073 /* XXX: unimplemented! */
1075 printf(_("data fork growth unimplemented\n"));
1079 /* we need to grow the attr fork, so create another attr */
1080 ret
= fsetxattr(txfd
.fd
, name
, "XX", 2, XATTR_CREATE
);
1082 fsrprintf(_("could not set ATTR\n"));
1086 } while (++i
< 100); /* don't go forever */
1090 fsrprintf(_("set temp attr\n"));
1091 /* We failed to resolve the fork difference */
1093 fsrprintf(_("failed to match fork offset\n"));;
1095 #endif /* HAVE_FSETXATTR */
1100 * Do the defragmentation of a single file.
1101 * We already are pretty sure we can and want to
1102 * defragment the file. Create the tmp file, copy
1103 * the data (maintaining holes) and call the kernel
1104 * extent swap routine.
1107 * -1: Some error was encountered
1108 * 0: Successfully defragmented the file
1109 * 1: No change / No Error
1112 packfile(char *fname
, char *tname
, int fd
,
1113 struct xfs_bstat
*statp
, struct fsxattr
*fsxp
)
1117 int retval
= -1; /* Failure is the default */
1118 int nextents
, extent
, cur_nextents
, new_nextents
;
1122 static xfs_swapext_t sx
;
1123 struct xfs_flock64 space
;
1127 char ffname
[SMBUFSZ
];
1131 * Work out the extent map - nextents will be set to the
1132 * minimum number of extents needed for the file (taking
1133 * into account holes), cur_nextents is the current number
1136 nextents
= read_fd_bmap(fd
, statp
, &cur_nextents
);
1138 if (cur_nextents
== 1 || cur_nextents
<= nextents
) {
1140 fsrprintf(_("%s already fully defragmented.\n"), fname
);
1141 retval
= 1; /* indicates no change/no error */
1146 fsrprintf(_("%s extents=%d can_save=%d tmp=%s\n"),
1147 fname
, cur_nextents
, (cur_nextents
- nextents
),
1150 if ((tfd
= open(tname
, openopts
, 0666)) < 0) {
1152 fsrprintf(_("could not open tmp file: %s: %s\n"),
1153 tname
, strerror(errno
));
1158 /* Setup extended attributes */
1159 if (fsr_setup_attr_fork(fd
, tfd
, statp
) != 0) {
1160 fsrprintf(_("failed to set ATTR fork on tmp: %s:\n"), tname
);
1164 /* Setup extended inode flags, project identifier, etc */
1165 if (fsxp
->fsx_xflags
|| fsxp
->fsx_projid
) {
1166 if (ioctl(tfd
, FS_IOC_FSSETXATTR
, fsxp
) < 0) {
1167 fsrprintf(_("could not set inode attrs on tmp: %s\n"),
1173 if ((ioctl(tfd
, XFS_IOC_DIOINFO
, &dio
)) < 0 ) {
1174 fsrprintf(_("could not get DirectIO info on tmp: %s\n"), tname
);
1178 dio_min
= dio
.d_miniosz
;
1179 if (statp
->bs_size
<= dio_min
) {
1180 blksz_dio
= dio_min
;
1182 blksz_dio
= min(dio
.d_maxiosz
, BUFFER_MAX
- pagesize
);
1183 if (argv_blksz_dio
!= 0)
1184 blksz_dio
= min(argv_blksz_dio
, blksz_dio
);
1185 blksz_dio
= (min(statp
->bs_size
, blksz_dio
) / dio_min
) * dio_min
;
1189 fsrprintf(_("DEBUG: "
1190 "fsize=%lld blsz_dio=%d d_min=%d d_max=%d pgsz=%d\n"),
1191 statp
->bs_size
, blksz_dio
, dio
.d_miniosz
,
1192 dio
.d_maxiosz
, pagesize
);
1195 if (!(fbuf
= (char *)memalign(dio
.d_mem
, blksz_dio
))) {
1196 fsrprintf(_("could not allocate buf: %s\n"), tname
);
1201 /* Create new tmp file in same AG as first */
1202 sprintf(ffname
, "%s.frag", tname
);
1204 /* Open the new file for sync writes */
1205 if ((ffd
= open(ffname
, openopts
, 0666)) < 0) {
1206 fsrprintf(_("could not open fragfile: %s : %s\n"),
1207 ffname
, strerror(errno
));
1213 /* Loop through block map allocating new extents */
1214 for (extent
= 0; extent
< nextents
; extent
++) {
1215 pos
= outmap
[extent
].bmv_offset
;
1216 if (outmap
[extent
].bmv_block
== -1) {
1217 space
.l_whence
= SEEK_SET
;
1218 space
.l_start
= pos
;
1219 space
.l_len
= outmap
[extent
].bmv_length
;
1220 if (ioctl(tfd
, XFS_IOC_UNRESVSP64
, &space
) < 0) {
1221 fsrprintf(_("could not trunc tmp %s\n"),
1224 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1225 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1226 tname
, strerror(errno
));
1230 } else if (outmap
[extent
].bmv_length
== 0) {
1231 /* to catch holes at the beginning of the file */
1235 space
.l_whence
= SEEK_CUR
;
1237 space
.l_len
= outmap
[extent
].bmv_length
;
1239 if (ioctl(tfd
, XFS_IOC_RESVSP64
, &space
) < 0) {
1240 fsrprintf(_("could not pre-allocate tmp space:"
1244 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1245 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1246 tname
, strerror(errno
));
1250 } /* end of space allocation loop */
1252 if (lseek(tfd
, 0, SEEK_SET
)) {
1253 fsrprintf(_("Couldn't rewind on temporary file\n"));
1257 /* Check if the temporary file has fewer extents */
1258 new_nextents
= getnextents(tfd
);
1260 fsrprintf(_("Temporary file has %d extents (%d in original)\n"), new_nextents
, cur_nextents
);
1261 if (cur_nextents
<= new_nextents
) {
1263 fsrprintf(_("No improvement will be made (skipping): %s\n"), fname
);
1264 retval
= 1; /* no change/no error */
1268 /* Loop through block map copying the file. */
1269 for (extent
= 0; extent
< nextents
; extent
++) {
1270 pos
= outmap
[extent
].bmv_offset
;
1271 if (outmap
[extent
].bmv_block
== -1) {
1272 if (lseek(tfd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1273 fsrprintf(_("could not lseek in tmpfile: %s : %s\n"),
1274 tname
, strerror(errno
));
1277 if (lseek(fd
, outmap
[extent
].bmv_length
, SEEK_CUR
) < 0) {
1278 fsrprintf(_("could not lseek in file: %s : %s\n"),
1279 fname
, strerror(errno
));
1283 } else if (outmap
[extent
].bmv_length
== 0) {
1284 /* to catch holes at the beginning of the file */
1287 for (cnt
= outmap
[extent
].bmv_length
; cnt
> 0;
1288 cnt
-= ct
, pos
+= ct
) {
1289 if (nfrags
&& --nfrags
) {
1290 ct
= min(cnt
, dio_min
);
1291 } else if (cnt
% dio_min
== 0) {
1292 ct
= min(cnt
, blksz_dio
);
1294 ct
= min(cnt
+ dio_min
- (cnt
% dio_min
),
1297 ct
= read(fd
, fbuf
, ct
);
1299 /* EOF, stop trying to read */
1303 /* Ensure we do direct I/O to correct block
1306 if (ct
% dio_min
!= 0) {
1307 wc
= ct
+ dio_min
- (ct
% dio_min
);
1312 if (ct
< 0 || ((wc
= write(tfd
, fbuf
, wc
)) != wc_b4
)) {
1314 fsrprintf(_("bad read of %d bytes "
1315 "from %s: %s\n"), wc_b4
,
1316 fname
, strerror(errno
));
1318 fsrprintf(_("bad write of %d bytes "
1319 "to %s: %s\n"), wc_b4
,
1320 tname
, strerror(errno
));
1323 * Might be out of space
1325 * Try to finish write
1329 if ((wc
= write(tfd
, ((char *)fbuf
)+wc
,
1331 /* worked on second attempt? */
1335 fsrprintf(_("bad write2 of %d "
1336 "bytes to %s: %s\n"),
1340 fsrprintf(_("bad copy to %s\n"),
1347 /* Do a matching write to the tmp file */
1349 if (((wc
= write(ffd
, fbuf
, wc
)) != wc_b4
)) {
1350 fsrprintf(_("bad write of %d bytes "
1352 wc_b4
, ffname
, strerror(errno
));
1357 if (ftruncate(tfd
, statp
->bs_size
) < 0) {
1358 fsrprintf(_("could not truncate tmpfile: %s : %s\n"),
1359 fname
, strerror(errno
));
1362 if (fsync(tfd
) < 0) {
1363 fsrprintf(_("could not fsync tmpfile: %s : %s\n"),
1364 fname
, strerror(errno
));
1368 sx
.sx_stat
= *statp
; /* struct copy */
1369 sx
.sx_version
= XFS_SX_VERSION
;
1370 sx
.sx_fdtarget
= fd
;
1373 sx
.sx_length
= statp
->bs_size
;
1375 /* switch to the owner's id, to keep quota in line */
1376 if (fchown(tfd
, statp
->bs_uid
, statp
->bs_gid
) < 0) {
1378 fsrprintf(_("failed to fchown tmpfile %s: %s\n"),
1379 tname
, strerror(errno
));
1383 /* Swap the extents */
1384 srval
= xfs_swapext(fd
, &sx
);
1386 if (errno
== ENOTSUP
) {
1388 fsrprintf(_("%s: file type not supported\n"), fname
);
1389 } else if (errno
== EFAULT
) {
1390 /* The file has changed since we started the copy */
1392 fsrprintf(_("%s: file modified defrag aborted\n"),
1394 } else if (errno
== EBUSY
) {
1395 /* Timestamp has changed or mmap'ed file */
1397 fsrprintf(_("%s: file busy\n"), fname
);
1399 fsrprintf(_("XFS_IOC_SWAPEXT failed: %s: %s\n"),
1400 fname
, strerror(errno
));
1405 /* Report progress */
1407 fsrprintf(_("extents before:%d after:%d %s %s\n"),
1408 cur_nextents
, new_nextents
,
1409 (new_nextents
<= nextents
? "DONE" : " " ),
1423 gettmpname(char *fname
)
1425 static char buf
[PATH_MAX
+1];
1429 sprintf(sbuf
, "/.fsr%d", getpid());
1431 strncpy(buf
, fname
, PATH_MAX
);
1432 buf
[PATH_MAX
] = '\0';
1433 ptr
= strrchr(buf
, '/');
1440 if ((strlen(buf
) + strlen (sbuf
)) > PATH_MAX
) {
1441 fsrprintf(_("tmp file name too long: %s\n"), fname
);
1451 getparent(char *fname
)
1453 static char buf
[PATH_MAX
+1];
1456 strncpy(buf
, fname
, PATH_MAX
);
1457 buf
[PATH_MAX
] = '\0';
1458 ptr
= strrchr(buf
, '/');
1471 * Read in block map of the input file, coalesce contiguous
1472 * extents into a single range, keep all holes. Convert from 512 byte
1475 * This code was borrowed from mv.c with some minor mods.
1478 #define OUTMAP_SIZE_INCREMENT MAPSIZE
1480 int read_fd_bmap(int fd
, struct xfs_bstat
*sin
, int *cur_nextents
)
1483 struct getbmap map
[MAPSIZE
];
1486 if (++cnt >= outmap_size) { \
1487 outmap_size += OUTMAP_SIZE_INCREMENT; \
1488 outmap = (struct getbmap *)realloc(outmap, \
1489 outmap_size*sizeof(*outmap)); \
1490 if (outmap == NULL) { \
1491 fsrprintf(_("realloc failed: %s\n"), \
1497 /* Initialize the outmap array. It always grows - never shrinks.
1498 * Left-over memory allocation is saved for the next files.
1500 if (outmap_size
== 0) {
1501 outmap_size
= OUTMAP_SIZE_INCREMENT
; /* Initial size */
1502 outmap
= (struct getbmap
*)malloc(outmap_size
*sizeof(*outmap
));
1504 fsrprintf(_("malloc failed: %s\n"),
1510 outmap
[0].bmv_block
= 0;
1511 outmap
[0].bmv_offset
= 0;
1512 outmap
[0].bmv_length
= sin
->bs_size
;
1515 * If a non regular file is involved then forget holes
1518 if (!S_ISREG(sin
->bs_mode
))
1521 outmap
[0].bmv_length
= 0;
1523 map
[0].bmv_offset
= 0;
1524 map
[0].bmv_block
= 0;
1525 map
[0].bmv_entries
= 0;
1526 map
[0].bmv_count
= MAPSIZE
;
1527 map
[0].bmv_length
= -1;
1533 if (ioctl(fd
, XFS_IOC_GETBMAP
, map
) < 0) {
1534 fsrprintf(_("failed reading extents: inode %llu"),
1535 (unsigned long long)sin
->bs_ino
);
1539 /* Concatenate extents together and replicate holes into
1542 *cur_nextents
+= map
[0].bmv_entries
;
1543 for (i
= 0; i
< map
[0].bmv_entries
; i
++) {
1544 if (map
[i
+ 1].bmv_block
== -1) {
1546 outmap
[cnt
] = map
[i
+1];
1547 } else if (outmap
[cnt
].bmv_block
== -1) {
1549 outmap
[cnt
] = map
[i
+1];
1551 outmap
[cnt
].bmv_length
+= map
[i
+ 1].bmv_length
;
1554 } while (map
[0].bmv_entries
== (MAPSIZE
-1));
1555 for (i
= 0; i
<= cnt
; i
++) {
1556 outmap
[i
].bmv_offset
= BBTOB(outmap
[i
].bmv_offset
);
1557 outmap
[i
].bmv_length
= BBTOB(outmap
[i
].bmv_length
);
1560 outmap
[cnt
].bmv_length
= sin
->bs_size
- outmap
[cnt
].bmv_offset
;
1566 * Read the block map and return the number of extents.
1572 struct getbmap map
[MAPSIZE
];
1574 map
[0].bmv_offset
= 0;
1575 map
[0].bmv_block
= 0;
1576 map
[0].bmv_entries
= 0;
1577 map
[0].bmv_count
= MAPSIZE
;
1578 map
[0].bmv_length
= -1;
1583 if (ioctl(fd
,XFS_IOC_GETBMAP
, map
) < 0) {
1584 fsrprintf(_("failed reading extents"));
1588 nextents
+= map
[0].bmv_entries
;
1589 } while (map
[0].bmv_entries
== (MAPSIZE
-1));
1595 * Get xfs realtime space information
1598 xfs_getrt(int fd
, struct statvfs
*sfbp
)
1600 unsigned long bsize
;
1601 unsigned long factor
;
1602 xfs_fsop_counts_t cnt
;
1604 if (!fsgeom
.rtblocks
)
1607 if (xfs_fscounts(fd
, &cnt
) < 0) {
1611 bsize
= (sfbp
->f_frsize
? sfbp
->f_frsize
: sfbp
->f_bsize
);
1612 factor
= fsgeom
.blocksize
/ bsize
; /* currently this is == 1 */
1613 sfbp
->f_bfree
= (cnt
.freertx
* fsgeom
.rtextsize
) * factor
;
1618 fsrprintf(const char *fmt
, ...)
1624 static int didopenlog
;
1626 openlog("fsr", LOG_PID
, LOG_USER
);
1629 vsyslog(LOG_INFO
, fmt
, ap
);
1637 * Initialize a directory for tmp file use. This is used
1638 * by the full filesystem defragmentation when we're walking
1639 * the inodes and do not know the path for the individual
1640 * files. Multiple directories are used to spread out the
1641 * tmp data around to different ag's (since file data is
1642 * usually allocated to the same ag as the directory and
1643 * directories allocated round robin from the same
1644 * parent directory).
1650 static char buf
[SMBUFSZ
];
1654 sprintf(buf
, "%s/.fsr", mnt
);
1657 if (mkdir(buf
, 0700) < 0) {
1658 if (errno
== EEXIST
) {
1660 fsrprintf(_("tmpdir already exists: %s\n"),
1663 fsrprintf(_("could not create tmpdir: %s: %s\n"),
1664 buf
, strerror(errno
));
1668 for (i
=0; i
< fsgeom
.agcount
; i
++) {
1669 sprintf(buf
, "%s/.fsr/ag%d", mnt
, i
);
1670 if (mkdir(buf
, 0700) < 0) {
1671 if (errno
== EEXIST
) {
1674 _("tmpdir already exists: %s\n"), buf
);
1676 fsrprintf(_("cannot create tmpdir: %s: %s\n"),
1677 buf
, strerror(errno
));
1689 static char buf
[SMBUFSZ
];
1691 sprintf(buf
, "%s/.fsr/ag%d/tmp%d",
1692 ( (strcmp(mnt
, "/") == 0) ? "" : mnt
),
1696 if (++tmp_agi
== fsgeom
.agcount
)
1703 tmp_close(char *mnt
)
1705 static char buf
[SMBUFSZ
];
1708 /* No data is ever actually written so we can just do rmdir's */
1709 for (i
=0; i
< fsgeom
.agcount
; i
++) {
1710 sprintf(buf
, "%s/.fsr/ag%d", mnt
, i
);
1711 if (rmdir(buf
) < 0) {
1712 if (errno
!= ENOENT
) {
1714 _("could not remove tmpdir: %s: %s\n"),
1715 buf
, strerror(errno
));
1719 sprintf(buf
, "%s/.fsr", mnt
);
1720 if (rmdir(buf
) < 0) {
1721 if (errno
!= ENOENT
) {
1722 fsrprintf(_("could not remove tmpdir: %s: %s\n"),
1723 buf
, strerror(errno
));