Btrfs

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Btrfs and the translation is 27% complete.
Outdated translations are marked like this.

"Btrfs" es un sistema de ficheros copy-on-write (CoW) para Linux enfocado a implementar características novedosas y avanzadas y, a la vez, centrado en la tolerancia a fallos, reparación y facilidad de administración. Desarrollado conjuntamente por Oracle, Red Hat, Fujitsu, Intel, SUSE, STRATO, y muchos más, Btrfs está publicado bajo la licencia GPL y se encuentra abierto a contribuciones por parte de cualquier persona.

Ext4 es seguro y estable y es capaz de manejar sistemas de ficheros muy grandes sin problemas, entonces ¿Por qué cambiar?. Si bien es verdad que Btrfs aún es considerado experimental y está creciendo en cuanto a estabilidad, el momento en el que se convierta en el sistema de ficheros d por defecto en los sistemas Linux se va acercando. Algunas distribuciones ya han comenzado a cambiar en sus últimos lanzamientos. Btrfs tiene un gran número de características avanzadas en común con ZFS, las cuales hicieron que ZFS fuera tan popular entre las distribuciones de BSD y los dispositivos NAT.

  • Copy on Write (CoW) y snapshotting - Facilitar la creación de backups incluso desde un sistema de ficheros "en caliente" o de una máquina virtual.
  • Checksums a nivel de fichero - Los metadatos de cada fichero incluyen un checksum que es usado para detectar y reparar errores.
  • Compresión - Los ficheros pueden estar comprimidos o descomprimidos en vuelo, lo que aumenta la velocidad de lectura.
  • Auto-Desfragmentación - Los sistemas de ficheros son optimizados por un proceso en segundo plano "mientras" están en uso.
  • Subvolumenes - Los sistemas de ficheros pueden compartir un determinado espacio en vez de tener que utilizar sus propias particiones.
  • RAID - Btrfs tiene sus propias implementaciones de RAID de manera que LVM o mdadm no son necesarios para tener un RAID. De momento RAID 0 y 1 están soportados; RAID 5 y 6 están de camino.
  • Las particiones son opcionales - Si bien Btrfs puede trabajar con particiones, también es capaz de utilizar volumenes sin formato (/dev/<device>) directamente.
  • Deduplicación de datos - El soporte de deduplicación de datos es limitado; sin embargo, eventualmente se convertirá en una característica estándar en Btrfs. Ésto permite reducir el espacio ocupado mediante la comparación binaria de ficheros.
Consejo
Para una lista más exhaustiva y actualizada de las características visite la sección de estado de su Wiki. Sin embargo, no todas las características son lo suficientemente maduras para un uso extensivo.

Con el tiempo, los nuevos sistemas de ficheros en cluster tomarán ventaja de Btrfs mediante el uso de copy on write y otras características avanzadas referentes al almacenamiento de objetos. Ceph es un ejemplo de un sistema de ficheros en cluster que se ve realmente prometedor, y es capaz de aprovechar las ventajas de Btrfs.

Advertencia
Btrfs is said to be a stable and well-tested single-disk filesystem and ext4 replacement, but caution is advised when using advanced features such as Btrfs-RAID.[1]

Caveats

btrfs can counter-intuitively fail filesystem operations with ENOSPC when df reports free space due to internal fragmentation (free space pinned by DATA + SYSTEM chunks, but needed in METADATA chunks).

Additionally, a single 4K reference to a 128M extent inside btrfs can cause free space to be present, but unavailable for allocations. This can also cause btrfs to return ENOSPC when free space is reported by df.

Installing sys-fs/btrfsmaintenance and configuring the scripts to run periodically can help to reduce the possibility of ENOSPC issues by rebalancing btrfs, but it will not eliminate the risk of ENOSPC when free space is present. Some workloads will never hit ENOSPC while others will. If the risk of ENOSPC in production is unacceptable, you should use something else. If using btrfs, be certain to avoid configurations known to have issues.

With the exception of ENOSPC, information on the issues present in btrfs in the latest kernel branches is available at the btrfs status page.

Instalación

Kernel

Active las siguientes opciones del kernel para habilitar el soporte para Btrfs:

KERNEL Activate Btrfs in the kernel
File systems  --->
    <*> Btrfs filesystem

Emerge

El paquete sys-fs/btrfs-progs contiene las utilidades necesarias para trabajar con el sistema de ficheros Btrfs.

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

Uso

Consejo
Consider setting up sys-fs/btrfsmaintenance to handle regular balancing, defrag, trimming, and scrubbing.

