If some of your files are big, it might be technically impossible to defragment them all without reformating the filesystem.
Any ext4 filesystem is composed of a sequence of block groups. By default, each block group is 128 MiB long.
Each block group starts with a bunch of filesystem metadata (superblock, group descriptor, allocation bitmaps, and inode tables) followed by actual data blocks used by files belonging to that block group. This means that filesystem metadata are scattered mostly uniformly across the entire device.
However, thanks to the optional flex_bg
feature, several block groups can be aggregated together into a single bigger one. mke2fs
has been creating filesystems by default with 16 block groups packed together since 2008-ish. Assuming you haven't changed this when making the filesystem using the -G
option to mkfs, your filesystem is thus likely split into 2-GiB flex groups.
Unless all your files are significantly smaller than 2 GiB, you would thus inevitably run into a situation where the next file to store would have to be fragmented across two or more (flex) block groups. Of course this is guaranteed to happen if any of your files is bigger than the usable data blocks in a (flex) block group.
To achieve your goal, you will thus likely have to reformat the filesystem with a much higher setting of the -G
option than the default 16 to make the filesystem use really big flex block groups.