Btrfs/ru

Btrfs is Article description::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 является безопасной и стабильной и может обрабатывать большие файловые системы с экстентами, но зачем переключаться? Хотя Btrfs все еще считается экспериментальной, стабильность ее растет, и время, когда Btrfs станет файловой системой по умолчанию для систем Linux, становится все ближе. Некоторые дистрибутивы Linux уже начали переключаться на нее в своих текущих релизах. Btrfs имеет ряд дополнительных функций, общих с ZFS, которые и сделали файловую систему ZFS популярной для BSD дистрибутивов и устройств NAS.


 * 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 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 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.

Обновленный и отчасти исчерпывающий список функций смотрите на upstream wiki.

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:

Emerge
Пакет содержит утилиты необходимые для работы с файловой системой Btrfs.

Использование
Typing long Btrfs commands can quickly become a hassle. Each command (besides the initial 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.

Например, ниже показа длинная команда, чтобы дефрагментировать файловую систему расположенную в.

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

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

Создание
Чтобы создать файловую систему Btrfs на разделе :

В примере выше замените  на номер раздела, а   на букву диска. Например, чтобы отформатировать в Btrfs третий раздел на первом диске запустите:

Монтирование
После создания файловую систему можно смонтировать несколькими способами:


 * - смонтировать вручную.
 * - определить точку монтирования в файле, что позволит автоматически монтировать файловую систему во время загрузки.
 * съемные носители - автоматическое монтирование по запросу (полезно для USB-носителей).
 * AutoFS - автоматическая настройка для доступа к файловой системе.

Конвертация ext* файловых систем
Можно сконвертировать файловые системы ext2, ext3 и ext4 в Btrfs с помощью утилиты.

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.

Сперва убедитесь, что отмонтировали раздел:

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

Воспользуйтесь для того чтобы сконвертировать отформатированное в ext* устройство в Btrfs:

Убедитесь, что после форматирования устройства не забыли отредактировать файл и изменить значение в колонке файловая система с ext4 на Btrfs:

Дефрагментация
Другая полезная функция Btrfs это онлайн дефрагментация. Чтобы дефрагментировать файловую систему root с Btrfs запустите:

Сжатие
Btrfs поддерживает прозрачное сжатие с помощью алгоритмов zlib и lzo.

Можно сжать конкретный файл с помощью атрибутов файла:

The  mount option sets the default behavior to compress all the newly created files. To re-compress the whole file system, run the following command:

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:

RAID
Создать RAID в Btrfs гораздо проще, чем создать RAID с помощью.

The simplest method is to use the entire device to create a RAID:

Subvolumes
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. 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.

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

Replace  with the desired destination and subvolume name. For example, if a Btrfs filesystem exists at, a subvolume could be created inside it using the following command:

Список
To see the subvolume(s) that have been created, use the  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:

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:

Удаление
Subvolumes can be properly removed by using the  command followed by the path to the subvolume. All available subvolume paths in a Btrfs filesystem can be seen using the list command above.

As above, replace  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:

Snapshots
Snapshots are subvolumes that share data and metadata with other subvolumes. This is made possible by Btrfs' Copy on Write (CoW) ability. 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  commands:

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.

Монтирование
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 and create  and  subvolumes. The subvolumes could then be mounted at and, 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  is the relative path of the subvolume from the top level subvolume, obtainable through the   command:

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

Clear the free space cache
It is possible to clear Btrfs' free space cache by mounting the filesystem with the  mount option. For example:

Btrfs hogging memory (disk cache)
When utilizing some of Btrfs' special abilities (like making many  copies or creating a crazy amount of snapshots), lot of memory can be eaten and not freed fast enough by the kernel's inode cache. This issue can go undiscovered since memory dedicated to the disk cache might not be clearly visible in traditional system monitoring utilities. The utility (available as part of the  package) was specifically created to determine how much memory kernel objects are consuming:

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 file.

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

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

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

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:

Смотрите также

 * 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.

Внешние ресурсы

 * https://wiki.debian.org/Btrfs - As described by the Debian wiki.
 * https://wiki.archlinux.org/index.php/Btrfs Btrfs article - As described by the Arch Linux wiki.
 * http://www.funtoo.org/BTRFS_Fun - BTRFS Fun on the Funtoo wiki.
 * http://marc.merlins.org/perso/btrfs/post_2014-05-04_Fixing-Btrfs-Filesystem-Full-Problems.html - Tips and tricks on fixing niche Btrfs filesystem problems in some situations.