Btrfs

From Gentoo Wiki
Jump to: navigation, search
This page is a translated version of the page Btrfs and the translation is 50% complete.

Other languages:
English • ‎italiano • ‎日本語 • ‎한국어 • ‎polski • ‎русский • ‎中文(中国大陆)‎

Btrfs is a copy-on-write (CoW) filesystem for Linux aimed at implementing advanced features while focusing on fault tolerance, repair, and easy administration. Jointly developed at Oracle, Red Hat, Fujitsu, Intel, SUSE, STRATO, and many others, Btrfs is licensed under the GPL and open for contribution from anyone.

기능

Ext4 is safe and stable and can handle large filesystems with extents, but why switch? While it is true that Btrfs is still considered experimental and is growing in stability, the time when Btrfs will become the default filesystem for Linux systems is getting closer. Some Linux distributions have already begun to switch to it with their current releases. Btrfs has a number of advanced features in common with ZFS, which is what made the ZFS filesystem popular with BSD distributions and NAS devices.

  • Copy on Write (CoW) and snapshotting - Make incremental backups painless even from a "hot" filesystem or virtual machine (VM).
  • File level checksums - Metadata for each file includes a checksum that is used to detect and repair errors.
  • Compression - Files may be compressed and decompressed on the fly, which speeds up read performance.
  • Auto defragmentation - The filesystems are tuned by a background thread while they are in use.
  • Subvolumes - Filesystems can share a single pool of space instead of being put into their own partitions.
  • RAID - Btrfs does its own RAID implementations so LVM or mdadm are not required in to have RAID. Currently RAID 0 and 1 are supported; RAID 5 and 6 are upcoming.
  • Partitions are optional - While Btrfs can work with partitions, it has the potential to use raw devices (/dev/<device>) directly.
  • Data deduplication - There is limited data deduplication support; however, deduplication will eventually become a standard feature in Btrfs. This enables Btrfs to save space by comparing files via binary diffs.
