Skip to content

Introduce zfs rewrite subcommand #17246

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

amotin
Copy link
Member

@amotin amotin commented Apr 15, 2025

Motivation and Context

For years users were asking for an ability to re-balance pool after vdev addition, de-fragment randomly written files, change some properties for already written files, etc. The closest option would be to either copy and rename a file or send/receive/rename the dataset. Unfortunately all of those options have some downsides.

Description

This change introduces new zfs rewrite subcommand, that allows to rewrite content of specified file(s) as-is without modifications, but at a different location, compression, checksum, dedup, copies and other parameter values. It is faster than read plus write, since it does not require data copying to user-space. It is also faster for sync=always datasets, since without data modification it does not require ZIL writing. Also since it is protected by normal range range locks, it can be done under any other load. Also it does not affect file's modification time or other properties.

How Has This Been Tested?

Manually tested it on FreeBSD. Linux-specific code is not yet tested.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Performance enhancement (non-breaking change which improves efficiency)
  • Code cleanup (non-breaking change which makes code smaller or more readable)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Library ABI change (libzfs, libzfs_core, libnvpair, libuutil and libzfsbootenv)
  • Documentation (a change to man pages or other documentation)

Checklist:

@github-actions github-actions bot added the Status: Work in Progress Not yet ready for general review label Apr 15, 2025
@amotin
Copy link
Member Author

amotin commented Apr 15, 2025

I've tried to find some kernel APIs to wire this to, but found that plenty of Linux file systems each implement their own IOCTL's for similar purposes. I did the same, except the IOCTL number I took almost arbitrary, since ZFS seems quite rough in this area. I am open to any better ideas before this is committed.

@HPPinata
Copy link

This looks amazing! Not having to sift through half a dozen shell scripts every time this comes up to see what currently handles the most edge cases correctly is very much appreciated. Especially with RaidZ expansion, being able to direct users to run a built-in command instead of debating what script to send them to would be very nice.

Also being able to reliably rewrite a live dataset while it's in use without having to worry about skipped files or mtime conflicts would make the whole process much less of a hassle. With the only thing to really worry about being snapshots/space usage this seems as close to perfect as reasonably possible (without diving deep into internals and messing with snapshot immutability). Bravo!

@amotin amotin added the Status: Design Review Needed Architecture or design is under discussion label Apr 16, 2025
@clhedrick
Copy link

thank you. Fixes one of the biggest problems with ZFS.

Is there a way to suspend the process? It might be nice to have it run only during off hours.

@amotin
Copy link
Member Author

amotin commented Apr 16, 2025

Is there a way to suspend the process? It might be nice to have it run only during off hours.

It does one file at a time, and should be killable in between. Signal handling within one huge file can probably be added. Though the question of the process restart is on the user. I didn't plan to go that deep into the area within this PR.

@clhedrick
Copy link

I couldn't find documentation in the files changed, so I have to guess how it actually works. Is it a file at a time? I guess you could feed it with a "find" command. For a system with a billion files, do you have a sense how long this is gong to take? We can do scrubs in a day or two, but rsync is impractically slow. If this is happening at the file system level, that migth be the case here as well.

@stuartthebruce
Copy link

I guess you could feed it with a "find" command.

This will likely be a good use case for GNU Parallel.

@HPPinata
Copy link

I couldn't find documentation in the files changed, so I have to guess how it actually works. Is it a file at a time? I guess you could feed it with a "find" command. For a system with a billion files, do you have a sense how long this is gong to take? We can do scrubs in a day or two, but rsync is impractically slow. If this is happening at the file system level, that migth be the case here as well.

It can take a directory as an argument and there are some recursive functions and iterators in the code so piping find into it should not be necessary. That avoids some userspace file handling overhead, but it still has to go through the contents of each directory one file at a time. I also don't see any parallel execution or threading (though I'm not too familiar with ZFS internals, maybe some of the primitives used here run asynchronously?).

Whether doing parallelism in userspace by just calling it for many files/directories at once or not it should have the required locking to just run in the background and be significantly more elegant than the CP + mtime (or potentially userspace hash) check to make sure files didn't change during the copy process avoiding one of the potential pitfalls of existing solutions.

@amotin
Copy link
Member Author

amotin commented Apr 16, 2025