Escribir largos comandos de Btrfs se puede convertir rápidamente en un incordio. Cada comando (además del btrfs inicial) puede ser reducido a un pequeño conjunto de instrucciones. Este método es de gran ayuda cuando se trabaja desde la línea de comandos ya que ayuda a reducir el número de caracteres a teclear.

Por ejemplo, para defragmentar un sistema de ficheros localizado en /, la manera larga sería:

root #btrfs filesystem defragment -v /

Acorte cada uno de los comandos largos a base de reducirlos a su prefijo único. En este contexto único significa que no existe una pareja de comandos que hagan cosas diferentes, por mínimas que sean, que concidan en la forma mínima del comando. La versión acortada del comando anterior es:

root #btrfs fi de -v /

Ningún otro comando de btrfs comienza con fi; filesystem es el único. Lo mismo se aplica al comando de, el cual es un subcomando del comando filesystem.

Creación

Advertencia
La orden mkfs.btrfs es irreversible y destruye todo el contenido de la partición a formatear. Por favor, asegúrese de que se ha seleccionado la partición en el disco correcto antes de ejecutar cualquier orden mkfs!

Para crear un sistema de ficheros Btrfs en la partición /dev/sdXN:

root #mkfs.btrfs /dev/sdXN

En el ejemplo anterior, reemplace N con el número de la partición y X con la letra del disco a formatear. Por ejemplo, para formatear la tercera partición del primer disco del sistema con formato Btrfs ejecute:

root #mkfs.btrfs /dev/sda3
Importante
El número de la última columna en /etc/fstab debe ser 0 para todas las particiones Btrfs. Ni fsck.btrfs ni btrfsck deberían ser ejecutados en cada inicio del sistema.

Labels

Labels can be added to btrfs filesystems, making mounting and organization easier.

Nota
Labels are generally less unique than UUIDs, but setting labels like rootfs for /, and homedir for /home can help with organization.
Advertencia
If multiple filesystems with the same label exist on a system, the first labeled system in the fstab, or the first returned by blkid will be mounted. It is generally best to avoid depending on this behavior, so unique labels should be used.

Labels can be added to a btrfs filesystem after it has been created by using:

root #btrfs filesystem label /dev/sda1 rootfs

Labels can be added when the btrfs filesystem is created with:

root #mkfs.btrfs -L rootfs /dev/sda1

Montaje

Después de la creación, los sistemas de ficheros se pueden montar de diferentes maneras:

  • mount - Montaje manual.
  • fstab - Definir los puntos de montaje en /etc/fstab activa los montajes automáticos en el inicio del sistema.
  • Removable media - Montajes automáticos a demanda (útil para memorias USB).
  • AutoFS - Montaje automático al acceder al sistema de ficheros.

Convertir sistemas de ficheros basados en ext*

Es posible convertir sistemas ext2, ext3 y ext4 a Btrfs using la herramienta btrfs-convert.

Las siguientes instrucciones solo soportan la conversión de sistemas de ficheros que se encuentran desmontados. Para convertir la partición root, inicie un disco de rescate del sistema (SystemRescueCD funciona perfectamente) y ejecute los comandos de conversión sobre la partición de root.

Primero, asegúrese de que el sistema no se encuentra montada:

root #umount <dispositivo_montado>

Compruebe la integridad del sistema de ficheros usando la herramienta apropiada de fsck. En el siguiente ejemplo, el sistema de ficheros es ext4:

root #fsck.ext4 -f <dispositivo_desmontado>

Use btrfs-convert para convertir el dispositivo con formato ext* a un dispositivo formateado en Btrfs:

root #btrfs-convert <dispositivo_desmontado>

Asegúrese de editar el fichero /etc/fstab después de que el dispositivo haya sido formateado para cambiar la columna de sistema de ficheros de ext4 a Btrfs:

ARCHIVO /etc/fstabCambiar de ext4 a btrfs
<device>   <mountpoint>  btrfs  defaults  0 0

Desfragmentación

Otra característica de Btrfs es la desfragmentación en línea. Para desfragmentar un sistema de ficheros root formateado en Btrfs ejecute el comando:

root #btrfs filesystem defragment -r -v /

La opción de montado autodefrag mantiene el efecto default del defragmentado online.

Advertencia
La desfragmentación con la versiones de kernel < 3.9 o ≥ 3.14-rc2, así como las versiones estables ≥ 3.10.31, ≥ 3.12.12 o ≥ 3.13.4 rompen los enlaces entre los ficheros y sus copias COW [2] y por lo tanto puede incrementar el espacio usado considerablemente. Asegúrese de que tiene suficiente espacio disponible y no demasiadas snapshots en el disco porque las particiones Btrfs pueden volverse realmente lentas.