요령
For an up-to-date and somewhat exhaustive listing of features see the [https://btrfs.wiki.kernel.org/index.php/Status upstream wiki's status page. Not all features are sufficiently mature for wide use though.

Down the road, new clustered filesystems will readily take advantage of Btrfs with its copy on write and other advanced features for their object stores. Ceph is one example of a clustered filesystem that looks very promising, and can take advantage of Btrfs.

설치

커널

btrfs 기능을 활용하려면 다음 커널 옵션을 활성화하십시오:

커널 커널의 btrfs 활성화
File systems  --->
    <*> Btrfs filesystem

Emerge

The sys-fs/btrfs-progs package contains the utilities necessary to work with the Btrfs filesystem.

root #emerge --ask sys-fs/btrfs-progs

사용법

Typing long Btrfs commands can quickly become a hassle. Each command (besides the initial btrfs command) can be reduced to a very short set of instructions. This method is helpful when working from the command line to reduce the amount of characters typed.

For example, to defragment a filesystem located at /, the following shows the long command:

root #btrfs filesystem defragment -v /

Shorten each of the longer commands after the btrfs command by reducing them to their unique, shortest prefix. In this context, unique means that no other btrfs commands will match the command at the command's shortest length. The shortened version of the above command is:

root #btrfs fi de -v /

No other btrfs commands start with fi; filesystem is the only one. The same goes for the de sub-command under the filesystem command.

만들기

경고
mkfs.btrfs 명령은 분할 영역을 초기화한 이후로 해당 영역의 모든 내용을 복구할 수 없게끔 파괴합니다. mkfs 명령을 실행하기 올바른 분할 영역을 선택했는지 확인하십시오!

/dev/sdXN 분할 영역에 btrfs 파일 시스템을 만들려면:

root #mkfs.btrfs /dev/sdXN

위 예제에서 N 대신 분할 영역 번호를, X 대신 포맷한 디스크의 문자를 넣으십시오. 예를 들어 시스템의 첫번째 드라이브의 세번째 분할 영역을 포맷한다면 다음 명령을 실행합니다:

root #mkfs.btrfs /dev/sda3
중요
The last number column in /etc/fstab should be 0 for all Btrfs partitions. fsck.btrfs and btrfsck should not be run during each system boot.

마운트

파일 시스템을 만들고 나면 다양한 방법으로 마운트할 수 있습니다:

  • mount - Manual mount.
  • fstab - Defining mount points in /etc/fstab enables automatic mounts on system boot.
  • Removable media - Automatic mounts on demand (useful for USB drives).
  • AutoFS - Automatic mount on filesystem access.

ext* 기반 파일 시스템 변환

It is possible to convert ext2, ext3, and ext4 filesystems to Btrfs using the btrfs-convert utility.

The following instructions only supports the conversion of filesystems that are unmounted. To convert the root partition, boot to a system rescue disk (SystemRescueCD works nicely) and run on the conversion commands on the root partition.

First be sure the the mount point is unmounted:

root #umount <mounted_device>

Check the integrity of the filesystem using the appropriate fsck tool. In the next example, the filesystem is ext4:

root #fsck.ext4 -f <unmounted_device>

Use btrfs-convert to convert the ext* formatted device into a Btrfs-formatted device:

root #btrfs-convert <unmounted_device>

Be sure to edit /etc/fstab after the device has been formatted to change the filesystem column from ext4 to Btrfs:

파일 /etc/fstabext4에서 btrfs로 변환
<device>   <mountpoint>  btrfs  defaults  0 0

단편화 제거

btrfs의 다른 기능으로 가동중 단편화 제거 기능이 있습니다. btrfs 루트 파일 시스템의 단편화를 제거하려면 다음 명령을 실행하십시오:

root #btrfs filesystem defragment -r -v /
경고
Defragmenting with kernel versions < 3.9 or ≥ 3.14-rc2 as well as with Linux stable kernel versions ≥ 3.10.31, ≥ 3.12.12 or ≥ 3.13.4 breaks up ref-links between files and their COW copies[1] and thus may increase space usage considerably. Make sure to have enough free space available and not too many snapshots on the drive as full btrfs partitions can get really slow.

압축

btrfs에서는 zlib와 lzo 알고리즘으로 전송 단계 압축을 지원합니다.

파일 속성을 활용하여 특정 파일을 압축할 수 있습니다:

user $chattr +c
compress 마운트 옵션은 새로 만든 모든 파일에 대해 기본적으로 압축동작이 동작하도록 설정합니다. 파일 시스템 전체를 다시 압축하려면 다음 명령을 실행하십시오:
root #btrfs filesystem defragment -r -v -clzo /

Depending on the CPU and disk performance, using lzo compression could improve the overall throughput.

It is possible to use the zlib compression algorithm instead of lzo. Zlib is slower but has a higher compression ratio:

root #btrfs filesystem defragment -r -v -czlib /

RAID

btrfs에서 RAID를 구성하는 방법은 mdadm으로 RAID를 구성하는 방법 만큼이나 쉽습니다.

RAID를 만들 때 전체 장치를 활용할 간단한 방법은:

root #mkfs.btrfs -m raid1 <device1> <device2> -d raid1 <device1> <device2>
경고
It is currently not safe to use the RAID 5 or 6 modes[2]. RAID 5 and 6 modes have seen some fixes[3] in Linux 4.12, but overall status is still marked as unstable.[4][5]. Users who want to use RAID5 or RAID6 functionality of btrfs are encouraged to check the btrfs status page for stability status of said modes before utilizing the modes.

하위 볼륨

As mentioned above in the features list, Btrfs can create subvolumes. Subvolumes can be used to better organize and manage data. They become especially powerful when combined with snapshots. Important distinctions must be made between Btrfs subvolumes and subvolumes created by Logical Volume Management (LVM). Btrfs subvolumes are not block level devices, they are POSIX file namespaces.[6] They can be created at any location in the filesystem and will act like any other directory on the system with one caveat: subvolumes can be mounted and unmounted. Subvolumes are nestable (subvolumes can be created inside other subvolumes), and easily created or removed.

참고
A subvolume cannot be created across different Btrfs filesystems. If /dev/sda and /dev/sdb both contain separate (non-RAID) Btrfs filesystems, there is no way a subvolume can expand across the two filesystems. The snapshot can be moved from one filesystem to another, but it cannot span across the two. It must be on /dev/sda or /dev/sdb.

만들기

To create a subvolume, issue the following command inside a Btrfs filesystem's name space:

root #btrfs subvolume create <dest-name>

Replace <dest-name> with the desired destination and subvolume name. For example, if a Btrfs filesystem exists at /mnt/btrfs, a subvolume could be created inside it using the following command:

root #btrfs subvolume create /mnt/btrfs/subvolume1

목록

To see the subvolume(s) that have been created, use the subvolume list command followed by a Btrfs filesystem location. If the current directory is somewhere inside a Btrfs filesystem, the following command will display the subvolume(s) that exist on the filesystem:

root #btrfs subvolume list .

If a Btrfs filesystem with subvolumes exists at the mount point created in the example command above, the output from the list command will look similar to the following:

root #btrfs subvolume list /mnt/btrfs
ID 309 gen 102913 top level 5 path mnt/btrfs/subvolume1

제거

Subvolumes can be properly removed by using the subvolume delete command followed by the path to the subvolume. All available subvolume paths in a Btrfs filesystem can be seen using the list command above.

root #btrfs subvolume delete <subvolume-path>

As above, replace <subvolume-path> with the actual path to the subvolume to be removed. To delete the subvolume used in the examples above, the following command would be issued:

root #btrfs subvolume delete /mnt/btrfs/subvolume1
Delete subvolume (no-commit): '/mnt/btrfs/subvolume1'

스냅샷

Snapshots are subvolumes that share data and metadata with other subvolumes. This is made possible by Btrfs' Copy on Write (CoW) ability.[6] Snapshots can be used for several purposes, one of which is to create backups of file system structures at specific points in time.

If the root filesystem is Btrfs, it is possible to create a snapshot using the subvolume snapshot commands:

root #mkdir -p /mnt/backup/rootfs
root #btrfs subvolume snapshot / /mnt/backup/rootfs/

The following small shell script can be added to a timed cron job to create a timestamped snapshot backup of a Btrfs formatted root filesystem. The timestamps can be adjusted to whatever is preferred by the user.

파일 btrfs_snapshot.shBtrfs rootfs snapshot cron job example
#!/bin/bash
NOW=$(date +"%Y-%m-%d_%H:%M:%S")
 
if [ ! -e /mnt/backup ]; then
mkdir -p /mnt/backup
fi
 
cd /
/sbin/btrfs subvolume snapshot / "/mnt/backup/backup_${NOW}"

Mounting

A subvolume can be mounted in a location different from where it was created, or users can choose to not mount them at all. For example, a user could create a Btrfs filesystem in /mnt/btrfs and create /mnt/btrfs/home and /mnt/btrfs/portage subvolumes. The subvolumes could then be mounted at /home and /usr/portage, with the original top level subvolume left unmounted. This results in a configuration where the subvolumes' relative path from the top level subvolume is different from their actual path.

To mount a subvolume, perform the following command, where <rel-path> is the relative path of the subvolume from the top level subvolume, obtainable through the subvolume list command:

root #mount -o subvol=<rel-path> <device> <mountpoint>

Similarly, one can update the filesystem tab to mount their Btrfs subvolumes like so:

파일 /etc/fstabMounting Subvolumes
<device>  <mountpoint>  btrfs  subvol=<rel-path>  0 2

문제 해결

여분 공간 캐시 삭제

btrfs의 여분 공간 캐시는 파일 시스템을 마운트할 때 clear_cache 마운트 옵션을 주어 비울 수 있습니다. 예를 들면:

root #mount -o clear_cache /path/to/device /path/to/mountpoint

btrfs의 메모리 점유(디스크 캐시)

btrfs 의 특별한 기능을 활용할 때(많은 양의 --reflink 사본을 만들거나 상당한 양의 스냅샷을 만들 때), 상당한 양의 메모리를 차지할 수 있으며 커널의 아이노드 캐시로 바로 점유 영역을 해제할 수 없습니다. 이 문제는 기존 시스템 감시 유틸리티에서 디스크 캐싱에 관여하는 메모리 영역을 분명하게 볼 수 없어 확인할 수 없게 되는 경우가 있습니다. 커널 객체에서 메모리를 얼마나 차지하는지 확인하려고 (sys-process/procps 꾸러미에 있는) slabtop 유틸리티를 따로 만들었습니다:

root #slabtop

If the inode cache is consuming too much memory, the kernel can be manually instructed to drop the cache by echoing an integer value to the /proc/sys/vm/drop_caches file[7].

To be safe, and to help the kernel determine the maximum amount of freeable memory, be sure to run a sync before running the echo commands below:

user $sync

Most of the time Btrfs users will probably want to echo 2 to reclaim just the slab objects (dentries and btrfs_inodes):

root #echo 2 > /proc/sys/vm/drop_caches

To clear the entire disk cache (slab objects and the page cache) use echo 3 instead:

root #echo 3 > /proc/sys/vm/drop_caches
경고
While the above commands are non-destructive (as long as a sync was completed before running them), they could seriously but temporarily slow down the system while the kernel loads only the necessary items back into memory. Think twice before running the above commands for systems under heavy load!

More information on kernel slabs can be found in this dedoimedo blog entry.

Mounting Btrfs fails, returning mount: unknown filesystem type 'btrfs'

The original solution by Tim on Stack Exchange inspired the following solution: build the kernel manually instead of using genkernel:

#cd /usr/src/linux
#make menuconfig
#make && make modules_install
#cp arch/x86_64/boot/bzImage /boot
#mv /boot/bzImage /boot/whatever_kernel_filename
#genkernel --install initramfs

Btrfs root doesn't boot

Genkernel's initramfs as created with the command below doesn't load btrfs:

root #genkernel --btrfs initramfs

Compile support for btrfs in the kernel rather than as a module, or use genkernel-next or Dracut to generate the initramfs.

See also

  • Btrfs snapshots - Script that creates snapshots when files have changed
  • Btrfs/System Root Guide - Use the Btrfs filesystem as a collection of subvolumes including one as a system root.
  • Btrfs native system root guide - An alternative guide on using a subvolume in a Btrfs filesystem as the system's root.
  • ext4 - The default filesystem for most Linux distributions.
  • Samba shadow copies - Using Samba to expose Shadow Copies as 'Previous Versions' to Windows clients.
  • Snapper - A command-line program capable of managing Btrfs filesystem snapshots.
  • ZFS - A filesystem that shares much in common with Btrfs, but has licensing issues.

External resources

References