]> git.hungrycats.org Git - btrfs-progs/commitdiff
btrfs-progs: mkfs: add a sorted directory walker for reproducible -r
authorLeo Martins <loemra.dev@gmail.com>
Thu, 28 May 2026 21:44:48 +0000 (14:44 -0700)
committerQu Wenruo <wqu@suse.com>
Sat, 3 Oct 2026 22:40:52 +0000 (09:10 +1030)
mkfs.btrfs -r walks the source tree with nftw(), which returns entries in
the source filesystem's readdir() order. That order comes from the
filesystem, not the tree: ext4 uses a name hash with a per-fs seed, xfs a
b+tree key order, tmpfs and btrfs insertion order. Discovery order then
decides inode numbers, dir_index values, extent bytenrs, and which
hardlink owns the data, so the same tree staged on two different
filesystems produces two different images.

Add path_sorted_walk() in common/path-utils, which sorts each directory's
entries by name (byte-wise strcmp, not the locale-dependent strcoll)
before recursing. It keeps nftw()'s callback signature and
preorder/FTW_PHYS semantics. ftw_add_inode() still needs a NULL-stat
guard: the walker reports a failed lstat() as FTW_NS with a NULL stat
where glibc nftw() passes a buffer, so the callback skips it instead of
dereferencing. The walker also matches
the two nftw() edges the callbacks depend on: an unreadable directory is
reported once as FTW_DNR, and errno is checked after the readdir() loop
since readdir() returns NULL for both end-of-stream and error. The child
path is heap-allocated so a deep tree doesn't overflow the stack.

A sorted traversal means reading a whole directory up front plus the qsort
and allocations that go with it. A regular mkfs doesn't need that, so keep
nftw() as the default and only sort when a reproducible image is actually
requested, i.e. when both SOURCE_DATE_EPOCH and DETERMINISTIC_SEED are set
(reproducible_is_enabled()). Setting just one can't produce a reproducible
image anyway, since the other source of nondeterminism (host time, or
random UUIDs) still leaks in. btrfs_mkfs_size_dir() stays on nftw()
regardless; it only sums sizes and counts inodes, so walk order doesn't
matter there.

The same reproducible mode sorts each inode's xattrs by name in
add_xattr_item(), the xattr counterpart of sorting directory entries. It
only matters when two names collide under btrfs_name_hash() and share a
dir_item stored in insertion order, but sorting removes the dependence.

Signed-off-by: Leo Martins <loemra.dev@gmail.com>
common/path-utils.c
common/path-utils.h
common/reproducible.c
common/reproducible.h
mkfs/rootdir.c

index 3ce312348de1764821cc13477709289608d2eecf..893ae0a9fbd18e8fbaccec10413b7f18c158dc1d 100644 (file)
@@ -20,7 +20,9 @@
 #include <linux/kdev_t.h>
 #include <linux/loop.h>
 #include <linux/limits.h>
+#include <dirent.h>
 #include <fcntl.h>
+#include <ftw.h>
 #include <unistd.h>
 #include <stdlib.h>
 #include <stdio.h>
@@ -508,3 +510,141 @@ int path_readlink(char *dest, const char *src)
        dest[ret] = 0;
        return ret;
 }