Compresión

Btrfs ofrece soporte transparente para compresión usando los algoritmos zlib, lzo y zstd (v5.1.0)[3].

Es posible comprimir ficheros específicos utilizando los siguientes atributos de fichero:

user $chattr +c

La opción de montaje compress establece por defecto la compresión de los ficheros nuevos que se crean. Para comprimir de nuevo el sistema de ficheros completo usando la compresión lzo, ejecute la siguiente orden:

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

Dependiendo de la CPU y del rendimiento del disco, utilizar compresión mediante el algoritmo lzo podría mejorar el rendimiento en general.

Es posible utilizar el algoritmo de compresión zlib en vez de lzo. Zlib es más lento pero tiene un mejor ratio de compresión:

To force zlib compression across the whole filesystem:

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

Substitute zstd for zlib in the example above to activate zstd compression.

Nivel de compresión

Since kernel version 4.15.0[4], zlib compression can now be set by levels 1-9. Since kernel version 5.1.0 zstd can be set to levels 1-15. For example, to set zlib to maximum compression at mount time:

root #mount -o compress=zlib:9 /dev/sdXY /ruta/a/puntodemontaje/btrfs

Or to set minimal compression:

root #mount -o compress=zlib:1 /dev/sdXY /ruta/a/puntodemontaje/btrfs

Or adjust compression by remounting:

root #mount -o remount,compress=zlib:3 /ruta/a/puntodemontaje/btrfs

The compression level should be visible in /proc/mounts, or by checking the most recent dmesg output using the following command:

root #dmesg |grep -i btrfs
[    0.495284] Btrfs loaded, crc32c=crc32c-intel
[ 3010.727383] BTRFS: device label My Passport devid 1 transid 31 /dev/sdd1
[ 3111.930960] BTRFS info (device sdd1): disk space caching is enabled
[ 3111.930973] BTRFS info (device sdd1): has skinny extents
[ 9428.918325] BTRFS info (device sdd1): use zlib compression, level 3

Adjust fstab for compression

Once a drive has been remounted or adjusted to compress data, be sure to add the appropriate modifications to the /etc/fstab file. In this example, zstd compression is set with a level of 9 at mount time:

ARCHIVO /etc/fstabAdd Btrfs compression for zstd
/dev/sdb                /srv            btrfs           compress=zstd:9,relatime,rw     0 0

Compression ratio and disk usage

The usual userspace tools for determining used and free space like du and df may provide inaccurate results on a Btrfs partition due to inherent design differences in the way files are written compared to, for example, ext2/3/4[5].

It is therefore advised to use the du/df alternatives provided by the btrfs userspace tool btrfs filesystem. In addition, the compsize tool found in the sys-fs/compsize package can be helpful in providing additional information regarding compression ratios and the disk usage of compressed files. The following are example uses of these tools for a btrfs partition mounted under /media/drive.

user $btrfs filesystem du -s /media/drive
     Total   Exclusive  Set shared  Filename
 848.12GiB   848.12GiB       0.00B  /media/drive/
user $btrfs filesystem df /media/drive
Data, single: total=846.00GiB, used=845.61GiB
System, DUP: total=8.00MiB, used=112.00KiB
Metadata, DUP: total=2.00GiB, used=904.30MiB
GlobalReserve, single: total=512.00MiB, used=0.00B
user $compsize /media/drive
Processed 2262 files, 112115 regular extents (112115 refs), 174 inline.
Type       Perc     Disk Usage   Uncompressed Referenced  
TOTAL       99%      845G         848G         848G       
none       100%      844G         844G         844G       
zlib        16%      532M         3.2G         3.2G 

Múltiples dispositivos (RAID)

Se puede utilizar Btrfs con dispositivos múltiples (md) para crear RAIDs. Utilizar Btrfs para crear sistemas de ficheros que se extienden en dispositivos múltiples es más fácil que crearlos usando {tip{c|mdadm}}. No se necesita tiempo para inicialización para su creación.

Btrfs handles data and metadata separately. This is important to keep in mind when using a multi-device filesystem. It is possible to use separate profiles for data and metadata block groups. For example, metadata could be configured across multiple devices in RAID1, while data could be configured to RAID5. This profile is possible when using three or more block devices, since RAID5 requires a minimum of 3 block devices.

This type of profile offers the benefit of redundancy for metadata on each device and striping for data across devices, which increases read speeds. The drawback of this profile is more space than necessary is used for metadata, and write speeds are reduced for data blocks, since RAID5 uses a parity bit.