I haven't benchmarked it deep yet, but unless the files are tiny, I don't expect there is a major need for parallelism. The code in kernel should handle up to 16MB at a time, plus allows ZFS to do read-ahead and write-back on top of that, so there will be quite a lot in the pipeline to saturate the disks and/or the system, especially if there is some compression/checksuming/encryption. And without need to copy data to/from user-space, the only thread will not be doing too much, I think mostly a decompression from ARC. Bunch of small files on a wide HDD pool I suspect may indeed suffer from read latency, but that in user-space we can optimize/parallelize all day long.

@tonyhutter
Copy link
Contributor

tonyhutter commented Apr 16, 2025

I gave this a quick test. It's very fast and does exactly what it says 👍

# Copy ZFS source workspace to pool with compression=off
$ time cp -a ~/zfs /tank2

real	0m0.600s
user	0m0.032s
sys	0m0.519s

$ df -h /tank2
Filesystem      Size  Used Avail Use% Mounted on
tank2           9.3G  893M  8.4G  10% /tank2


# Set compression to 'gzip' and rewrite
$ sudo ./zfs set compression=gzip tank2
$ time sudo ./zfs rewrite -r /tank2

real	0m2.272s
user	0m0.005s
sys	0m0.005s

$ df -h /tank2
Filesystem      Size  Used Avail Use% Mounted on
tank2           9.3G  402M  8.9G   5% /tank2


# Set compression to 'lz4' and rewrite
$ sudo ./zfs set compression=lz4 tank2
$ time sudo ./zfs rewrite -r /tank2
real	0m1.947s
user	0m0.002s
sys	0m0.010s

$ df -h /tank2
Filesystem      Size  Used Avail Use% Mounted on
tank2           9.3G  456M  8.8G   5% /tank2


# Set compression to 'zstd' and rewrite
$ sudo ./zfs set compression=zstd tank2
$ time sudo ./zfs rewrite -r /tank2

real	0m0.616s
user	0m0.003s
sys	0m0.006s

$ df -h /tank2
Filesystem      Size  Used Avail Use% Mounted on
tank2           9.3G  366M  8.9G   4% /tank2

I can already see people writing scripts that go though every dataset, setting the optimal compression, recordsize, etc, and zfs rewrite-ing them.

@amotin
Copy link
Member Author

amotin commented Apr 16, 2025

Cool! Though the recordsize is one of things it can't change, since it would requite real byte-level copy, not just marking existing blocks dirty. I am not sure it can be done under the load in general. At least it would be much more complicated.

@snajpa
Copy link
Contributor

snajpa commented Apr 17, 2025

Umm this is basically same as doing send | recv, isn't it? I mean, in a way, this is already possible to do without any changes, isn't it? Recv will even respect a lower recordsize, if I'm not mistaken - at least when receiving into a pool without large blocks support, it has to do that.

I'm thinking whether we can do better, in the original sense of ZFS "better", meaning "automagic" - what do you think of using snapshots, send|recv, in a loop with ever decreasing delta size and then when the delta isn't decreasing anymore, we could swap those datasets and use (perhaps slightly modified) zfs_resume_fs transparently to the userspace... that way we would get transparent migration into a dataset with different options, that would scratch some itches for people, wouldn't it?

It'd be even cooler if it could coalesce smaller blocks into larger ones, but that potentially implies performance problems with write amplification, I would say if the app writes in smaler chunks that it gets onto disk in such smaller chunks, it's probably for the best to leave them that way. For any practical use-case I could think of though, I would definitely appreciate the ability to split the blocks of a dataset using smaller recordsize.

If there's a way how to make zfs rewrite more automagical, I think it's at least worth considering.

@HPPinata
Copy link

HPPinata commented Apr 17, 2025

send recv has the huge downside of requiring 2x the space, even if you do the delta size thing since it has to send the entire dataset at least once and old data can't be deleted until the new dataset is complete.
Also recv doesn't increase block sizes, it only splits them if they are larger than the other pool supports (and iirc. there have even been some issues with that).
Also that idea sounds a lot more complex than simply walking the directory tree and iterating through the files to mark their records as dirty to cause a rewrite.

we would get transparent migration into a dataset with different options, that would scratch some itches for people, wouldn't it?

Isn't this exactly what rewrite does? Change the options, run it and all the blocks are changed in the background. Without an application even seeing a change to the file. And unlike send recv it only needs a few MB of extra space.

