# Maintain the integrity of filesystems

> Watch free space and inodes with df and du, check and repair ext and XFS filesystems, and tune them with tune2fs.

Source: https://aminbytes.dev/bytes/devices-and-filesystems/filesystem-integrity/


A full disk stops a server cold: logs can't be written, databases refuse to save, and sometimes you can't even log in. A damaged filesystem is worse, because files quietly go missing. This byte is about seeing problems early and fixing the simple ones yourself.

You'll use three groups of tools: `df` and `du` to watch space, `fsck` and friends to check and repair, and the ext and XFS tools to look inside and tune.

## Two things can run out: blocks and inodes

A filesystem stores file contents in **blocks**, usually 4 KiB each. Every file also needs one **inode**: a small record that holds the file's size, owner, permissions, timestamps and where its blocks are. The file name lives in the directory, not in the inode.

On ext2/3/4, the number of inodes is fixed when you create the filesystem. So a disk can be "full" in two ways: no free blocks, or no free inodes.

## df: free space per filesystem

`df` (disk free) shows every mounted filesystem. Add `-h` for human sizes and `-T` for the type:

```console
$ df -hT
Filesystem     Type      Size  Used Avail Use% Mounted on
udev           devtmpfs  1.9G     0  1.9G   0% /dev
tmpfs          tmpfs     392M  1.1M  391M   1% /run
/dev/sda3      ext4       37G  8.2G   27G  24% /
/dev/sda1      vfat     1022M  6.1M 1016M   1% /boot/efi
/dev/sdb1      xfs       9.9G  104M  9.8G   2% /srv/data
```

Notice that Used plus Avail on `/` is less than Size. That's not a bug: ext filesystems keep **5% reserved** for root by default, so the system can still write logs when users fill the disk.

`df -i` shows inodes instead of blocks:

```console
$ df -i /
Filesystem      Inodes  IUsed   IFree IUse% Mounted on
/dev/sda3      2424832 187654 2237178    8% /
```

If IUse% hits 100%, you get "No space left on device" even though `df -h` shows free space. The usual cause is a directory with millions of tiny files: a mail queue, session files or a cache.

Handy `df` options: `-h` human sizes, `-T` type, `-i` inodes, `-t ext4` only this type, `-x tmpfs` exclude a type, and a path (`df -h /var`) to see only the filesystem that holds it.

## du: who is using the space

`du` (disk usage) adds up the size of files and directories. `df` tells you *that* a disk is full, `du` tells you *what* filled it:

```console
$ sudo du -sh /var/log
412M	/var/log
$ sudo du -h --max-depth=1 /var | sort -h
4.0K	/var/mail
16K	/var/opt
1.2M	/var/backups
88M	/var/cache
412M	/var/log
1.3G	/var/lib
1.8G	/var
```

| Option | Does |
| --- | --- |
| `-s` | summary: one total per argument |
| `-h` | human sizes (K, M, G) |
| `-c` | add a grand total line |
| `-a` | list files too, not only directories |
| `-d N`, `--max-depth=N` | only show N levels deep |
| `-x` | stay on one filesystem (skip mounts below) |
| `--inodes` | count inodes instead of size (GNU du) |

`du --inodes -d 1 /var | sort -n` finds the directory that eats your inodes.

> [!TIP]
> When `df` says the disk is full but `du` can't find the space, a process probably holds a **deleted file** open. The space only comes back when the process closes it. `sudo lsof +L1` lists those files, and restarting the service frees the space.

## fsck: check and repair

`fsck` (file system check) is a front end, like `mkfs`. It finds the filesystem type and runs the right checker: `fsck.ext4` (which is `e2fsck`), `fsck.vfat`, `fsck.xfs` and so on.

> [!CAUTION]
> Never repair a mounted filesystem. The kernel and fsck would both write to it, and you can lose data. Unmount it first. For the root filesystem, check it at boot or from a rescue system.

```console
$ sudo umount /dev/sdb1
$ sudo fsck /dev/sdb1
fsck from util-linux 2.38.1
e2fsck 1.47.0 (5-Feb-2023)
data: clean, 11/38400 files, 7862/153600 blocks
```

"clean" means the filesystem was unmounted properly, so e2fsck skipped the full check. Force one with `-f`.