+
+struct path_walk_entry {
+       char *name;
+};
+
+static int path_walk_entry_cmp(const void *a, const void *b)
+{
+       const struct path_walk_entry *ea = a;
+       const struct path_walk_entry *eb = b;
+
+       return strcmp(ea->name, eb->name);
+}
+
+/*
+ * Emulate nftw()'s depth-first, preorder, FTW_PHYS walk, but visit each
+ * directory's entries in sorted name order. The struct FTW fields are filled
+ * the way nftw() reports them so existing nftw() callbacks work unchanged.
+ */
+static int path_sorted_walk_recursive(char *path, int level, path_walk_cb cb)
+{
+       struct stat st;
+       struct FTW ftwbuf;
+       struct path_walk_entry *entries = NULL;
+       size_t count = 0, cap = 0;
+       DIR *dir = NULL;
+       struct dirent *de;
+       const char *slash;
+       int ret;
+
+       slash = strrchr(path, '/');
+       ftwbuf.base = slash ? (int)(slash - path + 1) : 0;
+       ftwbuf.level = level;
+
+       if (lstat(path, &st) != 0)
+               return cb(path, NULL, FTW_NS, &ftwbuf);
+
+       if (!S_ISDIR(st.st_mode)) {
+               if (S_ISLNK(st.st_mode))
+                       return cb(path, &st, FTW_SL, &ftwbuf);
+               return cb(path, &st, FTW_F, &ftwbuf);
+       }
+
+       /*
+        * Open the directory before reporting it: one we can lstat() but not
+        * open is reported once as FTW_DNR, not FTW_D then FTW_DNR.
+        */
+       dir = opendir(path);
+       if (!dir)
+               return cb(path, &st, FTW_DNR, &ftwbuf);
+
+       ret = cb(path, &st, FTW_D, &ftwbuf);
+       if (ret)
+               goto cleanup;
+
+       /*
+        * readdir() returns NULL at both end-of-stream and error; clear
+        * errno before each call to tell them apart after the loop.
+        */
+       while (1) {
+               errno = 0;
+               de = readdir(dir);
+               if (!de)
+                       break;
+               if (strcmp(de->d_name, ".") == 0 ||
+                   strcmp(de->d_name, "..") == 0)
+                       continue;
+               if (count == cap) {
+                       struct path_walk_entry *new_entries;
+
+                       cap = cap ? cap * 2 : 16;
+                       new_entries = reallocarray(entries, cap,
+                                                  sizeof(*entries));
+                       if (!new_entries) {
+                               ret = -ENOMEM;
+                               goto cleanup;
+                       }
+                       entries = new_entries;
+               }
+               entries[count].name = strndup(de->d_name, NAME_MAX);
+               if (!entries[count].name) {
+                       ret = -ENOMEM;
+                       goto cleanup;
+               }
+               count++;
+       }
+       if (errno != 0) {
+               ret = -errno;
+               goto cleanup;
+       }
+       closedir(dir);
+       dir = NULL;
+
+       if (count)
+               qsort(entries, count, sizeof(*entries), path_walk_entry_cmp);
+
+       for (size_t i = 0; i < count; i++) {
+               char *child = malloc(PATH_MAX);
+
+               if (!child) {
+                       ret = -ENOMEM;
+                       goto cleanup;
+               }
+               ret = path_cat_out(child, path, entries[i].name);
+               if (!ret)
+                       ret = path_sorted_walk_recursive(child, level + 1, cb);
+               free(child);
+               if (ret)
+                       goto cleanup;
+       }
+       ret = 0;
+
+cleanup:
+       if (dir)
+               closedir(dir);
+       for (size_t i = 0; i < count; i++)
+               free(entries[i].name);
+       free(entries);
+       return ret;
+}
+
+int path_sorted_walk(const char *root, path_walk_cb cb)
+{
+       char path[PATH_MAX];
+       size_t root_len = strlen(root);
+
+       /* glibc nftw() rejects an empty path with ENOENT and no callback. */
+       if (root_len == 0)
+               return -ENOENT;
+       if (root_len >= sizeof(path))
+               return -ENAMETOOLONG;
+       memcpy(path, root, root_len + 1);
+
+       /* Strip trailing slashes (but keep a lone "/"), matching nftw. */
+       while (root_len > 1 && path[root_len - 1] == '/')
+               path[--root_len] = '\0';
+
+       return path_sorted_walk_recursive(path, 0, cb);
+}
index 7719d0fd5bcdd156163cf26f2b39fcaaa4477674..29182fd92b1da8814c74236f8d67c82161a4c952 100644 (file)
@@ -18,7 +18,9 @@
 #define __BTRFS_PATH_UTILS_H__
 
 #include <sys/types.h>
+#include <sys/stat.h>
 #include <linux/limits.h>
+#include <ftw.h>
 
 char *path_canonicalize_dm_name(const char *ptname);
 char *path_canonicalize(const char *path);
@@ -38,4 +40,30 @@ char *path_basename(char *path);
 char *path_dirname(char *path);
 int path_readlink(char *dest, const char *src);
 