Edit: with the only real exception being record size, but recv also solves that only partially at best and it doesn't look like there's a reasonable way to work around that in a wholly transparent fashion.

@amotin
Copy link
Member Author

amotin commented Apr 19, 2025

  • Added -x flag to not cross mount points.
  • Added signal handling in kernel.
  • Added man page.

@amotin amotin force-pushed the rewrite branch 4 times, most recently from d23a371 to c5f4413 Compare April 19, 2025 22:49
@stuartthebruce
Copy link

Which release is this game changing enhancement likely to land in?

@amotin
Copy link
Member Author

amotin commented Apr 20, 2025

@stuartthebruce So far it haven't landed even in master, so anybody who want to speed it up is welcome to test and comment. In general though, when completed, there is no reason why aside of 2.4.0 it can't be ported back to some 2.3.x of the time.

@stuartthebruce
Copy link

@stuartthebruce So far it haven't landed even in master, so anybody who want to speed it up is welcome to test and comment. In general though, when completed, there is no reason why aside of 2.4.0 it can't be ported back to some 2.3.x of the time.

Good to know there are no obvious blockers from including in a future 2.3.x. Once this hits master I will help by setting up a test system with 1/2PB of 10^9 small files to see if I can break it. Is there any reason to think the code will be sensitive to Linux vs FreeBSD?

@amotin
Copy link
Member Author

amotin commented Apr 20, 2025

Is there any reason to think the code will be sensitive to Linux vs FreeBSD?

IOCTL interface of the kernels is obviously slightly different, requiring OS-specific shims, as with most of other VFS-related code. But seems like not a big problem, as Tony confirmed it works on Linux too from the first try.

@amotin
Copy link
Member Author

amotin commented Apr 20, 2025

Once this hits master

Since this introduces new IOCTL API, I'd appreciate some feedback before it hit master in case some desired functionality might require API changes aside of the flags field I already reserved for later extensions. I was thinking about some options to not rewrite in some cases, but didn't want to pollute the code until I am convinced it is required.

@stuartthebruce
Copy link

Since this introduces new IOCTL API, I'd appreciate some feedback before it hit master in case some desired functionality might require API changes aside of the flags field I already reserved for later extensions. I was thinking about some options to not rewrite in some cases, but didn't want to pollute the code until I am convinced it is required.

OK, I will see if I can find some time this next week to stress test.

@amotin amotin marked this pull request as ready for review April 20, 2025 20:39
@amotin
Copy link
Member Author

amotin commented Apr 29, 2025

@stuartthebruce To specify any times we'd at very least need #16853 to land first.

@amotin
Copy link
Member Author

amotin commented Apr 29, 2025

Added some tests (not yet tested ;)) and opaque arg field into the IOCTLs structure to make it even more future-proof.

@amotin amotin removed the Status: Design Review Needed Architecture or design is under discussion label Apr 29, 2025
@amotin amotin force-pushed the rewrite branch 7 times, most recently from 1e50c20 to 12b0e14 Compare April 30, 2025 18:40
@amotin
Copy link
Member Author

amotin commented May 1, 2025

Test cases would be good

@tonyhutter Added and passed.

@tonyhutter
Copy link
Contributor

You'll want to add some input validation to the zfs rewrite test case. I was able to pass strings instead of numbers to -o|-l and was also able to pass offsets/lengths beyond the file size.

@amotin
Copy link
Member Author

amotin commented May 1, 2025

You'll want to add some input validation to the zfs rewrite test case. I was able to pass strings instead of numbers to -o|-l and was also able to pass offsets/lengths beyond the file size.

Values beyond the file size are not illegal there. Kernel will rewrite only what is actually there. Can just add a check for non-numeric value, if you prefer.

@tonyhutter
Copy link
Contributor

Values beyond the file size are not illegal there. Kernel will rewrite only what is actually there.

We should error out if a user is trying to seek/rewrite pass the end of the file. Maybe they accidentally typed in the wrong offset? dd will print an error if you pass a skip value past the end of an input file, for example.

Also, I'm wondering if we should not allow -r with -o|-l. It's likely a mistake if someone is doing a recursive rewrite with -o|-l, and we should give that feedback to the user. We may also want to error out if they pass [-o|-l] with a directory.

@amotin
Copy link
Member Author

amotin commented May 1, 2025