| Option | Does |
| --- | --- |
| `-A` | check every filesystem in `/etc/fstab` (in pass order) |
| `-t ext4` | only this type |
| `-N` | dry run: show what would be run |
| `-n` | check only, answer "no" to every repair question |
| `-y` | answer "yes" to every repair question |
| `-p` (or `-a`) | "preen": fix safe problems without asking |
| `-f` | force a full check even if it looks clean (passed to e2fsck) |
| `-C` | show a progress bar |

When fsck finishes, its **exit code** tells you what happened. The values add up, so 3 means "errors fixed, please reboot":

| Code | Meaning |
| --- | --- |
| 0 | no errors |
| 1 | errors were corrected |
| 2 | errors corrected, reboot needed |
| 4 | errors left uncorrected |
| 8 | operational error |
| 16 | usage or syntax error |
| 32 | cancelled by the user |
| 128 | shared library error |

### Checks at boot

The last field in each `/etc/fstab` line decides the boot-time check: `1` for the root filesystem, `2` for the others, `0` for never. On systemd systems, `systemd-fsck-root.service` and `systemd-fsck@.service` run these checks. To force a full check on the next boot, add `fsck.mode=force` to the kernel command line (and `fsck.repair=yes` to fix without asking). On old SysV systems you did the same with `touch /forcefsck` or `shutdown -F -r now`.

## The ext tools: e2fsck, mke2fs, tune2fs

### e2fsck

`e2fsck` is the real checker for ext2, ext3 and ext4. It runs five passes:

```console
$ sudo e2fsck -f /dev/sdb1
e2fsck 1.47.0 (5-Feb-2023)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
data: 11/38400 files (0.0% non-contiguous), 7862/153600 blocks
```

Files that lost their directory entry end up in `lost+found` at the top of the filesystem, named by inode number like `#12345`.

The **superblock** is the filesystem's master record: size, block size, inode count, state. ext keeps backup copies. If the main one is damaged, point e2fsck at a backup:

```bash
sudo e2fsck -b 32768 /dev/sdb1
```

### mke2fs

`mke2fs` creates ext filesystems. `mkfs.ext4` is the same program. You saw it in the last byte. Some options matter for integrity later:

```bash
sudo mke2fs -t ext4 -L data -m 1 -i 8192 /dev/sdb1
```

- `-t ext4` the ext version (`ext2`, `ext3`, `ext4`), `-L` a label
- `-m 1` reserve 1% for root instead of 5%
- `-i 8192` one inode per 8 KiB of space (more inodes for lots of small files), or `-N` for an exact count
- `-j` add a journal (makes ext3 out of ext2)
- `-c` check for bad blocks first
- `-n` dry run: show what it *would* do, without writing anything

That last one is a lifesaver. Lost the backup superblock locations? `mke2fs -n` prints them, as long as you use the same options as when the filesystem was made. Default settings come from `/etc/mke2fs.conf`.

> [!WARNING]
> Mind the letter: `mke2fs -n` is harmless, `mke2fs` without `-n` wipes the partition.

### tune2fs

`tune2fs` changes settings of an existing ext filesystem. `-l` lists the superblock:

```console
$ sudo tune2fs -l /dev/sdb1 | grep -Ei 'volume name|inode count|reserved block|free inodes|mount count|checked|interval'
Filesystem volume name:   data
Inode count:              38400
Reserved block count:     7680
Free inodes:              38389
Mount count:              3
Maximum mount count:      -1
Last checked:             Tue Dec  1 09:12:44 2026
Check interval:           0 (<none>)
```

A maximum mount count of `-1` means "never force a check because of mounts", which is the default today.

| Option | Does | Example |
| --- | --- | --- |
| `-l` | list superblock info | `tune2fs -l /dev/sdb1` |
| `-L` | set the label | `tune2fs -L backup /dev/sdb1` |
| `-c` | check after this many mounts (`0` or `-1` = off) | `tune2fs -c 30 /dev/sdb1` |
| `-C` | set the current mount count | `tune2fs -C 31 /dev/sdb1` |
| `-i` | check after this time (`d`, `w`, `m`) | `tune2fs -i 3m /dev/sdb1` |
| `-m` | reserved blocks percentage | `tune2fs -m 1 /dev/sdb1` |
| `-j` | add a journal (ext2 to ext3) | `tune2fs -j /dev/sdb1` |
| `-e` | what to do on errors: `continue`, `remount-ro`, `panic` | `tune2fs -e remount-ro /dev/sdb1` |
| `-U` | set a new UUID | `tune2fs -U random /dev/sdb1` |
| `-O` | turn features on or off | `tune2fs -O ^has_journal /dev/sdb1` |

 (Side note: `dumpe2fs /dev/sdb1` prints everything tune2fs `-l` shows, plus details for every block group, including where each backup superblock lives.)