+/*
+ * Callback for path_sorted_walk(), matching nftw()'s callback signature
+ * so existing nftw() callbacks can be reused unchanged.
+ *
+ *   st     : lstat() result, or NULL when type == FTW_NS
+ *   type   : FTW_F, FTW_D (pre-order), FTW_SL (never followed),
+ *            FTW_DNR (unreadable directory) or FTW_NS (lstat failed)
+ *   ftwbuf : level (depth, 0 at the root) and base (basename offset)
+ *
+ * Return 0 to continue the walk, non-zero to abort it (that value is
+ * then returned by path_sorted_walk()).
+ */
+typedef int (*path_walk_cb)(const char *path, const struct stat *st,
+                           int type, struct FTW *ftwbuf);
+
+/*
+ * Walk a directory tree depth-first, pre-order, visiting the entries of
+ * each directory in byte-wise (strcmp) name order. Symlinks are never
+ * followed (FTW_PHYS). Sorting makes the walk order independent of the
+ * filesystem's readdir() order.
+ *
+ * Returns 0 on success, the callback's non-zero return value if it
+ * aborted, or -errno on I/O failure.
+ */
+int path_sorted_walk(const char *root, path_walk_cb cb);
+
 #endif
index f8bca5d8aeb16c4581d3e4d7d1538b0feb21f02e..4e9f8164005e807a0b349ed223a20d3d689808f9 100644 (file)
@@ -54,6 +54,11 @@ bool reproducible_is_deterministic(void)
        return v && strcmp(v, "1") == 0;
 }
 
+bool reproducible_is_enabled(void)
+{
+       return reproducible_has_source_date() && reproducible_is_deterministic();
+}
+
 void reproducible_uuid_generate(const u8 fs_uuid[BTRFS_UUID_SIZE],
                                enum reproducible_uuid_role role, u64 key,
                                u8 out[BTRFS_UUID_SIZE])
index 4edd6e9a22c1afdcdb4f7b44eb8ea9c3ca230345..1cbe5cec7ca1daf8cfb175f433f450013c222926 100644 (file)
@@ -33,6 +33,9 @@ bool reproducible_has_source_date(void);
 
 bool reproducible_is_deterministic(void);
 