Values beyond the file size are not illegal there. Kernel will rewrite only what is actually there.

We should error out if a user is trying to seek/rewrite pass the end of the file. Maybe they accidentally typed in the wrong offset? dd will print an error if you pass a skip value past the end of an input file, for example.

I don't think we should, considering the code was planned to work under concurrent load. We should not fail if the file just got truncated. We achieved our goal by doing nothing.

Also, I'm wondering if we should not allow -r with -o|-l. It's likely a mistake if someone is doing a recursive rewrite with -o|-l, and we should give that feedback to the user. We may also want to error out if they pass [-o|-l] with a directory.

It may be a weird combination, but again not illegal. I am actually verifying it in the test, just because I can.

@stuartthebruce
Copy link

Running parallel instances on the other datasets in this test pool appears to have increased the aggregate performance,

These have now finished after 90 hours without any obvious problems,

[root@zfsarchive1 ~]# zfs list
NAME                 USED  AVAIL  REFER  MOUNTPOINT
jbod17              16.8T   910T   136K  /jbod17
jbod17/cal           534G   910T   534G  /jbod17/cal
jbod17/dqr          4.06T   910T  3.97T  /jbod17/dqr
jbod17/grb.exttrig  4.99T   910T  4.98T  /jbod17/grb.exttrig
jbod17/idq          2.51T   910T  2.51T  /jbod17/idq
jbod17/pe.o4        4.73T   910T  4.63T  /jbod17/pe.o4

[root@zfsarchive1 ~]# parallel 'zfs set compression=off {} && time zfs rewrite -r /{}' ::: jbod17/dqr jbod17/grb.exttrig jbod17/idq jbod17/pe.o4                                                                    

real    616m48.074s
user    0m18.245s
sys     52m49.744s

real    1188m48.153s
user    0m14.149s
sys     59m4.946s

real    1544m41.673s
user    0m34.218s
sys     77m23.340s

real    5414m12.459s
user    2m19.411s
sys     135m19.536s

[root@zfsarchive1 ~]# zfs list
NAME                 USED  AVAIL  REFER  MOUNTPOINT
jbod17              39.6T   887T   136K  /jbod17
jbod17/cal           534G   887T   534G  /jbod17/cal
jbod17/dqr          8.63T   887T  4.69T  /jbod17/dqr
jbod17/grb.exttrig  11.4T   887T  6.40T  /jbod17/grb.exttrig
jbod17/idq          9.13T   887T  6.62T  /jbod17/idq
jbod17/pe.o4        9.95T   887T  5.23T  /jbod17/pe.o4

@tonyhutter
Copy link
Contributor

Values beyond the file size are not illegal there. Kernel will rewrite only what is actually there.

We should error out if a user is trying to seek/rewrite pass the end of the file. Maybe they accidentally typed in the wrong offset? dd will print an error if you pass a skip value past the end of an input file, for example.

I don't think we should, considering the code was planned to work under concurrent load. We should not fail if the file just got truncated. We achieved our goal by doing nothing.

Ok, I still think this is weird, but am not going to let it hold up the review. Please document the behavior though:

diff --git a/man/man8/zfs-rewrite.8 b/man/man8/zfs-rewrite.8
index 5fb360d90..86c75e06e 100644
--- a/man/man8/zfs-rewrite.8
+++ b/man/man8/zfs-rewrite.8
@@ -54,6 +54,13 @@ Print names of all successfully rewritten files.
 .It Fl x
 Don't cross file system mount points when recursing.
 .El
+.Pp
+Note: If a
+.Fl l
+or
+.Fl o
+value would cause a rewrite to regions past the end of the file, then those
+regions are silently ignored, and no error is reported.
 .
 .Sh SEE ALSO
 .Xr zfsprops 7

@satmandu
Copy link
Contributor

satmandu commented May 6, 2025

I was using this built against 2.3.2 using sudo zfs rewrite -rv <path_on_zpool> on a 8Tb mirror with ~ 100Gb free and ran out of space, presumably because I used a less compressing compression setting than originally set.

I don't know if documenting that possibility might be helpful to users.

@amotin amotin force-pushed the rewrite branch 2 times, most recently from b31fbb6 to ed5405b Compare May 6, 2025 17:07
@amotin
Copy link
Member Author

amotin commented May 6, 2025