## The XFS tools: xfs_repair, xfs_fsr, xfs_db

XFS (the RHEL default) has its own toolbox from the `xfsprogs` package. It doesn't really use fsck. `fsck.xfs` exists only so boot scripts don't fail, and by default it just exits with success. XFS replays its journal itself when you mount it.

### xfs_repair

`xfs_repair` checks and repairs an **unmounted** XFS filesystem. Use `-n` (no modify) to only check:

```console
$ sudo umount /srv/data
$ sudo xfs_repair -n /dev/sdb1
Phase 1 - find and verify superblock...
Phase 2 - using internal log
        - zero log...
        - scan filesystem freespace and inode maps...
        - found root inode chunk
Phase 3 - for each AG...
...
Phase 7 - verify link counts...
No modify flag set, skipping filesystem flush and exiting.
```

Drop the `-n` to repair. If it complains that the log has unwritten changes, mount and unmount the filesystem once so the log gets replayed, then run it again. Only if mounting fails, use `-L` to throw the log away. That's a last resort: it can lose the most recent changes.

### xfs_fsr

`xfs_fsr` (filesystem reorganizer) **defragments** XFS while it's mounted and in use. Give it a mount point or device, or no argument to work through every mounted XFS filesystem for up to two hours:

```bash
sudo xfs_fsr -v /srv/data
```

### xfs_db

`xfs_db` is the XFS debugger: it lets you look inside the filesystem's structures. Always open it with `-r` (read-only) unless you know exactly what you're doing. `-c` runs one command:

```console
$ sudo xfs_db -r -c frag /dev/sdb1
actual 1532, ideal 1490, fragmentation factor 2.74%
Note, this number is largely meaningless.
Files on this filesystem average 1.03 extents per file
$ sudo xfs_db -r -c label /dev/sdb1
label = "logs"
```

Other read-only commands: `freesp` (free space summary), `sb 0` then `print` (show the superblock), `uuid`.

Three cousins you'll meet: `xfs_info /srv/data` shows the layout of a mounted XFS, `xfs_admin -L newlabel /dev/sdb1` changes the label, and `xfs_growfs /srv/data` grows it after you enlarge the partition. XFS can't shrink.

## Exam checklist

- `df -h` shows free space per filesystem, `df -i` shows free **inodes**. Out of inodes also gives "No space left on device".
- `du -sh DIR` totals a directory, `du -h --max-depth=1` breaks it down, `-x` stays on one filesystem.
- ext reserves 5% of blocks for root by default. Change it with `mke2fs -m` or `tune2fs -m`.
- Never repair a mounted filesystem. `fsck` is a front end for `fsck.TYPE`. Exit code 0 = OK, 1 = fixed, 4 = errors left.
- fstab's 6th field: `1` root, `2` others, `0` no check. `fsck.mode=force` forces a check at boot on systemd.
- `e2fsck -f` forces a check, `-p` fixes safe problems, `-y` says yes to all, `-b 32768` uses a backup superblock.
- `tune2fs -l` lists, `-c`/`-i` set check intervals, `-L` label, `-m` reserved %, `-j` adds a journal.
- XFS: `xfs_repair` (unmounted, `-n` to only check, `-L` last resort), `xfs_fsr` defragments mounted, `xfs_db -r` inspects.


## Byte check

1. A program fails with "No space left on device", but `df -h` shows the filesystem is only 40% full. What do you check next?
   - **`df -i`, because the filesystem may have run out of inodes** (correct)
   - `du -sh /`, because df is often wrong
   - `tune2fs -c 0`, to stop the disk checks
   Every file needs an inode. Millions of tiny files can use up all inodes while plenty of blocks are still free, and `df -i` shows exactly that.

2. What must be true before you run `e2fsck -f /dev/sdb1` to repair it?
   - The filesystem is mounted read-write
   - **The filesystem is unmounted** (correct)
   - You have run `tune2fs -l` first
   Repairing a mounted filesystem can corrupt it badly, because the kernel and fsck would both change it at once. Unmount it first (or check root from a rescue system).

3. Which tool defragments a **mounted** XFS filesystem?
   - `xfs_repair`
   - `xfs_db`
   - **`xfs_fsr`** (correct)
   `xfs_fsr` (filesystem reorganizer) works on mounted XFS. `xfs_repair` needs it unmounted, and `xfs_db` is a debugger for looking inside.