+/* True when SOURCE_DATE_EPOCH is non-empty and DETERMINISTIC_SEED is "1". */
+bool reproducible_is_enabled(void);
+
 enum reproducible_uuid_role {
        REPRODUCIBLE_UUID_ROLE_CHUNK_TREE,      /* singleton, key ignored */
        REPRODUCIBLE_UUID_ROLE_SUBVOL,          /* key = subvolume objectid */
index 7109f16bbf4fc088800f86efd7239378e42ffb6e..0b5dbee12ccaca651beffd90236e16c0ec65298a 100644 (file)
@@ -310,6 +310,11 @@ static void stat_to_inode_item(struct btrfs_inode_item *dst, const struct stat *
        btrfs_set_stack_timespec_nsec(&dst->otime, 0);
 }
 
+static int xattr_name_cmp(const void *a, const void *b)
+{
+       return strcmp(*(const char * const *)a, *(const char * const *)b);
+}
+
 static int add_xattr_item(struct btrfs_trans_handle *trans,
                          struct btrfs_root *root, u64 objectid,
                          const char *file_name)
@@ -320,6 +325,9 @@ static int add_xattr_item(struct btrfs_trans_handle *trans,
        char *xattr_list_end;
        char *cur_name;
        char cur_value[XATTR_SIZE_MAX];
+       char **names = NULL;
+       size_t nr_names = 0;
+       size_t i;
 
        ret = llistxattr(file_name, xattr_list, XATTR_LIST_MAX);
        if (ret < 0) {
@@ -332,17 +340,37 @@ static int add_xattr_item(struct btrfs_trans_handle *trans,
                return ret;
 
        xattr_list_end = xattr_list + ret;
-       cur_name = xattr_list;
-       while (cur_name < xattr_list_end) {
+
+       for (cur_name = xattr_list; cur_name < xattr_list_end;
+            cur_name += strlen(cur_name) + 1)
+               nr_names++;
+
+       names = malloc(nr_names * sizeof(*names));
+       if (!names) {
+               error("not enough memory to process xattrs of %s", file_name);
+               return -ENOMEM;
+       }
+       i = 0;
+       for (cur_name = xattr_list; cur_name < xattr_list_end;
+            cur_name += strlen(cur_name) + 1)
+               names[i++] = cur_name;
+
+       /* llistxattr() order is filesystem-defined. */
+       if (reproducible_is_enabled())
+               qsort(names, nr_names, sizeof(*names), xattr_name_cmp);
+
+       for (i = 0; i < nr_names; i++) {
+               cur_name = names[i];
                cur_name_len = strlen(cur_name);
 
                ret = lgetxattr(file_name, cur_name, cur_value, XATTR_SIZE_MAX);
                if (ret < 0) {
                        if (errno == ENOTSUP)
-                               return 0;
-                       error("getting a xattr value failed for %s attr %s: %m",
-                               file_name, cur_name);
-                       return ret;
+                               ret = 0;
+                       else
+                               error("getting a xattr value failed for %s attr %s: %m",
+                                       file_name, cur_name);
+                       goto out;
                }
 
                ret = btrfs_insert_xattr_item(trans, root, cur_name,
@@ -353,10 +381,9 @@ static int add_xattr_item(struct btrfs_trans_handle *trans,
                        error("inserting a xattr item failed for %s: %m",
                                        file_name);
                }
-
-               cur_name += cur_name_len + 1;
        }
-
+out:
+       free(names);
        return ret;
 }
 
@@ -1853,10 +1880,19 @@ static int ftw_add_inode(const char *full_path, const struct stat *st,
        struct btrfs_inode_item inode_item = { 0 };
        struct inode_entry *parent;
        struct rootdir_subvol *rds;
-       const bool have_hard_links = (!S_ISDIR(st->st_mode) && st->st_nlink > 1);
+       bool have_hard_links;
        u64 ino;
        int ret;
 
+       /*
+        * No stat (FTW_NS) or unreadable directory (FTW_DNR): abort rather
+        * than dereference a NULL st.
+        */
+       if (typeflag == FTW_NS || typeflag == FTW_DNR)
+               return -EPERM;
+
+       have_hard_links = (!S_ISDIR(st->st_mode) && st->st_nlink > 1);
+
        /* The rootdir itself. */
        if (unlikely(ftwbuf->level == 0)) {
                u64 root_ino;
@@ -2181,7 +2217,14 @@ int btrfs_mkfs_fill_dir(struct btrfs_trans_handle *trans, const char *source_dir
        g_do_reflink = do_reflink;
        INIT_LIST_HEAD(&current_path.inode_list);
 
-       ret = nftw(source_dir, ftw_add_inode, 32, FTW_PHYS);
+       /*
+        * A reproducible image needs a sorted traversal, which costs extra
+        * allocation and CPU. A regular mkfs doesn't, so use nftw() there.
+        */
+       if (reproducible_is_enabled())
+               ret = path_sorted_walk(source_dir, ftw_add_inode);
+       else
+               ret = nftw(source_dir, ftw_add_inode, 32, FTW_PHYS);
        if (ret) {
                error("unable to traverse directory %s: %d", source_dir, ret);
                return ret;
@@ -2278,11 +2321,16 @@ u64 btrfs_mkfs_size_dir(const char *dir_name, u32 sectorsize, u64 min_dev_size,
        /*
         * Symbolic link is not followed when creating files, so no need to
         * follow them here.
+        *
+        * This pass only sums file sizes and counts inodes, a result that is
+        * independent of walk order, so it always uses nftw() -- the sorted
+        * walk (see btrfs_mkfs_fill_dir()) is only needed where the order
+        * feeds the on-disk layout.
         */
        ret = nftw(dir_name, ftw_add_entry_size, 10, FTW_PHYS);
        rb_free_nodes(&hardlink_root, free_one_hardlink);
        if (ret < 0) {
-               error("ftw subdir walk of %s failed: %m", dir_name);
+               error("unable to walk subdir of %s: %m", dir_name);
                exit(1);
        }