@satmandu I've added few more notes about possible effects.

Copy link
Member

@robn robn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The guts of this looks good to me. I'd like you to consider the change I proposed in zfs_rewrite_path, but that's all I've got. Good work!

Comment on lines 9135 to 9147
if (stat(path, &st) < 0) {
ret = errno;
(void) fprintf(stderr, gettext("failed to stat %s: %s\n"),
path, strerror(errno));
return (ret);
}

if (S_ISREG(st.st_mode)) {
ret = zfs_rewrite_file(path, verbose, args);
} else if (S_ISDIR(st.st_mode) && recurse) {
ret = zfs_rewrite_dir(path, verbose, xdev, st.st_dev, args,
dirs);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I messed with this a bit, and came up with:

Suggested change
if (stat(path, &st) < 0) {
ret = errno;
(void) fprintf(stderr, gettext("failed to stat %s: %s\n"),
path, strerror(errno));
return (ret);
}
if (S_ISREG(st.st_mode)) {
ret = zfs_rewrite_file(path, verbose, args);
} else if (S_ISDIR(st.st_mode) && recurse) {
ret = zfs_rewrite_dir(path, verbose, xdev, st.st_dev, args,
dirs);
}
if (lstat(path, &st) < 0) {
ret = errno;
(void) fprintf(stderr, gettext("failed to stat %s: %s\n"),
path, strerror(errno));
return (ret);
}
if (S_ISREG(st.st_mode)) {
ret = zfs_rewrite_file(path, verbose, args);
} else if (S_ISDIR(st.st_mode) && recurse) {
ret = zfs_rewrite_dir(path, verbose, xdev, st.st_dev, args,
dirs);
} else {
ret = S_ISDIR(st.st_mode) ? EISDIR : EINVAL;
const char *errstr =
(ret == EISDIR) ? "is a directory" : "not a regular file";
(void) fprintf(stderr, gettext("can't rewrite %s: %s\n"),
path, errstr);
}

That is:

  • don't allow a rewrite through a symlink (matches directory mode, protects against cross-device, protects multiple links to same file)
  • show an error if you try to rewrite something that isn't a file
  • show an error if you try to write a directory without -r

The symlink thing I think is important; at least, it surprised me that it worked at all (rewrote the target), and not being the same as directory mode bothered me. The other two are just niceties.

I did think about also limiting to things not on ZFS, because it is strange to me that a zfs command could even have an opinion about non-ZFS filesystems. But, there isn't really a good cross-platform way to find this out, and the ioctl() call will probably fail, so I'm kind of whatever about it.

Copy link
Member Author

@amotin amotin May 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

About lstat() is a good point. Thank you. Fixed.

About the reporting errors I am not sure. I wanted to make possible running it with * not worrying about directory content, and when recursing we do not report errors for non-regular files, so it is kind of consistent.

Limiting to ZFS would be good, but I don't know how. That was actually the first reason I added the -x flag, to at least allow correct use of it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh, I hadn't thought about *, interesting.

The actual thing that confused me originally was zfs-rewrite somedir/, which outputs nothing and returns success. And then it seemed like you might want that for other file types too.

I guess if I had to argue, I'd want more error output, not less, because I can redirect errors away, and I can prefilter by file types if I want with find | xargs.

(Other programs tackle this with a "quiet" option or, less often, a "noisy" option, but I never remember those sort of things exist)

}

free(fullname);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we break the loop for certain kinds of errors from rewrite, like ENOSPC or EDQUOT? Probably not I guess, it's hard to tell for sure that it's the right thing and ctrl-c is right there.

@amotin amotin force-pushed the rewrite branch 2 times, most recently from 6c7d427 to 6e6f97f Compare May 7, 2025 13:54
This allows to rewrite content of specified file(s) as-is without
modifications, but at a different location, compression, checksum,
dedup, copies and other parameter values.  It is faster than read
plus write, since it does not require data copying to user-space.
It is also faster for sync=always datasets, since without data
modification it does not require ZIL writing.  Also since it is
protected by normal range range locks, it can be done under any
other load.  Also it does not affect file's modification time or
other properties.

Signed-off-by:	Alexander Motin <[email protected]>
Sponsored by:	iXsystems, Inc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Status: Code Review Needed Ready for review and testing
Projects
None yet
Development

Successfully merging this pull request may close these issues.

10 participants