如何将你的文件系统转换为 Btrfs
Btrfs 文件系统
![](/data/attachment/album/202205/11/154616z17eu5uurn31n3th.png)


### 引言


这篇概述文章将告诉你为何以及如何迁移你的当前分区到 Btrfs 文件系统。如果你对此感兴趣，请阅读这篇分步指南来完成。


从 Fedora 33 开始，新安装的 Fedora 操作系统默认文件系统为 Btrfs。我确信大部分用户现在已经听说了它的优势：写时复制、内置校验、灵活的压缩方式、简易的快照和回滚方式。它确实是一个现代化的文件系统，为桌面存储带来新的功能。


在升级到 Fedora 33 后，我想利用 Btrfs 的优势，但对我个人来说，我不想因为“只是为了改变文件系统”而去重装整个系统。我发现（只有）寥寥无几的具体如何做转换的教程，所以我决定在这里分享我的详细经验。


### 小心！


这样做你是在玩火。希望你阅读以下内容时不要感到惊讶：



> 
> 在编辑分区和转换文件系统时，你的数据可能会被破坏和丢失。最终，你可能会得到一个不能启动的操作系统，并面临数据恢复的风险。你可能会无意删除你的分区，或者以其它方式破坏了你的操作系统。
> 
> 
> 


这些转换过程即使对于生产系统来说也是安全的 —— 前提是你提前做好了计划，对关键数据做好了备份和回滚计划。作为一个 *可以执行超级权限的系统管理员*，你可以在没有限制、没有任何常规安全防护措施的情况下，做任何事情。


### 安全的方式：重装 Fedora


重装操作系统是转换文件系统到 Btrfs 的 “官方” 方式，推荐给大多数用户使用。因此，如果在这个教程中有那么一点不确定，就选择这种方式。步骤大致如下：


1. 备份你的主文件夹和你系统中可能会用到的任何数据，比如 `/etc`。（编者按：虚拟机也是这样）
2. 将已安装的安装包以列表形式保存到到文件中。
3. 重新安装 Fedora，删除你当前的分区，并选择新的 Btrfs 默认分区方案。
4. 恢复主文件夹的内容，并使用软件包列表文件重装软件包。