Creation

El método más simple es utilizar el dispositivo de bloques completo sin particionar para crear un sistema de ficheros. Por ejemplo, para crear un sistema de ficheros en modo RAID1 en dos dispositivos:

root #mkfs.btrfs -m raid1 <dispositivo1> <dispositivo2> -d raid1 <dispositivo1> <dispositivo2>

Conversion

Converting between RAID profiles is possible with the balance sub-command. For example, say three block devices are presently configured for RAID1 and mounted at /srv. It is possible to convert the data in this profile from RAID1 to RAID5 with the following command:

root #btrfs balance start -dconvert=raid0 -mconvert=raid0 --force /srv

Conversion can be performed while the filesystem is online and in use. Possible RAID modes in btrfs include RAID0, RAID1, RAID5, RAID6, and RAID10. See the upstream Btrfs wiki for more information.

Advertencia
Actualmente no es seguro utilizar los modos RAID 5 o RAID 6[6]. RAID 5 y 6 han recibido ciertas correcciones[7] en Linux 4.12, but en general siguen estando marcados como inestables.[8][9]. A los usuarios que quieran utilizar las funcionalidades de RAID 5 y RAID 6 en Btrfs se les recomienda que comprueben la página sobre el estado de Brtfs para ver el estado de la estabilidad de dichos modos antes de utilizarlos.

Addition

Additional devices can be added to existing multi device file systems. Follow the removal section below.

A riskier, but faster, alternative to safely removing a device is to shut the system down (or if the system supports hot swappable drives, at least unmount the filesystem), physically disconnect and remove the device that is to be replaced, substituted and connect the new device in it's place, power up the system (if necessary).

Note: Systems that will be power cycled will have the multi device filesystem fail to mount, since a device has been physically removed from the pool.

Once the system is booted, mount the multi-device filesystem with mount -odegraded, then perform the following steps on adding a new device.

root #mount -odegraded /srv
root #btrfs device add --force /dev/sdd /srv

After the device has been re-added it is then necessary to re-balance the filesystem to be sure data is spanned across the newly added device:

root #btrfs balance start /srv

Removal

By device path

Block devices (disks) can be removed from multi-device filesystems using the btrfs device remove subcommand:

root #btrfs device remove /dev/sde /srv
By device ID

Use the usage subcommand to determine the device IDs:

root #btrfs device usage /srv
/dev/sdb, ID: 3
   Device size:             1.82TiB
   Device slack:              0.00B
   Data,RAID1:             25.00GiB
   Data,RAID5:            497.00GiB
   Data,RAID5:              5.00GiB
   Metadata,RAID5:         17.00GiB
   Metadata,RAID5:        352.00MiB
   System,RAID5:           32.00MiB
   Unallocated:             1.29TiB
 
/dev/sdc, ID: 1
   Device size:             1.82TiB
   Device slack:              0.00B
   Data,RAID1:             25.00GiB
   Data,RAID5:            497.00GiB
   Data,RAID5:              5.00GiB
   Metadata,RAID5:         17.00GiB
   Metadata,RAID5:        352.00MiB
   System,RAID5:           32.00MiB
   Unallocated:             1.29TiB
 
/dev/sdd, ID: 4
   Device size:             1.82TiB
   Device slack:              0.00B
   Data,RAID1:             25.00GiB
   Data,RAID5:            497.00GiB
   Data,RAID5:              5.00GiB
   Metadata,RAID5:         17.00GiB
   Metadata,RAID5:        352.00MiB
   System,RAID5:           32.00MiB
   Unallocated:             1.29TiB
 
/dev/sde, ID: 5
   Device size:               0.00B
   Device slack:              0.00B
   Data,RAID1:             75.00GiB
   Data,RAID5:              5.00GiB
   Metadata,RAID5:        352.00MiB
   Unallocated:             1.74TiB

Next use the device ID to remove the device. In this case /dev/sde will be removed:

root #btrfs device remove 5 /srv

Resizing

btrfs partitions can be resized while online using the built-in resize subcommand.

Nota
This does not affect the size of the partition itself, just the filesystem.

Set the size of the root filesystem to 128gb:

root #btrfs filesystem resize 128g /

Add 50 gigabytes of space to the rootfs:

root #btrfs filesystem resize +50g /

The command can also fill all available space:

root #btrfs filesystem resize max /

Subvolúmenes

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.[10] They can be created at any location in the filesystem and will act like any other directory on the system with one difference: subvolumes can be mounted and unmounted. Subvolumes are nestable (subvolumes can be created inside other subvolumes), and easily created or removed.

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