对于详细的步骤和命令，请看一位社区用户在 [ask.fedoraproject.org](https://ask.fedoraproject.org/t/conversion-of-an-existing-ext4-fedora-32-system-completely-to-btrfs/9446/6?u=gombosghttps://ask.fedoraproject.org/t/conversion-of-an-existing-ext4-fedora-32-system-completely-to-btrfs/9446/6?u=gombosg) 站点的评论。如果正确完成，你将得到一个和之前一样的操作系统，使丢失数据的风险最小化。


### 转换的利弊


让我们快速澄清一下：这种文件系统转换有什么优势和劣势？


**优势：**


* 当然，不需要重新安装！你的系统里的所有文件和之前一模一样。
* 技术上来说，没有备份的情况下，就地进行是可能的。
* 你会学到许多关于 Btrfs 的知识！
* 如果所有都按计划进行，会是相当快的一个过程。


**劣势：**


* 你必须熟悉终端环境和 shell 命令。
* 你可能会丢失数据，参见上文。
* 如果出了什么问题，你得自己解决。


**特别之处：**


* 你需要大约 20% 的可用磁盘空间才能成功转换。但对于完整的备份和重装方式，你可能需要的空间更多。
* 你可以在转换过程中自定义你分区的所有参数，但如果选择重装，你也可以从 Anaconda 自定义。


### LVM 怎么办？


在近期几次 Fedora 安装中，LVM 布局一直是默认的。如果你有一个带有多个分区（例如 `/` 和 `/home`）的 LVM 分区布局，你得以某种方式合并它们，来获得 Btrfs 所有性能。


如果选择这样做，你可以单独转换分区到 Btrfs 文件系统，同时保留卷组。然而，迁移到 Btrfs 文件系统的优势之一是摆脱 LVM 分区布局强加的限制。你也可以利用 Btrfs 文件系统提供的收发功能在转换后来合并分区。



> 
> 另见 《Fedora 杂志》： [利用 LVM 回收硬盘空间](https://fedoramagazine.org/reclaim-hard-drive-space-with-lvm/)、[从 Btrfs 快照中恢复文件](https://fedoramagazine.org/recover-your-files-from-btrfs-snapshots/) 以及 [在 Btrfs 和 LVM-ext4 两者之间做选择](https://fedoramagazine.org/choose-between-btrfs-and-lvm-ext4/)。
> 
> 
> 


### 了解 Btrfs


建议阅读以下内容对 Btrfs 文件系统是什么有一个基础的了解。如果你没有把握，只有选择重装 Fedora 这种安全的方式。


必须了解的：


* [Fedora Magazine：Btrfs 来到 Fedora 33](https://fedoramagazine.org/btrfs-coming-to-fedora-33/)
* [Btrfs 系统管理指南](https://btrfs.wiki.kernel.org/index.php/SysadminGuide), *尤其是* 关于子卷和 flat 子卷布局。
* [btrfs-convert 指南](https://btrfs.wiki.kernel.org/index.php/Conversion_from_Ext3)


有用的资源：


* [man 8 btrfs](https://www.mankier.com/8/btrfs) – 命令行界面
* [man 5 btrfs](https://www.mankier.com/5/btrfs) – 挂载参数
* [man btrfs-convert](https://www.mankier.com/8/btrfs-convert) – 要用到的转换工具
* [man btrfs-subvolume](https://www.mankier.com/8/btrfs-subvolume) – 管理子卷


### 转换步骤


#### 创建一个实时镜像


由于不能转换已挂载的文件系统，我们将通过 Fedora <ruby> 实时镜像 <rt>  Live Image </rt></ruby>进行。安装 [Fedora 镜像写入工具](https://getfedora.org/en/workstation/download/)，然后 “烧录” Fedora 33 到你的 U 盘中来创建实时镜像。


#### 释放磁盘空间


`btrfs-convert` 会在分区的剩余空间重新创建文件系统的元数据，同时保持所有已有的 ext4 文件系统数据还在它当前的位置上。


不幸的是，所需的剩余空间的大小无法提前知道：如果没有足够的空间，转换将会失败（但不会破坏数据）。这里有一些释放空间有用的方法：


* 利用 `baobab` 来识别大容量的文件和文件夹，然后移除。如果可能的话，不要手动删除主文件夹以外的文件。
* 清理旧的系统日志：`journalctl –vacuum-size=100M`。
* 如果你正使用 Docker，请小心地使用类似 `docker volume prune`、`docker image prune -a` 这样的工具。
* 清理 GNOME Boxes 之类的虚拟机内不用的镜像。
* 清理不用的软件包和 Flatpak 包：`dnf autoremove`、`flatpak remove –unused`。
* 清理软件包缓存：`pkcon refresh force -c -1`、`dnf clean all`。
* 如果你有把握，你可以谨慎的清理 `~/.cache` 文件夹。


#### 转换到 Btrfs


备份你所有有价值的数据，确保你的系统已完全更新，然后重启到实时镜像。运行 `gnome-disks` 工具找到你所拥有的设备的路径，比如 `/dev/sda1`（如果你在使用 LVM，它可能看起来有所不同）。检查文件系统然后执行转换：（编者按：以下命令使用 root 用户运行，谨慎使用！）



```
$ sudo su -
# fsck.ext4 -fyv /dev/sdXX （请替换为你的具体的设备路径）
# man btrfs-convert （阅读它）
# btrfs-convert /dev/sdXX （请替换为你的具体的设备路径）

```

这将会花十几分钟甚至几个小时，依据分区的大小和是机械硬盘还是固态硬盘。如果你看到错误，你可能需要更多剩余空间。作为最后的手段，你可以尝试 `btrfs-convert -n`。


#### 怎样回滚？


如果因为某些原因转换失败，你的分区将保持在 ext4 文件系统或者它之前的状态。如果你想在成功转换之后回滚，简单如下：



```
# btrfs-convert -r /dev/sdXX

```


> 
> **警告！** 如果你做了以下这些事情之一，你将永久失去回滚的功能：碎片整理、均衡或者删除 `ext2_saved` 子卷。
> 
> 
> 


由于 Btrfs 文件系统的写时复制特性，你可以安全的复制/移动甚至删除文件、创建子卷，因为 `ext2_saved` 会保持引用旧数据。


#### 挂载和检查


现在这个分区应该已经有了 Btrfs 文件系统。挂载它然后查看你的文件……和子卷！



```
# mount /dev/sdXX /mnt （请替换为你的具体的设备路径）
# man btrfs-subvolume （阅读它）
# btrfs subvolume list / （使用 -t 以表格方式查看）

```

因为你已经阅读了 [相关的手册页](https://www.mankier.com/8/btrfs-subvolume#Subvolume_and_Snapshot)，你应该知道创建子卷快照是安全的，并且有 `ext2-saved` 子卷作为你之前数据的简易备份。



> 
> 是时候阅读 [Btrfs 系统管理指南](https://btrfs.wiki.kernel.org/index.php/SysadminGuide)了，这样你就不会把常规文件夹和子卷混淆了。
> 
> 
> 


#### 创建子卷


我们希望实现一个“扁平”子卷布局，这和 Anaconda 默认创建的布局相同：



```
toplevel （卷根目录，不能被默认挂载）
  +-- root （子卷根目录，被挂载到 /）
  +-- home （子卷根目录，被挂载到 /home）

```

你可以跳过这个步骤，或者使用一个不同的布局。这种特殊结构的优势是你可以轻松的创建 `/home` 的快照，并且对每个子卷使用不同的压缩和挂载参数。



```
# cd /mnt
# btrfs subvolume snapshot ./ ./root2
# btrfs subvolume create home2
# cp -a home/* home2/

```

这里我们已经创建了两个子卷。`root2` 是一个完整的分区快照，而 `home2` 开始是一个空子卷，然后我们往里复制内容。（这个 `cp` 命令不会重复数据，所以会很快。）


* 在 `/mnt` 目录（顶层子卷），删除除了 `root2`、`home2` 和 `ext2_saved` 之外的所有内容。
* 重命名 `root2` 和 `home2` 子卷为 `root` 和 `home`。
* 在 `root` 子卷里，清空 `home` 目录，以便之后我们能够挂载 `home` 子卷。


如果都做对了，那就很简单了！


#### 修改 fstab 分区表


为了重启之后挂载新卷，必须要修改 `fstab`，用新的行来代替旧的 ext4 文件系统挂载行。


你可以使用 `blkid` 命令来找到你的分区的 UUID。



```
UUID=xx / btrfs subvol=root 0 0 （请替换为你的具体 UUID）
UUID=xx /home btrfs subvol=home 0 0 （请替换为你的具体 UUID）

```

（注意如果指向的是同一个分区，那么这两个 UUID 是相同的。）


这些都是新安装的 Fedora 33 的默认值。在 `fstab` 中，你也可以选择自定义压缩和添加类似 `noatime` 这样的参数。



> 
> 可以查看 [关于压缩参数的维基页面](https://btrfs.wiki.kernel.org/index.php/Compression) 和 [man 5 btrfs](https://www.mankier.com/5/btrfs) 了解所有相关的参数。
> 
> 
> 


#### chroot 到系统


如果你曾经做过系统恢复，我想你肯定知道这些命令。这里，我们将得到一个 *基本上* 在你系统里的 shell 提示符，可以访问网络。


首先，我们必须重新挂载 `root` 子卷到 `/mnt` 目录，然后挂载 `/boot` 和 `/boot/efi` 分区（它们可能有所不同，这取决于你的文件系统布局）：



```
# umount /mnt
# mount -o subvol=root /dev/sdXX /mnt （请替换为你的具体的设备路径）
# mount /dev/sdXX /mnt/boot （请替换为你的具体的设备路径）
# mount /dev/sdXX /mnt/boot/efi （请替换为你的具体的设备路径）

```

然后我们继续挂载系统设备：



```
# mount -t proc /proc /mnt/proc
# mount --rbind /dev /mnt/dev
# mount --make-rslave /mnt/dev
# mount --rbind /sys /mnt/sys
# mount --make-rslave /mnt/sys
# cp /mnt/etc/resolv.conf /mnt/etc/resolv.conf.chroot
# cp -L /etc/resolv.conf /mnt/etc
# chroot /mnt /bin/bash
$ ping www.fedoraproject.org

```

#### 重装 GRUB 及内核


最容易的方法就是重装 GRUB 和 内核，因为它完成了所有必要的配置 —— 现在我们可以访问网络了。所以，在 chroot 环境内部：



```
# mount /boot/efi
# dnf reinstall grub2-efi shim
# grub2-mkconfig -o /boot/efi/EFI/fedora/grub.cfg
# dnf reinstall kernel-core
...或者干脆重新生成 initramfs：
# dracut --kver $(uname -r) --force

```

如果你是支持 UEFI 的系统，这里是适用的。如果你是 BIOS 的系统，请查看下面的文档。重启之前，让我们查看是否一切正常：



```
# cat /boot/grub2/grubenv
# cat /boot/efi/EFI/fedora/grub.cfg
# lsinitrd /boot/initramfs-$(uname -r).img | grep btrfs

```

你应该在 `grubenv` 和 `grub.cfg` 有正确的分区 UUID 或指向（`grubenv` 可能没有更新，如有必要可以编辑它），并在 `grub.cfg` 中看到 `insmod btrfs` 配置和在 initramfs 镜像中有 btrfs 模块。



> 
> 参见: Fedora 系统管理指南中的 [重装 GRUB 2](https://docs.fedoraproject.org/en-US/fedora/f33/system-administrators-guide/kernel-module-driver-configuration/Working_with_the_GRUB_2_Boot_Loader/#sec-Reinstalling_GRUB_2) 和 [验证初始 RAM 磁盘镜像](https://docs.fedoraproject.org/en-US/fedora/f33/system-administrators-guide/kernel-module-driver-configuration/Manually_Upgrading_the_Kernel/#sec-Verifying_the_Initial_RAM_Disk_Image) 。
> 
> 
> 


#### 重启


现在系统能够正常启动。如果不能，别慌，回到实时镜像修复这个问题。最坏的情况下，你可以从那里重装 Fedora 。


#### 首次启动之后


检查你的新 Btrfs 文件系统一切都正常。如果你觉得没问题，你需要回收旧的 ext4 快照使用的空间，进行碎片整理和平衡子卷。后两者可能要花一些时间，并且相当耗费资源。


对此你必须这样挂载顶级子卷：



```
# mount /dev/sdXX -o subvol=/ /mnt/someFolder
# btrfs subvolume delete /mnt/someFolder/ext2_saved

```

然后，当机器有空闲时间时，运行这些命令：



```
# btrfs filesystem defrag -v -r -f /
# btrfs filesystem defrag -v -r -f /home
# btrfs balance start -m /

```

最后，有一个 “非写时复制” [属性](https://www.mankier.com/1/chattr#Attributes-C)，对于新系统，这个属性是为虚拟机镜像文件夹自动设置的。如果你使用虚拟机的话，可以设置它：



```
# chattr +C /var/lib/libvirt/images

```


```
$ chattr +C ~/.local/share/gnome-boxes/images

```

这个属性只会对在这些文件夹里的新文件生效。复制镜像并删除原镜像，你可以通过 `lsattr` 确认结果。


### 总结


我真心希望你发现这个教程是有用的，并且能够对是否在你的系统上转换为 Btrfs 做出谨慎而明智的决定。祝你成功转换！


欢迎在评论中分享你的经验，或者遇到更深层次的问题，请在 [ask.fedoraproject.org](https://ask.fedoraproject.org/) 提问。




---


via: <https://fedoramagazine.org/convert-your-filesystem-to-btrfs/>


作者：[Gergely Gombos](https://fedoramagazine.org/author/gombosg/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[hwlife](https://github.com/hwllife) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
## Introduction

The purpose of this article is to give you an overview about why, and how to migrate your current partitions to a Btrfs filesystem. To read a step-by-step walk through of how this is accomplished – follow along, if you’re curious about doing this yourself.

Starting with Fedora 33, the default filesystem is now Btrfs for new installations. I’m pretty sure that most users have heard about its advantages by now: copy-on-write, built-in checksums, flexible compression options, easy snapshotting and rollback methods. It’s really a modern filesystem that brings new features to desktop storage.

Updating to Fedora 33, I wanted to take advantage of Btrfs, but personally didn’t want to reinstall the whole system for ‘just a filesystem change’. I found [there was] little guidance on how exactly to do it, so decided to share my detailed experience here.

## Watch out!

Doing this, you are playing with fire. Hopefully you are not surprised to read the following:

During editing partitions and converting file systems, you can have your data corrupted and/or lost. You can end up with an unbootable system and might be facing data recovery. You can inadvertently delete your partitions or otherwise harm your system.


These conversion procedures are meant to be safe even for production systems – but only if you plan ahead, have backups for critical data and rollback plans. As a *sudoer*, you can do anything without limits, without any of the usual safety guards protecting you.

## The safe way: reinstalling Fedora

Reinstalling your operating system is the ‘official’ way of converting to Btrfs, recommended for most users. Therefore, choose this option if you are unsure about anything in this guide. The steps are roughly the following:

- Backup your home folder and any data that might be used in your system like
*/etc*. [Editors note: VM’s too] - Save your list of installed packages to a file.
- Reinstall Fedora by removing your current partitions and choosing the new default partitioning scheme with Btrfs.
- Restore the contents of your home folder and reinstall the packages using the package list.

For detailed steps and commands, see this comment by a community user at [ask.fedoraproject.org](https://ask.fedoraproject.org/t/conversion-of-an-existing-ext4-fedora-32-system-completely-to-btrfs/9446/6?u=gombosghttps://ask.fedoraproject.org/t/conversion-of-an-existing-ext4-fedora-32-system-completely-to-btrfs/9446/6?u=gombosg). If you do this properly, you’ll end up with a system that is functioning in the same way as before, with minimal risk of losing any data.

## Pros and cons of conversion

Let’s clarify this real quick: what kind of advantages and disadvantages does this kind of filesystem conversion have?

**The good**

- Of course, no reinstallation is needed! Every file on your system will remain the exact same as before.
- It’s technically possible to do it in-place i.e. without a backup.
- You’ll surely learn a lot about btrfs!
- It’s a rather quick procedure if everything goes according to plan.

#### The bad

- You have to know your way around the terminal and shell commands.
- You can lose data, see above.
- If anything goes wrong, you are on your own to fix it.

#### The ugly

- You’ll need about 20% of free disk space for a successful conversion. But for the complete backup & reinstall scenario, you might need even more.
- You can customize everything about your partitions during the process, but you can also do that from Anaconda if you choose to reinstall.

**What about LVM?**

LVM layouts have been the default during the last few Fedora installations. If you have an LVM partition layout with multiple partitions e.g. */* and */home*, you would somehow have to merge them in order to enjoy all the benefits of Btrfs.

If you choose so, you can individually convert partitions to Btrfs while keeping the volume group. Nevertheless, one of the advantages of migrating to Btrfs is to get rid of the limits imposed by the LVM partition layout. You can also use the send-receive functionality offered by *btrfs* to merge the partitions after the conversion.

See also on Fedora Magazine: [Reclaim hard-drive space with LVM](https://fedoramagazine.org/reclaim-hard-drive-space-with-lvm/), [Recover your files from Btrfs snapshots](https://fedoramagazine.org/recover-your-files-from-btrfs-snapshots/) and [Choose between Btrfs and LVM-ext4](https://fedoramagazine.org/choose-between-btrfs-and-lvm-ext4/).

## Getting acquainted with Btrfs

It’s advisable to read at least the following to have a basic understanding about what Btrfs is about. If you are unsure, just choose the safe way of reinstalling Fedora.

#### Must reads

[Fedora Magazine: Btrfs Coming to Fedora 33](https://fedoramagazine.org/btrfs-coming-to-fedora-33/)[Btrfs sysadmin guide](https://btrfs.wiki.kernel.org/index.php/SysadminGuide),*especially*about subvolumes & flat subvolume layout.[Btrfs-convert guide](https://btrfs.wiki.kernel.org/index.php/Conversion_from_Ext3)

#### Useful resources

– command-line interface*man 8 btrfs*– mount options[man 5 btrfs](https://www.mankier.com/5/btrfs)– the conversion tool we are going to use[man btrfs-convert](https://www.mankier.com/8/btrfs-convert)– managing subvolumes[man btrfs-subvolume](https://www.mankier.com/8/btrfs-subvolume)

## Conversion steps

#### Create a live image

Since you can’t convert mounted filesystems, we’ll be working from a Fedora live image. Install [Fedora Media Writer](https://getfedora.org/en/workstation/download/) and ‘burn’ Fedora 33 to your favorite USB stick.

#### Free up disk space

*btrfs-convert* will recreate filesystem metadata in your partition’s free disk space, while keeping all existing *ext4 *data at its current location.

Unfortunately, the amount of free space required cannot be known ahead – the conversion will just fail (and do no harm) if you don’t have enough. Here are some useful ideas for freeing up space:

- Use
*baobab*to identify large files & folders to remove. Don’t manually delete files outside of your home folder if possible. - Clean up old system journals:
*journalctl –vacuum-size=100M* - If you are using Docker, carefully use tools like
*docker volume prune, docker image prune -a* - Clean up unused virtual machine images inside e.g. GNOME Boxes
- Clean up unused packages and flatpaks:
*dnf autoremove*,*flatpak remove –unused*, - Clean up package caches:
*pkcon refresh force -c -1*,*dnf clean all* - If you’re confident enough to, you can cautiously clean up the
*~/.cache*folder.

#### Convert to Btrfs

Save all your valuable data to a backup, make sure your system is fully updated, then reboot into the live image. Run *gnome-disks* to find out your device handle e.g. */dev/sda1* (it can look different if you are using LVM). Check the filesystem and do the conversion: [Editors note: The following commands are run as root, use caution!]

$ sudo su - # fsck.ext4 -fyv /dev/sdXX # man btrfs-convert (read it!) # btrfs-convert /dev/sdXX

This can take anywhere from 10 minutes to even hours, depending on the partition size and whether you have a rotational or solid-state hard drive. If you see errors, you’ll likely need more free space. As a last resort, you could try *btrfs-convert* *-n*.

#### How to roll back?

If the conversion fails for some reason, your partition will remain *ext4* or whatever it was before. If you wish to roll back after a successful conversion, it’s as simple as

# btrfs-convert -r /dev/sdXX

**Warning!** You will permanently lose your ability to roll back if you do any of these: defragmentation, balancing or deleting the *ext2_saved* subvolume.

Due to the copy-on-write nature of Btrfs, you can otherwise safely copy, move and even delete files, create subvolumes, because *ext2_saved *keeps referencing to the old data.

#### Mount & check

Now the partition is supposed to have *btrfs* file system. Mount it and look around your files… and subvolumes!

# mount /dev/sdXX /mnt # man btrfs-subvolume (read it!) # btrfs subvolume list / (-t for a table view)

Because you have already read the [relevant manual page](https://www.mankier.com/8/btrfs-subvolume#Subvolume_and_Snapshot), you should now know that it’s safe to create subvolume snapshots, and that you have an *ext2-saved* subvolume as a handy backup of your previous data.

It’s time to read the [Btrfs sysadmin guide](https://btrfs.wiki.kernel.org/index.php/SysadminGuide), so that you won’t confuse subvolumes with regular folders.

#### Create subvolumes

We would like to achieve a ‘flat’ subvolume layout, which is the same as what Anaconda creates by default:

toplevel (volume root directory, not to be mounted by default) +-- root (subvolume root directory, to be mounted at /) +-- home (subvolume root directory, to be mounted at /home)

You can skip this step, or decide to aim for a different layout. The advantage of this particular structure is that you can easily create snapshots of */home*, and have different compression or mount options for each subvolume.

# cd /mnt # btrfs subvolume snapshot ./ ./root2 # btrfs subvolume create home2 # cp -a home/* home2/

Here, we have created two subvolumes. *root2 *is a full snapshot of the partition, while *home2* starts as an empty subvolume and we copy the contents inside. (This *cp* command doesn’t duplicate data so it is going to be fast.)

- In
*/mnt*(the top-level subvolume) delete everything except*root2*,*home2*, and*ext2_saved*. - Rename
*root2*and*home2*subvolumes to*root*and*home*. - Inside
*root*subvolume, empty out the*home*folder, so that we can mount the*home*subvolume there later.

It’s simple if you get everything right!

#### Modify fstab

In order to mount the new volume after a reboot, *fstab* has to be modified, by replacing the old *ext4* mount lines with new ones.

You can use the command *blkid * to learn your partition’s UUID.

UUID=xx / btrfs subvol=root 0 0 UUID=xx /home btrfs subvol=home 0 0

(Note that the two UUIDs are the same if they are referring to the same partition.)

These are the defaults for new Fedora 33 installations. In *fstab* you can also choose to customize compression and add options like *noatime.*

See the relevant [wiki page about compression](https://btrfs.wiki.kernel.org/index.php/Compression) and * man 5 btrfs* for all relevant options.

#### Chroot into your system

If you’ve ever done system recovery, I’m pretty sure you know these commands. Here, we get a shell prompt that is essentially *inside* your system, with network access.

First, we have to remount the *root* subvolume to */mnt*, then mount the */boot* and */boot/efi* partitions (these can be different depending on your filesystem layout):

# umount /mnt # mount -o subvol=root /dev/sdXX /mnt # mount /dev/sdXX /mnt/boot # mount /dev/sdXX /mnt/boot/efi

Then we can move on to mounting system devices:

# mount -t proc /proc /mnt/proc # mount --rbind /dev /mnt/dev # mount --make-rslave /mnt/dev # mount --rbind /sys /mnt/sys # mount --make-rslave /mnt/sys # cp /mnt/etc/resolv.conf /mnt/etc/resolv.conf.chroot # cp -L /etc/resolv.conf /mnt/etc # chroot /mnt /bin/bash $ ping www.fedoraproject.org

#### Reinstall GRUB & kernel

The easiest way – now that we have network access – is to reinstall GRUB and the kernel because it does all configuration necessary. So, inside the chroot:

# mount /boot/efi # dnf reinstall grub2-efi shim # grub2-mkconfig -o /boot/efi/EFI/fedora/grub.cfg # dnf reinstall kernel-core ...or just renegenerating initramfs: # dracut --kver $(uname -r) --force

This applies if you have an UEFI system. Check the docs below if you have a BIOS system. Let’s check if everything went well, before rebooting:

# cat /boot/grub2/grubenv # cat /boot/efi/EFI/fedora/grub.cfg # lsinitrd /boot/initramfs-$(uname -r).img | grep btrfs

You should have proper partition UUIDs or references in *grubenv* and *grub.cfg* (grubenv may not have been updated, edit it if needed) and see *insmod btrfs* in *grub.cfg* and *btrfs* module in your initramfs image.

See also: [Reinstalling GRUB 2](https://docs.fedoraproject.org/en-US/fedora/f33/system-administrators-guide/kernel-module-driver-configuration/Working_with_the_GRUB_2_Boot_Loader/#sec-Reinstalling_GRUB_2) and [Verifying the Initial RAM Disk Image](https://docs.fedoraproject.org/en-US/fedora/f33/system-administrators-guide/kernel-module-driver-configuration/Manually_Upgrading_the_Kernel/#sec-Verifying_the_Initial_RAM_Disk_Image) in the Fedora System Administration Guide.

#### Reboot

Now your system should boot properly. If not, don’t panic, go back to the live image and fix the issue. In the worst case, you can just reinstall Fedora from right there.

#### After first boot

Check that everything is fine with your new Btrfs system. If you are happy, you’ll need to reclaim the space used by the old *ext4* snapshot, defragment and balance the subvolumes. The latter two might take some time and is quite resource intensive.

You have to mount the top level subvolume for this:

# mount /dev/sdXX -o subvol=/ /mnt/someFolder # btrfs subvolume delete /mnt/someFolder/ext2_saved

Then, run these commands when the machine has some idle time:

# btrfs filesystem defrag -v -r -f / # btrfs filesystem defrag -v -r -f /home # btrfs balance start -m /

Finally, there’s a “no copy-on-write” [attribute](https://www.mankier.com/1/chattr#Attributes-C) that is automatically set for virtual machine image folders for new installations. Set it if you are using VMs:

#$ chattr +Cchattr +C /var/lib/libvirt/images~/.local/share/gnome-boxes/images

This attribute only takes effect for new files in these folders. Duplicate the images and delete the originals. You can confirm the result with *lsattr*.

## Wrapping up

I really hope that you have found this guide to be useful, and was able to make a careful and educated decision about whether or not to convert to Btrfs on your system. I wish you a successful conversion process!

Feel free to share your experience here in the comments, or if you run into deeper issues, on [ask.fedoraproject.org](https://ask.fedoraproject.org/).

## Hugo Lopes

Portuguese –>> Existe algum script ou programa que já faça isso tudo de forma automática, iguais as facilidades do Windows (por isso eles chegaram onde chegaram), ou se tem que fazer tudo na mão (sem formatar, obvio) comando por comando (o que é chato). Caso não se tenha um script ou programa assim, fica a dica, inclusive para todos os formatos (ext2, ext4, etc).

## Taniguchi

Seguinte… não existe script.. e tbm não recomendo esse tipo de procedimento. Pois há muitas chances de não dar certo! É mais seguro vc fazer backup de tudo, e partir para uma nova instalação do SO. Eu sempre usei EXT4, mas agora estou com o Btrfs. Fiz a conversão dele através de uma instalação limpa, do zero. Não tive problemas até agora!

## AndreaS

Nice guide, I think I will try it. One question. I am currently running Fedora 33 on an external disk on my laptop.

Any chance that after conversion I will still be able to boot Fedora from the external Disk?

## Gergely Gombos

Hi, you will be able to boot the same, because likely there is no difference between an internal and an external drive from the computer’s perspective.

In this guide, we don’t touch /boot, only reinstall GRUB to accommodate the filesystem changes.

## Novid Emami

Thanks Gergely for this introduction to Btrfs convertion.

I’m new to Fedora and partitioned my system like the old days on Debian . It’s working fine for me to have /, /boot and /home separated but on the same ext4 partition scheme. I don’t know if its a good idea to convert into Btrfs for everyday desktop usage but it may have some advantages over the sever or cloud platforms. Let’s not rush through this and see what happens during next few month or even years!

P.S: I now understand why Fedora is such a great community for new technologies 😉

## Gergely Gombos

Hi! Btrfs is mature and totally safe for desktop usage. It’s way beyond early testing phases. That’s why it has been selected as the default file system for Fedora Workstation.

Of course, deciding whether to convert your FS is up to you, I hope this article gave some useful pointers on why it might be worth it.

## Karol

Well.. Good luck. Two months ago my OpenSuse TW had a total FS disaster (/home unfortunately) after just maybe 1 year after installation. Guess what was the filesystem? Yes, it was btrfs. This is the only total FS crash I can remember, and I have been using Linux since 1998.

## svsv sarma

This reminds me of the ‘Fat -NTFS’ conversion. Change always invites alertness, caution and guard and takes its own time to sink in. I decided to install Fedora 34 only, whether it retains ButterFS or not.

## Tomasz

Eh..

Convert to a self healing system that runs on top of raid 6 to assist with drive failure and then see your data go after a power loss when one system tries to correct the other and kernel panicking every 5 or so minutes when btrfs says the error is unrecoverable.

After desperately trying to recover 4tb of memories (photos and videos) and important archives and recognizing there are no tools to help me out during the 5 minute session between reboots I will never go back to btrfs.

YMMV.

## Amir

Can I do the filesystem change while on dual boot with Windows 10?

## Gergely Gombos

Absolutely, I did the same. This process doesn’t touch the Windows partition. You can also install WinBtrfs (https://github.com/maharmstone/btrfs) to be able to access btrfs partitions from Windows. For example, you could create a common data partition or a subvolume that you can share between Windows and Linux.

## Amir

Thanks Gergely..

## Taras

Hi! Thanks for the great article. Personally, I’ve used F33 on my laptop with btrfs about a month and I would say it pretty stable and reliable. But for the moment I switched back to the XFS, because it works much faster for me.

## ernesto

On one of these articles I saw a discussion on some old school linux commands not working properly with btrfs (it could have been ‘df’ or ‘du’).

Is this still the case?

## Matthew Miller

It’s not that they don’t work, it’s that the data they give back might be surprising. These commands do not know about reflinks, snapshots, compression, etc. So, it is better to use the btrfs-aware equivalents. See https://unix.stackexchange.com/a/436598/2511 for details.

## Gregory Bartholomew

I think you are referring to this comment. But I don’t know if anything has changed. EDIT: It looks like Matt found the answer while I was hunting down the original comment. 🙂

## Sally

Because I can’t take a risk with my current system, I am trying it as VM, but I have noticed that, when I divide partitions like ‘/’, ‘/home’ and give each one specific size, I see the size like to merge and they share the same size, is that normal, and if so, why is that? can’t I keep fixed size for each partition in Btrfs?

## Stephen Snow

The way Btrfs allocates space is as it needs it, so free space for one btrfs volume (disk partition) with more than one subvolume (like / and /home for example) will show identical for all subvolumes since it is currently available for all subvolumes to use.

## Sally

In this case I can’t encrypt just one partition e.g. ‘/home’ which I think it’s not a good idea.

## Jared Gray

Thanks for your excellent guide, Gergely (and of course the editors)! Because I had a lot of storage options, I decided to migrate my LVM/ext4 Fedora installation to an external mount point and then copy the data back to a new Btrfs filesystem. This approach considerably simplified moving off of LVM in particular. Even though my migration path was different than that described by this in-place tutorial, your guide was still instrumental in my own process.

Just in case others decide to follow a similar approach to what I did, there is one caveat I wanted to mention expressly. If you have SELinux enabled on your Fedora system, which is currently the default, you will need to relabel the new filesystem to get your system booting again. You can do this simply by placing a file called ‘autorelabel’ on the Btrfs subvolume corresponding to your ‘/’ mount point. I can’t speak to whether this step is required when using the in-place migration tools discussed in the article, however.

## Jared Gray

Correction: the file name is ‘.autorelabel’ not ‘autorelabel’. And warning: relabeling your entire file system is slow. With an NVME SSD and a two year-old installation of Fedora, I had to wait about five minutes for the process to complete. During this time, I was treated to a completely black screen. This is problematic because users may conclude that boot process has failed when in fact it is progressing.

To be clear, the fix I suggested does indeed work (eventually), but it is a hammer- rather than a scalpel-type solution. If your file system contains a lot of files (more than one million) or you are using a conventional spinning hard drive, I advise against relabeling everything as a first line measure. Since I’m not an SELinux nerd myself, I will put a call out there to those who know of a more fine-grained solution than I do.

In the meantime, my refined guidance is: before relabeling your filesystem, first verify that SELinux is the reason why your system will not boot. One way to do this is to disable SELinux policy enforcement temporarily and see if the system comes up afterwards.

To disable SELinux policy enforcement for the next boot only, ensure your kernel command line contains ‘selinux=1’ and ‘enforcing=0’. You can do this in GRUB by hitting the ‘e’ key during boot and appending the above parameters to the line containing ‘vm-linuz’. If the system now boots, you can reasonably infer that SELinux file attributes were likely causing the problem.

## Gregory Bartholomew

I was never a fan of disabling the post screen that shows what is happening (and if anything is failing) during boot. You should be able to hit the

Esckey to see the status messages.## Tony Nalagan

Wish I saw this article last November. My solution was less elegant and required considerable time to complete. I converted root, created an new home subvolume, and used gparted to shrink the original home partition while increasing the size of the new btrfs filesystem. Then migrating the data about 20 GB at a time, and repeating until all the data was transferred to the new home subvolume. Admittedly a brute force method.

## Mathieu Tanguay

“The purpose of this article is to give you an overview about why, and how to migrate your current partitions to a Btrfs filesystem”

Can’t find the why, only the how…

## Gergely Gombos

Hi, please see the “Pros and cons of conversion” and “What about LVM? ” sections in the article about the “Why”. I have pointed to several previous articles here on Fedora Magazine which discuss this topic in depth.

One example is: https://fedoramagazine.org/choose-between-btrfs-and-lvm-ext4/

## b1tninja

Further caution, you cannot rely on the snapshot as a backup