Create

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

root #btrfs subvolume create <nombre-destino>

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/subvolumen1

List

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/subvolumen1

Remove

All available subvolume paths in a Btrfs filesystem can be seen using the list command above.

Subvolumes can be properly removed by using the subvolume delete command, followed by the path to the subvolume:

root #btrfs subvolume delete <ruta-al-subvolumen>

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/subvolumen1
Delete subvolume (no-commit): '/mnt/btrfs/subvolumen1'

Snapshots

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

ARCHIVO btrfs_snapshot.shEjemplo de trabajo cron para instantánea rootfs con Btrfs
#!/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/gentoo-repo subvolumes. The subvolumes could then be mounted at /home and /var/db/repos/gentoo, 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=<ruta-relativa> <dispositivo> <puntodemontaje>

Similarly, the filesystem tab can be updated to mount a Btrfs subvolume:

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

Troubleshooting

Filesystem check

With a failing disk or corrupted data, it may be necessary to run the a filesystem check. Typically filesystem check commands are handled through the fsck. prefix, but for btrfs filesystems, checks are handled via the btrfs check subcommand:

root #btrfs check --progress /dev/<device>
Nota
Checking multi-device filesystems are handled by passing any one of the devices in the filesystem to btrfs check. As long as all of the devices are available the check should run.

Multi device filesystem mount fails

After ungracefully removing one or more devices from a multi device filesystem, attempting to mount the filesystem will fail:

root #mnt /srv
mount: /srv: wrong fs type, bad option, bad superblock on /dev/sdb, missing codepage or helper program, or other error.

This type of mount failure could be caused by missing one or more devices from the multi device filesystem. Missing devices can be detected by using the filesystem show subcommand. In the following example /dev/sdb is one of the devices still connected to the multi device filesystem:

root #btrfs filesystem show /dev/sdb
Label: none  uuid: 9e7e9824-d66b-4a9c-a05c-c4245accabe99
        Total devices 5 FS bytes used 2.50TiB
        devid    1 size 1.82TiB used 817.03GiB path /dev/sdc
        devid    3 size 1.82TiB used 817.00GiB path /dev/sdb
        devid    5 size 10.91TiB used 2.53TiB path /dev/sde
        devid    6 size 10.91TiB used 2.53TiB path /dev/sdd
        *** Some devices missing

Missing device can be ungracefully dropped from the filesystem by using the following command:

root #btrfs device delete missing /srv
Advertencia
If the multi device filesystem is in RAID 0 mode, then data loss will occur!

Using with VM disk images

When using Btrfs with virtual machine disk images, it is best to disable copy-on-write on the disk images in order to speed up IO performance. This can only be performed on files that are newly created. It also possible to disable CoW on all files created within a certain directory. For example, using the chattr command:

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

Clear the free space cache

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

root #mount -o clear_cache /ruta/a/dispositivo /ruta/a/puntodemontaje

Btrfs hogging memory (disk cache)

When utilizing some of Btrfs' special abilities (like making many --reflink copies or creating high amounts of snapshots), a lot of memory can be consumed 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 slabtop utility (available as part of the sys-process/procps package) was specifically created to determine how much memory kernel objects are consuming:

{{RootCmd|slabtop|collapse-output=true|output=
Active / Total Objects (% used)    : 2259363 / 2338091 (96.6%)
Active / Total Slabs (% used)      : 467797 / 467803 (100.0%)
Active / Total Caches (% used)     : 83 / 175 (47.4%)
Active / Total Size (% used)       : 1489775.62K / 1512200.52K (98.5%)
Minimum / Average / Maximum Object : 0.02K / 0.65K / 4096.00K
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[11].
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
Advertencia
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 Dracut to generate the initramfs.

See also

* Btrfs/snapshots — script to make automatic snapshots with Btrfs filesystem, using btrfs subvolume list-new function to create snapshots only when files have changed, so as to create fewer snapshots. * Btrfs/System Root Guide — one example for re-basing a Gentoo installation's root filesystem to use btrfs * Btrfs/Native System Root Guide — alternative guide on using a subvolume in a Btrfs filesystem as the system's root * Ext4 — an open source disk filesystem and most recent version of the extended series of filesystems. * Btrbk — a tool for creating incremental snapshots and remote backups of Btrfs subvolumes. * Samba shadow copies — expose Shadow Copies as 'Previous Versions' to Windows clients. * Snapper — a command-line program to create and manage filesystem snapshots, allowing viewing or reversion of changes. * ZFS — a next generation filesystem created by Matthew Ahrens and Jeff Bonwick.

External resources

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

References