btrfs-device

title: btrfs-device(8)

summary: manage devices of btrfs filesystems

text:
# btrfs-device(8)

## NAME
btrfs-device - manage devices of btrfs filesystems

## SYNOPSIS
btrfs device <subcommand> <args>

## DESCRIPTION
The btrfs device command group is used to manage devices of the btrfs filesystems.

## DEVICE MANAGEMENT
BTRFS filesystem can be created on top of single or multiple block devices. Devices can be then added, removed or replaced on demand. Data and metadata are organized in allocation profiles with various redundancy policies. There's some similarity with traditional RAID levels, but this could be confusing to users familiar with the traditional meaning. Due to the similarity, the RAID terminology is widely used in the documentation. See mkfs.btrfs(8) for more details and the exact profile capabilities and constraints.

The device management works on a mounted filesystem. Devices can be added, removed or replaced, by commands provided by btrfs device and btrfs replace.

The profiles can be also changed, provided there's enough workspace to do the conversion, using the btrfs balance command and namely the filter convert.

Type

The block group profile type is the main distinction of the information stored on the block device. User data are called Data, the internal data structures managed by filesystem are Metadata and System.

Profile

A profile describes an allocation policy based on the redundancy/replication constraints in connection with the number of devices. The profile applies to data and metadata block groups separately. E.g. single, RAID1.

RAID level

Where applicable, the level refers to a profile that matches constraints of the standard RAID levels. At the moment the supported ones are: RAID0, RAID1, RAID10, RAID5 and RAID6.

## TYPICAL USE CASES

### Starting with a single-device filesystem
Assume we've created a filesystem on a block device /dev/sda with profile single/single (data/metadata), the device size is 50GiB and we've used the whole device for the filesystem. The mount point is /mnt.

The amount of data stored is 16GiB, metadata have allocated 2GiB.

### Add new device
We want to increase the total size of the filesystem and keep the profiles. The size of the new device /dev/sdb is 100GiB.

```
$ btrfs device add /dev/sdb /mnt
```

The amount of free data space increases by less than 100GiB, some space is allocated for metadata.

### Convert to RAID1
Now we want to increase the redundancy level of both data and metadata, but we'll do that in steps. Note, that the device sizes are not equal and we'll use that to show the capabilities of split data/metadata and independent profiles.

The constraint for RAID1 gives us at most 50GiB of usable space and exactly 2 copies will be stored on the devices.

First we'll convert the metadata. As the metadata occupy less than 50GiB and there's enough workspace for the conversion process, we can do:

```
$ btrfs balance start -mconvert=raid1 /mnt
```

This operation can take a while, because all metadata have to be moved and all block pointers updated. Depending on the physical locations of the old and new blocks, the disk seeking is the key factor affecting performance.

You'll note that the system block group has been also converted to RAID1, this normally happens as the system block group also holds metadata (the physical to logical mappings).

What changed:

- available data space decreased by 3GiB, usable roughly (50 - 3) + (100 - 3) = 144 GiB

- metadata redundancy increased

IOW, the unequal device sizes allow for combined space for data yet improved redundancy for metadata. If we decide to increase redundancy of data as well, we're going to lose 50GiB of the second device for obvious reasons.

```
$ btrfs balance start -dconvert=raid1 /mnt
```

The balance process needs some workspace (i.e. a free device space without any data or metadata block groups) so the command could fail if there's too much data or the block groups occupy the whole first device.

The device size of /dev/sdb as seen by the filesystem remains unchanged, but the logical space from 50-100GiB will be unused.

### Remove device
Device removal must satisfy the profile constraints, otherwise the command fails. For example:

```
$ btrfs device remove /dev/sda /mnt
ERROR: error removing device '/dev/sda': unable to go below two devices on raid1
```

In order to remove a device, you need to convert the profile in this case:

```
$ btrfs balance start -mconvert=dup -dconvert=single /mnt
$ btrfs device remove /dev/sda /mnt
```

WARNING:

Do not run balance to convert from a profile with more redundancy to one with less redundancy in order to remove a failing device from a filesystem. Balance is done by reading out the good metadata/data and write them into into a new chunk. Thus it's possible the new chunk is written into the failing device.

Use btrfs device replace instead.

## SUBCOMMAND
add [-Kf] <device> [<device>...] <path>

Add device(s) to the filesystem identified by path. If applicable, a whole device discard (TRIM) operation is performed prior to adding the device. A device with existing filesystem detected by blkid(8) will prevent device addition and has to be forced. Alternatively the filesystem can be wiped from the device using e.g. the wipefs(8) tool.

The operation is instant and does not affect existing data. The operation merely adds the device to the filesystem structures and creates some block groups headers.

Options

-K|--nodiscard

do not perform discard (TRIM) by default

-f|--force

force overwrite of existing filesystem on the given disk(s)

--enqueue

wait if there's another exclusive operation running, otherwise continue

remove [options] <device>|<devid> [<device>|<devid>...] <path>

Remove device(s) from a filesystem identified by <path> Device removal must satisfy the profile constraints, otherwise the command fails and cannot be enforced. The filesystem must be converted to profile(s) that would allow the removal. This can for example happen when going down from 2 devices to 1 and using the RAID1 profile. See the section Typical use cases.

The operation can take long as it needs to move all data from the device.

NOTE:

It's possible to specify more than one device on the command line but the devices will be removed one by one, not at once. This means that the remaining devices to be deleted can be still used for writes. In that case there's a warning and safety timeout as this can be confusing and unexpected. The timeout can be overridden by option --force.

It is possible to delete the device that was used to mount the filesystem. The device entry in the mount table (/proc/self/mounts) will be replaced by another device name with the lowest device id.

If the filesystem is mounted in degraded mode (-o degraded), special term missing can be used for device. In that case, the first device that is described by the filesystem metadata, but not present at the mount time will be removed.

NOTE:

In most cases, there is only one missing device in degraded mode, otherwise mount fails. If there are two or more devices missing (e.g. possible in RAID6), you need specify missing as many times as the number of missing devices to remove all of them.

Options

--enqueue

wait if there's another exclusive operation running, otherwise continue

--force

skip the safety timeout when there are multiple devices for removal, this does not force removing devices that would break the profile constraints

delete <device>|<devid> [<device>|<devid>...] <path>

Alias of remove kept for backward compatibility

replace <command> [options] <path>

Alias of whole command group btrfs replace for convenience. See btrfs-replace(8).

ready <device>

Wait until all devices of a multiple-device filesystem are scanned and registered within the kernel module. This is to provide a way for automatic filesystem mounting tools to wait before the mount can start. The device scan is only one of the preconditions and the mount can fail for other reasons. Normal users usually do not need this command and may safely ignore it.

scan [options] [<device> [<device>...]]

Scan devices for a btrfs filesystem and register them with the kernel module. This allows mounting multiple-device filesystem by specifying just one from the whole group. If no devices are passed, all block devices that blkid reports to contain btrfs are scanned.

The options --all-devices or -d can be used as a fallback in case blkid is not available. If used, behavior is the same as if no devices are passed.

The command can be run repeatedly. Devices that have been already registered remain as such. Reloading the kernel module will drop this information. There's an alternative way of mounting multiple-device filesystem without the need for prior scanning. See the mount option device (in btrfs-man5).

Options

-d|--all-devices

Enumerate and register all devices, use as a fallback in case blkid is not available.

-u|--forget

Unregister a given device or all stale devices if no path is given, the device must be unmounted otherwise it's an error.

stats [options] <path>|<device>

Read and print the device IO error statistics for all devices of the given filesystem identified by path or for a single device. The filesystem must be mounted. See section DEVICE STATS for more information about the reported statistics and the meaning. Options

-z|--reset

Print the stats and reset the values to zero afterwards.

-c|--check

Check if the stats are all zeros and return 0 if it is so. Set bit 6 of the return code if any of the statistics is no-zero. The error values is 65 if reading stats from at least one device failed, otherwise it's 64.

-T

Print stats in a tabular form, devices as rows and stats as columns

usage [options] <path> [<path>...]::

Show detailed information about internal allocations on devices. The level of detail can differ if the command is run under a regular or the root user (due to use of restricted ioctls). The first example below is for normal user (warning included) and the next one with root on the same filesystem:

```
WARNING: cannot read detailed chunk info, per-device usage will not be shown, run as root
/dev/sdc1, ID: 1

   Device size:           931.51GiB

   Device slack:              0.00B

   Unallocated:           931.51GiB
/dev/sdc1, ID: 1

   Device size:           931.51GiB

   Device slack:              0.00B

   Data,single:           641.00GiB

   Data,RAID0/3:            1.00GiB

   Metadata,single:        19.00GiB

   System,single:          32.00MiB

   Unallocated:           271.48GiB
```

- Device size -- size of the device as seen by the filesystem (may be different than actual device size)

- Device slack -- portion of device not used by the filesystem but still available in the physical space provided by the device, e.g. after a device shrink

- Data,single, Metadata,single, System,single -- in general, list of block group type (Data, Metadata, System) and profile (single, RAID1, ...) allocated on the device

- Data,RAID0/3 -- in particular, striped profiles RAID0/RAID10/RAID5/RAID6 with the number of devices on which the stripes are allocated, multiple occurrences of the same profile can appear in case a new device has been added and all new available stripes have been used for writes

- Unallocated -- remaining space that the filesystem can still use for new block groups

Options

-b|--raw

raw numbers in bytes, without the B suffix

-h|--human-readable

print human friendly numbers, base 1024, this is the default

-H

print human friendly numbers, base 1000

--iec

select the 1024 base for the following options, according to the IEC standard

--si

select the 1000 base for the following options, according to the SI standard

-k|--kbytes

show sizes in KiB, or kB with --si

-m|--mbytes

show sizes in MiB, or MB with --si

-g|--gbytes

show sizes in GiB, or GB with --si

-t|--tbytes

show sizes in TiB, or TB with --si

If conflicting options are passed, the last one takes precedence.

## DEVICE STATS
The device stats keep persistent record of several error classes related to doing IO. The current values are printed at mount time and updated during filesystem lifetime or from a scrub run.

```
$ btrfs device stats /dev/sda3
[/dev/sda3].write_io_errs   0
[/dev/sda3].read_io_errs    0
[/dev/sda3].flush_io_errs   0
[/dev/sda3].corruption_errs 0
[/dev/sda3].generation_errs 0
```

write_io_errs

Failed writes to the block devices, means that the layers beneath the filesystem were not able to satisfy the write request.

read_io_errors

Read request analogy to write_io_errs.

flush_io_errs

Number of failed writes with the FLUSH flag set. The flushing is a method of forcing a particular order between write requests and is crucial for implementing crash consistency. In case of btrfs, all the metadata blocks must be permanently stored on the block device before the superblock is written.

corruption_errs

A block checksum mismatched or a corrupted metadata header was found.

generation_errs

The block generation does not match the expected value (e.g. stored in the parent node).

Since kernel 5.14 the device stats are also available in textual form in /sys/fs/btrfs/FSID/devinfo/DEVID/error_stats.

## EXIT STATUS
btrfs device returns a zero exit status if it succeeds. Non zero is returned in case of failure.

If the -c option is used, btrfs device stats will add 64 to the exit status if any of the error counters is non-zero.

## AVAILABILITY
btrfs is part of btrfs-progs. Please refer to the documentation at https://btrfs.readthedocs.io.

## SEE ALSO
btrfs-balance(8) btrfs-device(8), btrfs-replace(8), mkfs.btrfs(8)


btrfs-filesystem

package: btrfs-progs

title: btrfs-filesystem(8)

text:
# btrfs-filesystem(8)

## NAME
btrfs-filesystem - command group that primarily does work on the whole filesystems

## SYNOPSIS
btrfs filesystem <subcommand> <args>

## DESCRIPTION
btrfs filesystem is used to perform several whole filesystem level tasks, including all the regular filesystem operations like resizing, space stats, label setting/getting, and defragmentation. There are other whole filesystem tasks like scrub or balance that are grouped in separate commands.

## SUBCOMMAND
df [options] <path>

Show a terse summary information about allocation of block group types of a given mount point. The original purpose of this command was a debugging helper. The output needs to be further interpreted and is not suitable for quick overview. An example with description:

- device size: 1.9TiB, one device, no RAID

- filesystem size: 1.9TiB

- created with: mkfs.btrfs -d single -m single

```
$ btrfs filesystem df /path
Data, single: total=1.15TiB, used=1.13TiB
System, single: total=32.00MiB, used=144.00KiB
Metadata, single: total=12.00GiB, used=6.45GiB
GlobalReserve, single: total=512.00MiB, used=0.00B
```

- Data, System and Metadata are separate block group types. GlobalReserve is an artificial and internal emergency space, see below.

- single -- the allocation profile, defined at mkfs time

- total -- sum of space reserved for all allocation profiles of the given type, i.e. all Data/single. Note that it's not total size of filesystem.

- used -- sum of used space of the above, i.e. file extents, metadata blocks

GlobalReserve is an artificial and internal emergency space. It is used e.g. when the filesystem is full. Its total size is dynamic based on the filesystem size, usually not larger than 512MiB, used may fluctuate.

The GlobalReserve is a portion of Metadata. In case the filesystem metadata is exhausted, GlobalReserve/total + Metadata/used = Metadata/total. Otherwise there appears to be some unused space of Metadata.

Options

-b|--raw

raw numbers in bytes, without the B suffix

-h|--human-readable

print human friendly numbers, base 1024, this is the default

-H

print human friendly numbers, base 1000

--iec

select the 1024 base for the following options, according to the IEC standard

--si

select the 1000 base for the following options, according to the SI standard

-k|--kbytes

show sizes in KiB, or kB with --si

-m|--mbytes

show sizes in MiB, or MB with --si

-g|--gbytes

show sizes in GiB, or GB with --si

-t|--tbytes

show sizes in TiB, or TB with --si

If conflicting options are passed, the last one takes precedence.

defragment [options] <file>|<dir> [<file>|<dir>...]

Defragment file data on a mounted filesystem. Requires kernel 2.6.33 and newer. If -r is passed, files in dir will be defragmented recursively (not descending to subvolumes, mount points and directory symlinks). The start position and the number of bytes to defragment can be specified by start and length using -s and -l options below. Extents bigger than value given by -t will be skipped, otherwise this value is used as a target extent size, but is only advisory and may not be reached if the free space is too fragmented. Use 0 to take the kernel default, which is 256KiB but may change in the future. You can also turn on compression in defragment operations.

WARNING:

Defragmenting with Linux 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 will break up the reflinks of COW data (for example files copied with cp --reflink, snapshots or de-duplicated data). This may cause considerable increase of space usage depending on the broken up reflinks.

NOTE:

Directory arguments without -r do not defragment files recursively but will defragment certain internal trees (extent tree and the subvolume tree). This has been confusing and could be removed in the future.

For start, len, size it is possible to append units designator: K, M, G, T, P, or E, which represent KiB, MiB, GiB, TiB, PiB, or EiB, respectively (case does not matter).

Options

-c[<algo>]

compress file contents while defragmenting. Optional argument selects the compression algorithm, zlib (default), lzo or zstd. Currently it's not possible to select no compression. See also section EXAMPLES.

-r

defragment files recursively in given directories, does not descend to subvolumes or mount points

-f

flush data for each file before going to the next file. This will limit the amount of dirty data to current file, otherwise the amount accumulates from several files and will increase system load. This can also lead to ENOSPC if there's too much dirty data to write and it's not possible to make the reservations for the new data (i.e. how the COW design works).

-s <start>[kKmMgGtTpPeE]

defragmentation will start from the given offset, default is beginning of a file

-l <len>[kKmMgGtTpPeE]

defragment only up to len bytes, default is the file size

-t <size>[kKmMgGtTpPeE]

target extent size, do not touch extents bigger than size, default: 32MiB The value is only advisory and the final size of the extents may differ, depending on the state of the free space and fragmentation or other internal logic. Reasonable values are from tens to hundreds of megabytes.

--step SIZE

Perform defragmentation in the range in SIZE steps and flush (-f) after each one. The range is default (the whole file) or given by -s and -l, split into the steps or done in one go if the step is larger. Minimum range size is 256KiB.

-v

(deprecated) alias for global -v option

du [options] <path> [<path>..]

Calculate disk usage of the target files using FIEMAP. For individual files, it will report a count of total bytes, and exclusive (not shared) bytes. We also calculate a 'set shared' value which is described below. Each argument to btrfs filesystem du will have a set shared value calculated for it. We define each set as those files found by a recursive search of an argument (recursion descends to subvolumes but not mount points). The set shared value then is a sum of all shared space referenced by the set.

set shared takes into account overlapping shared extents, hence it isn't as simple as adding up shared extents.

Options

-s|--summarize

display only a total for each argument

--raw

raw numbers in bytes, without the B suffix.

--human-readable

print human friendly numbers, base 1024, this is the default

--iec

select the 1024 base for the following options, according to the IEC standard.

--si

select the 1000 base for the following options, according to the SI standard.

--kbytes

show sizes in KiB, or kB with --si.

--mbytes

show sizes in MiB, or MB with --si.

--gbytes

show sizes in GiB, or GB with --si.

--tbytes

show sizes in TiB, or TB with --si.

label [<device>|<mountpoint>] [<newlabel>]

Show or update the label of a filesystem. This works on a mounted filesystem or a filesystem image. The newlabel argument is optional. Current label is printed if the argument is omitted.

NOTE:

The maximum allowable length shall be less than 256 chars and must not contain a newline. The trailing newline is stripped automatically.

mkswapfile [-s size] file

Create a new file that's suitable and formatted as a swapfile. Default size is 2GiB, fixed page size 4KiB, minimum size is 40KiB. A swapfile must be created in a specific way: NOCOW and preallocated. Subvolume containing a swapfile cannot be snapshotted and blocks of an activated swapfile cannot be balanced.

Swapfile creation can be achieved by standalone commands too. Activation needs to be done by command swapon(8). See also command btrfs inspect-internal map-swapfile and the Swapfile feature description.

NOTE:

The command is a simplified version of 'mkswap', if you want to set label, page size, or other parameters please use 'mkswap' proper.

Options

-s|--size SIZE

Create swapfile of a given size SIZE (accepting k/m/g/e/p suffix).

-U|--uuid UUID

specify UUID to use, or a special value: clear (all zeros), random, time (time-based random)

resize [options] [<devid>:][+/-]<size>[kKmMgGtTpPeE]|[<devid>:]max <path>

Resize a mounted filesystem identified by path. A particular device can be resized by specifying a devid. WARNING:

If path is a file containing a BTRFS image then resize does not work as expected and does not resize the image. This would resize the underlying filesystem instead.

The devid can be found in the output of btrfs filesystem show and defaults to 1 if not specified. The size parameter specifies the new size of the filesystem. If the prefix + or - is present the size is increased or decreased by the quantity size. If no units are specified, bytes are assumed for size. Optionally, the size parameter may be suffixed by one of the following unit designators: K, M, G, T, P, or E, which represent KiB, MiB, GiB, TiB, PiB, or EiB, respectively (case does not matter).

If max is passed, the filesystem will occupy all available space on the device respecting devid (remember, devid 1 by default).

The resize command does not manipulate the size of underlying partition. If you wish to enlarge/reduce a filesystem, you must make sure you expand the partition before enlarging the filesystem and shrink the partition after reducing the size of the filesystem. This can be done using fdisk(8) or parted(8) to delete the existing partition and recreate it with the new desired size. When recreating the partition make sure to use the same starting partition offset as before.

The size of the portion that the filesystem uses of an underlying device can be determined via the btrfs filesystem show --raw command on the filesystem’s mount point (where it’s given for each devid after the string size or via the btrfs inspect-internal dump-super command on the specific device (where it’s given as the value of dev_item.total_bytes, which is not to be confused with total_bytes). The value is also the address of the first byte not used by the filesystem.

Growing is usually instant as it only updates the size. However, shrinking could take a long time if there are data in the device area that's beyond the new end. Relocation of the data takes time.

Note that there's a lower limit on the new size (either specified as an absolute size or difference) that is checked by kernel and rejected eventually as invalid. Lower values will print a warning but still pass the request to kernel. The currently known value is 256MiB.

See also section EXAMPLES.

Options

--enqueue

wait if there's another exclusive operation running, otherwise continue

show [options] [<path>|<uuid>|<device>|<label>]

Show the btrfs filesystem with some additional info about devices and space allocation. If no option none of path/uuid/device/label is passed, information about all the BTRFS filesystems is shown, both mounted and unmounted.

Options

-m|--mounted

probe kernel for mounted BTRFS filesystems

-d|--all-devices

scan all devices under /dev, otherwise the devices list is extracted from the /proc/partitions file. This is a fallback option if there's no device node manager (like udev) available in the system.

--raw

raw numbers in bytes, without the B suffix

--human-readable

print human friendly numbers, base 1024, this is the default

--iec

select the 1024 base for the following options, according to the IEC standard

--si

select the 1000 base for the following options, according to the SI standard

--kbytes

show sizes in KiB, or kB with --si

--mbytes

show sizes in MiB, or MB with --si

--gbytes

show sizes in GiB, or GB with --si

--tbytes

show sizes in TiB, or TB with --si

sync <path>

Force a sync of the filesystem at path, similar to the sync(1) command. In addition, it starts cleaning of deleted subvolumes. To wait for the subvolume deletion to complete use the btrfs subvolume sync command.

usage [options] <path> [<path>...]

Show detailed information about internal filesystem usage. This is supposed to replace the btrfs filesystem df command in the long run. The level of detail can differ if the command is run under a regular or the root user (due to use of restricted ioctl). For both there's a summary section with information about space usage:

```
$ btrfs filesystem usage /path
WARNING: cannot read detailed chunk info, RAID5/6 numbers will be incorrect, run as root
Overall:

    Device size:                   1.82TiB

    Device allocated:              1.17TiB

    Device unallocated:          669.99GiB

    Device missing:                  0.00B

    Device slack:                  1.00GiB

    Used:                          1.14TiB

    Free (estimated):            692.57GiB      (min: 692.57GiB)

    Free (statfs, df)            692.57GiB

    Data ratio:                       1.00

    Metadata ratio:                   1.00

    Global reserve:              512.00MiB      (used: 0.00B)

    Multiple profiles:                  no
```

- Device size -- sum of raw device capacity available to the filesystem, note that this may not be the same as the total device size (the difference is accounted as slack)

- Device allocated -- sum of total space allocated for data/metadata/system profiles, this also accounts space reserved but not yet used for extents

- Device unallocated -- the remaining unallocated space for future allocations (difference of the above two numbers)

- Device missing -- sum of capacity of all missing devices

- Device slack -- sum of slack space on all devices (difference between entire device size and the space occupied by filesystem)

- Used -- sum of the used space of data/metadata/system profiles, not including the reserved space

- Free (estimated) -- approximate size of the remaining free space usable for data, including currently allocated space and estimating the usage of the unallocated space based on the block group profiles, the min is the lower bound of the estimate in case multiple profiles are present

- Free (statfs, df) -- the amount of space available for data as reported by the statfs/statvfs syscall, also returned as Avail in the output of df. The value is calculated in a different way and may not match the estimate in some cases (e.g. multiple profiles).

- Data ratio -- ratio of total space for data including redundancy or parity to the effectively usable data space, e.g. single is 1.0, RAID1 is 2.0 and for RAID5/6 it depends on the number of devices

- Metadata ratio -- ditto, for metadata

- Global reserve -- portion of metadata currently used for global block reserve, used for emergency purposes (like deletion on a full filesystem)

- Multiple profiles -- what block group types (data, metadata) have more than one profile (single, raid1, ...), see btrfs(5) section FILESYSTEMS WITH MULTIPLE PROFILES.

And on a zoned filesystem there are two more lines in the Device section:

```
Device zone unusable:          5.13GiB
Device zone size:            256.00MiB
```

- Device zone unusable -- sum of of space that's been used in the past but now is not due to COW and not referenced anymore, the chunks have to be reclaimed and zones reset to make it usable again

- Device zone size -- the reported zone size of the host-managed device, same for all devices

The root user will also see stats broken down by block group types:

```
Data,single: Size:1.15TiB, Used:1.13TiB (98.26%)

   /dev/sdb        1.15TiB
Metadata,single: Size:12.00GiB, Used:6.45GiB (53.75%)

   /dev/sdb       12.00GiB
System,single: Size:32.00MiB, Used:144.00KiB (0.44%)

   /dev/sdb       32.00MiB
Unallocated:

   /dev/sdb      669.99GiB
```

Data is block group type, single is block group profile, Size is total size occupied by this type, Used is the actually used space, the percent is ratio of Used/Size. The Unallocated is remaining space.

Options

-b|--raw

raw numbers in bytes, without the B suffix

-h|--human-readable

print human friendly numbers, base 1024, this is the default

-H

print human friendly numbers, base 1000

--iec

select the 1024 base for the following options, according to the IEC standard

--si

select the 1000 base for the following options, according to the SI standard

-k|--kbytes

show sizes in KiB, or kB with --si

-m|--mbytes

show sizes in MiB, or MB with --si

-g|--gbytes

show sizes in GiB, or GB with --si

-t|--tbytes

show sizes in TiB, or TB with --si

-T

show data in tabular format

If conflicting options are passed, the last one takes precedence.

## EXAMPLES
$ btrfs filesystem defrag -v -r dir/

Recursively defragment files under dir/, print files as they are processed. The file names will be printed in batches, similarly the amount of data triggered by defragmentation will be proportional to last N printed files. The system dirty memory throttling will slow down the defragmentation but there can still be a lot of IO load and the system may stall for a moment.

$ btrfs filesystem defrag -v -r -f dir/

Recursively defragment files under dir/, be verbose and wait until all blocks are flushed before processing next file. You can note slower progress of the output and lower IO load (proportional to currently defragmented file).

$ btrfs filesystem defrag -v -r -f -clzo dir/

Recursively defragment files under dir/, be verbose, wait until all blocks are flushed and force file compression.

$ btrfs filesystem defrag -v -r -t 64M dir/

Recursively defragment files under dir/, be verbose and try to merge extents to be about 64MiB. As stated above, the success rate depends on actual free space fragmentation and the final result is not guaranteed to meet the target even if run repeatedly.

$ btrfs filesystem resize -1G /path

$ btrfs filesystem resize 1:-1G /path

Shrink size of the filesystem's device id 1 by 1GiB. The first syntax expects a device with id 1 to exist, otherwise fails. The second is equivalent and more explicit. For a single-device filesystem it's typically not necessary to specify the devid though.

$ btrfs filesystem resize max /path

$ btrfs filesystem resize 1:max /path

Let's assume that devid 1 exists and the filesystem does not occupy the whole block device, e.g. it has been enlarged and we want to grow the filesystem. By simply using max as size we will achieve that.

NOTE:

There are two ways to minimize the filesystem on a given device. The btrfs inspect-internal min-dev-size command, or iteratively shrink in steps.

## EXIT STATUS
btrfs filesystem returns a zero exit status if it succeeds. Non zero is returned in case of failure.

## AVAILABILITY
btrfs is part of btrfs-progs. Please refer to the documentation at https://btrfs.readthedocs.io.

## SEE ALSO
btrfs-subvolume(8), mkfs.btrfs(8)


btrfs-find-root

title: btrfs-find-root(8)

summary: filter to find btrfs root

text:
# btrfs-find-root(8)

## NAME
btrfs-find-root - filter to find btrfs root

## SYNOPSIS
btrfs-find-root [options] <device>

## DESCRIPTION
btrfs-find-root is used to find the satisfied root, you can filter by root tree's objectid, generation, level.

## OPTIONS
-a

Search through all metadata extents, even the root has been already found.

-g <generation>

Filter root tree by it's original transaction id, tree root's generation in default.

-o <objectid>

Filter root tree by it's objectid,tree root's objectid in default.

-l <level>

Filter root tree by b-tree's level, level 0 in default.

## EXIT STATUS
btrfs-find-root will return 0 if no error happened. If any problems happened, 1 will be returned.

## SEE ALSO
mkfs.btrfs(8)


btrfs-image

title: btrfs-image(8)

text:
# btrfs-image(8)

## NAME
btrfs-image - create/restore an image of the filesystem

## SYNOPSIS
btrfs-image [options] <source> <target>

## DESCRIPTION
btrfs-image is used to create an image of a btrfs filesystem. All data will be zeroed, but metadata and the like is preserved. Mainly used for debugging purposes.

In the dump mode, source is the btrfs device/file and target is the output file (use - for stdout).

In the restore mode (option -r), source is the dumped image and target is the btrfs device/file.

## OPTIONS
-r

Restore metadump image. By default, this fixes super's chunk tree, by using 1 stripe pointing to primary device, so that file system can be restored by running tree log reply if possible. To restore without changing number of stripes in chunk tree check -o option.

-c <value>

Compression level (0 ~ 9).

-t <value>

Number of threads (1 ~ 32) to be used to process the image dump or restore.

-o

Use the old restore method, this does not fixup the chunk tree so the restored file system will not be able to be mounted.

-s

Sanitize the file names when generating the image. Not recommended as this would introduce new file name hash mismatches, thus if your problem involves subvolume tress, it can even mask existing problems. Furthermore kernels can not do proper path resolution due to the introduced hash mismatches. One -s means just generate random garbage, which means that the directory hash won't match its file names. Using two -s will calculate a collision for the file name so that the hashes match, and if it can't calculate a collision then it will just generate garbage. The collision calculator is very time and CPU intensive.

-w

Walk all the trees manually and copy any blocks that are referenced. Use this option if your extent tree is corrupted to make sure that all of the metadata is captured.

-m

Restore for multiple devices, more than 1 device should be provided.

--version

Print the btrfs-image version, builtin features and exit.

## EXIT STATUS
btrfs-image will return 0 if no error happened. If any problems happened, 1 will be returned.

## SEE ALSO
mkfs.btrfs(8)


btrfs-inspect-internal

title: btrfs-inspect-internal(8)

summary: query various internal information

text:
# btrfs-inspect-internal(8)

## NAME
btrfs-inspect-internal - query various internal information

## SYNOPSIS
btrfs inspect-internal <subcommand> <args>

## DESCRIPTION
This command group provides an interface to query internal information. The functionality ranges from a simple UI to an ioctl or a more complex query that assembles the result from several internal structures. The latter usually requires calls to privileged ioctls.

## SUBCOMMAND
dump-super [options] <device> [device...]

Show btrfs superblock information stored on given devices in textual form. By default the first superblock is printed, more details about all copies or additional backup data can be printed. Besides verification of the filesystem signature, there are no other sanity checks. The superblock checksum status is reported, the device item and filesystem UUIDs are checked and reported.

NOTE:

The meaning of option -s has changed in version 4.8 to be consistent with other tools to specify superblock copy rather the offset. The old way still works, but prints a warning. Please update your scripts to use --bytenr instead. The option -i has been deprecated.

Options

-f|--full

print full superblock information, including the system chunk array and backup roots

-a|--all

print information about all present superblock copies (cannot be used together with -s option)

-i <super>

(deprecated since 4.8, same behaviour as --super)

--bytenr <bytenr>

specify offset to a superblock in a non-standard location at bytenr, useful for debugging (disables the -f option) If there are multiple options specified, only the last one applies.

-F|--force

attempt to print the superblock even if a valid BTRFS signature is not found; the result may be completely wrong if the data does not resemble a superblock

-s|--super <bytenr>

(see compatibility note above) specify which mirror to print, valid values are 0, 1 and 2 and the superblock must be present on the device with a valid signature, can be used together with --force

dump-tree [options] <device> [device...]

Dump tree structures from a given device in textual form, expand keys to human readable equivalents where possible. This is useful for analyzing filesystem state or inconsistencies and has a positive educational effect on understanding the internal filesystem structure. NOTE:

By default contains file names, consider that if you're asked to send the dump for analysis and use --hide-names eventually. Does not contain file data.

Special characters in file names, xattr names and values are escaped, in the C style like \n and octal encoding \NNN.

Options

-e|--extents

print only extent-related information: extent and device trees

-d|--device

print only device-related information: tree root, chunk and device trees

-r|--roots

print only short root node information, i.e. the root tree keys

-R|--backups

same as --roots plus print backup root info, i.e. the backup root keys and the respective tree root block offset

-u|--uuid

print only the uuid tree information, empty output if the tree does not exist

-b <block_num>

print info of the specified block only, can be specified multiple times

--follow

use with -b, print all children tree blocks of <block_num>

--dfs

(default up to 5.2) use depth-first search to print trees, the nodes and leaves are intermixed in the output

--bfs

(default since 5.3) use breadth-first search to print trees, the nodes are printed before all leaves

--hide-names

print a placeholder HIDDEN instead of various names, useful for developers to inspect the dump while keeping potentially sensitive information hidden This is:

- directory entries (files, directories, subvolumes)

- default subvolume

- extended attributes (name, value)

- hardlink names (if stored inside another item or as extended references in standalone items)

NOTE:

Lengths are not hidden because they can be calculated from the item size anyway.

--csum-headers

print b-tree node checksums stored in headers (metadata)

--csum-items

print checksums stored in checksum items (data)

--noscan

do not automatically scan the system for other devices from the same filesystem, only use the devices provided as the arguments

-t <tree_id>

print only the tree with the specified ID, where the ID can be numerical or common name in a flexible human readable form The tree id name recognition rules:

- case does not matter

- the C source definition, e.g. BTRFS_ROOT_TREE_OBJECTID

- short forms without BTRFS_ prefix, without _TREE and _OBJECTID suffix, e.g. ROOT_TREE, ROOT

- convenience aliases, e.g. DEVICE for the DEV tree, CHECKSUM for CSUM

- unrecognized ID is an error

inode-resolve [-v] <ino> <path>

(needs root privileges) resolve paths to all files with given inode number ino in a given subvolume at path, i.e. all hardlinks

Options

-v

(deprecated) alias for global -v option

logical-resolve [-Pvo] [-s <bufsize>] <logical> <path>

(needs root privileges) resolve paths to all files at given logical address in the linear filesystem space

Options

-P

skip the path resolving and print the inodes instead

-o

ignore offsets, find all references to an extent instead of a single block. Requires kernel support for the V2 ioctl (added in 4.15). The results might need further processing to filter out unwanted extents by the offset that is supposed to be obtained by other means.

-s <bufsize>

set internal buffer for storing the file names to bufsize, default is 64KiB, maximum 16MiB. Buffer sizes over 64Kib require kernel support for the V2 ioctl (added in 4.15).

-v

(deprecated) alias for global -v option

list-chunks [options] <path>

(needs root privileges) Enumerate chunks on all devices. The chunks represent the physical range on devices (not to be confused with block groups that represent the logical ranges, but the terms are often used interchangeably).

Example output:

```
Devid PNumber      Type/profile    PStart    Length      PEnd LNumber    LStart Usage%
----- ------- ----------------- --------- --------- --------- ------- --------- ------

    1       1       Data/single   1.00MiB  84.00MiB  85.00MiB      68 191.60GiB  62.77

    1       2     System/DUP     85.00MiB  32.00MiB 117.00MiB      39 140.17GiB   0.05

    1       3     System/DUP    117.00MiB  32.00MiB 149.00MiB      40 140.17GiB   0.05

    1       4   Metadata/DUP    149.00MiB 192.00MiB 341.00MiB      59 188.41GiB  45.00

    1       5   Metadata/DUP    341.00MiB 192.00MiB 533.00MiB      60 188.41GiB  45.00

    1       6       Data/single 533.00MiB   1.00GiB   1.52GiB      49 169.91GiB  72.23

    1       7       Data/single   1.52GiB  16.00MiB   1.54GiB      69 191.68GiB  79.83

    1       8       Data/single   1.54GiB   1.00GiB   2.54GiB      17 100.90GiB  46.39

    1       9       Data/single   2.54GiB   1.00GiB   3.54GiB      16  99.90GiB  40.68

    1      10       Data/single   3.54GiB   1.00GiB   4.54GiB       1  71.40GiB  62.97

    1      11       Data/single   4.54GiB   1.00GiB   5.54GiB      33 125.04GiB  26.00

    1      12       Data/single   5.54GiB   1.00GiB   6.54GiB      50 170.91GiB  60.44

    1      13       Data/single   6.54GiB 512.00MiB   7.04GiB      63 189.16GiB  67.34

    1      14       Data/single   7.04GiB   1.00GiB   8.04GiB      51 171.91GiB  70.94
```

- Devid -- the device id

- PNumber -- the number of the chunk on the device (in order)

- Type/profile -- the chunk type and profile

- PStart -- the chunk start on the device

- Length -- the chunk length (same for physical and logical address space)

- PEnd -- the chunk end, effectively PStart + Length

- LNumber -- the number of the chunk, in the logical address space of the whole filesystem

- LStart -- the chunk start in the logical address space of the whole filesystem, as it's a single space it's also called offset

- Usage -- chunk usage, percentage of used data/metadata of the chunk length

The chunks in the output can be sorted by one or more sorting criteria, evaluated as specified, in the ascending order. By default the chunks are sorted by devid and pstart, this is most convenient for single device filesystems.

On multi-device filesystems it's up to the user what is preferred as the layout of chunks on e.g. striped profiles (RAID0 etc) cannot be easily represented. A logical view with corresponding underlying structure would be better, but sorting by lstart,devid at least groups devices of the given logical range. Can be also combined with usage.

This output can provide information for balance filters.

Options

--sort MODE

sort by a column (ascending): MODE is a coma separated list of:

devid - by device id (default, with pstart) pstart - physical start (relative to the beginning of the device)

lstart - logical offset (in the logical address space)

usage - by chunk usage (percentage)

length - by chunk length

--raw

raw numbers in bytes, without the B suffix

--human-readable

print human friendly numbers, base 1024, this is the default

--iec

select the 1024 base for the following options, according to the IEC standard

--si

select the 1000 base for the following options, according to the SI standard

--kbytes

show sizes in KiB, or kB with --si

--mbytes

show sizes in MiB, or MB with --si

--gbytes

show sizes in GiB, or GB with --si

--tbytes

show sizes in TiB, or TB with --si

map-swapfile [options] <file>

(needs root privileges) Find device-specific physical offset of file that can be used for hibernation. Also verify that the file is suitable as a swapfile. See also command btrfs filesystem mkswapfile and the Swapfile feature description.

NOTE:

Do not use filefrag or FIEMAP ioctl values reported as physical, this is different due to internal filesystem mappings. The hibernation expects offset relative to the physical block device.

Options

-r|--resume-offset

print only the value suitable as resume offset for file /sys/power/resume_offset

min-dev-size [options] <path>

(needs root privileges) return the minimum size the device can be shrunk to, without performing any resize operation, this may be useful before executing the actual resize operation

Options

--id <id>

specify the device id to query, default is 1 if this option is not used

rootid <path>

for a given file or directory, return the containing tree root id, but for a subvolume itself return its own tree id (i.e. subvol id) NOTE:

The result is undefined for the so-called empty subvolumes (identified by inode number 2), but such a subvolume does not contain any files anyway

subvolid-resolve <subvolid> <path>

(needs root privileges) resolve the absolute path of the subvolume id subvolid

tree-stats [options] <device>

(needs root privileges) Print sizes and statistics of trees. This takes a device as an argument and not a mount point unlike other commands.

NOTE:

In case the the filesystem is still mounted it's possible to run the command but the results may be inaccurate or various errors may be printed in case there are ongoing writes to the filesystem. A warning is printed in such case.

Options

-b|--raw

raw numbers in bytes, without the B suffix

-t <treeid>

Print stats only for the given treeid.

--human-readable

print human friendly numbers, base 1024, this is the default

--iec

select the 1024 base for the following options, according to the IEC standard

--si

select the 1000 base for the following options, according to the SI standard

--kbytes

show sizes in KiB, or kB with --si

--mbytes

show sizes in MiB, or MB with --si

--gbytes

show sizes in GiB, or GB with --si

--tbytes

show sizes in TiB, or TB with --si

## EXIT STATUS
btrfs inspect-internal returns a zero exit status if it succeeds. Non zero is returned in case of failure.

## AVAILABILITY
btrfs is part of btrfs-progs. Please refer to the documentation at https://btrfs.readthedocs.io.

## SEE ALSO
mkfs.btrfs(8)


btrfs-map-logical

title: btrfs-map-logical(8)

text:
# btrfs-map-logical(8)

## NAME
btrfs-map-logical - map btrfs logical extent to physical extent

## SYNOPSIS
btrfs-map-logical <options> <device>

## DESCRIPTION
btrfs-map-logical can be used to find out what the physical offsets are on the mirrors, the result is dumped to stdout by default.

Mainly used for debug purpose.

## OPTIONS
-l|--logical <logical_num>

Logical extent to map.

-c|--copy <copy>

Copy of the extent to read(usually 1 or 2).

-o|--output <filename>

Output file to hold the extent.

-b|--bytes <bytes>

Number of bytes to read.

## EXIT STATUS
btrfs-map-logical will return 0 if no error happened. If any problems happened, 1 will be returned.

## SEE ALSO
mkfs.btrfs(8)


btrfs-property

title: btrfs-property(8)

text:
# btrfs-property(8)

## NAME
btrfs-property - get/set/list properties for given filesystem object

## SYNOPSIS
btrfs property <subcommand> <args>

## DESCRIPTION
btrfs property is used to get/set/list property for given filesystem object. The object can be an inode (file or directory), subvolume or the whole filesystem.

btrfs property provides an unified and user-friendly method to tune different btrfs properties instead of using the traditional method like chattr(1) or lsattr(1).

### Object types
A property might apply to several object types so in some cases it's necessary to specify that explicitly, however it's not needed in the most common case of files and directories.

The subcommands take parameter -t, use first letter as a shortcut (f/s/d/i) of the type:

- filesystem

- subvolume

- device

- inode (file or directory)

### Inode properties
compression

compression algorithm set for an inode (it's not possible to set the compression level this way), possible values:

- lzo

- zlib

- zstd

- no or none - disable compression (equivalent to chattr +m)

- "" (empty string) - set the default value

NOTE:

This has changed in version 5.18 of btrfs-progs and requires kernel 5.14 or newer to work.

### Subvolume properties
ro

read-only flag of subvolume: true or false. Please also see section SUBVOLUME FLAGS in btrfs-subvolume(8) for possible implications regarding incremental send.

### Filesystem properties
label

label of the filesystem. For an unmounted filesystem, provide a path to a block device as object. For a mounted filesystem, specify a mount point.

## SUBCOMMAND
get [-t <type>] <object> [<name>]

Read value of a property name of btrfs object of given type, empty name will read all of them

list [-t <type>] <object>

List available properties with their descriptions for the given object.

set [-f] [-t <type>] <object> <name> <value>

Set value of property name on a given btrfs object. Options

-f

Force the change. Changing some properties may involve safety checks or additional changes that depend on the properties semantics.

## EXAMPLES
Set compression on a file:

```
$ touch file1
$ btrfs prop get file1
[ empty output ]
$ btrfs prop set file1 compression zstd
$ btrfs prop get file1
compression=zstd
```

Make a writeable subvolume read-only:

```
$ btrfs subvol create subvol1
[ fill subvol1 with data ]
$ btrfs prop get subvol1
ro=false
$ btrfs prop set subvol1 ro true
ro=true
```

## EXIT STATUS
btrfs property returns a zero exit status if it succeeds. Non zero is returned in case of failure.

## AVAILABILITY
btrfs is part of btrfs-progs. Please refer to the documentation at https://btrfs.readthedocs.io.

## SEE ALSO
mkfs.btrfs(8), lsattr(1), chattr(1)


btrfs-qgroup

title: btrfs-qgroup(8)

text:
# btrfs-qgroup(8)

## NAME
btrfs-qgroup - control the quota group of a btrfs filesystem

## SYNOPSIS
btrfs qgroup <subcommand> <args>

## DESCRIPTION
btrfs qgroup is used to control quota group (qgroup) of a btrfs filesystem.

NOTE:

To use qgroup you need to enable quota first using btrfs quota enable command.

WARNING:

Qgroup is not stable yet and will impact performance in current mainline kernel (v4.14).

## QGROUP
Quota groups or qgroup in btrfs make a tree hierarchy, the leaf qgroups are attached to subvolumes. The size limits are set per qgroup and apply when any limit is reached in tree that contains a given subvolume.

The limits are separated between shared and exclusive and reflect the extent ownership. For example a fresh snapshot shares almost all the blocks with the original subvolume, new writes to either subvolume will raise towards the exclusive limit.

NOTE:

Qgroup limit only works when qgroup is in a consistent state. If some workload marks qgroup inconsistent (like assigning a qgroup to another qgroup), the limit will no longer work until the inconsistent flag is cleared by btrfs quota rescan.

The qgroup identifiers conform to level/id where level 0 is reserved to the qgroups associated with subvolumes. Such qgroups are created automatically.

The qgroup hierarchy is built by commands create and assign.

NOTE:

If the qgroup of a subvolume is destroyed, quota about the subvolume will not be functional until qgroup 0/<subvolume id> is created again.

## SUBCOMMAND
assign [options] <src> <dst> <path>

Assign qgroup src as the child qgroup of dst in the btrfs filesystem identified by path. Options

--rescan

(default since: 4.19) Automatically schedule quota rescan if the new qgroup assignment would lead to quota inconsistency. See QUOTA RESCAN for more information.

--no-rescan

Explicitly ask not to do a rescan, even if the assignment will make the quotas inconsistent. This may be useful for repeated calls where the rescan would add unnecessary overhead.

create <qgroupid> <path>

Create a subvolume quota group. For the 0/<subvolume id> qgroup, a qgroup can be created even before the subvolume is created.

destroy <qgroupid> <path>

Destroy a qgroup. If a qgroup is not isolated, meaning it is a parent or child qgroup, then it can only be destroyed after the relationship is removed.

clear-stale <path>

Clear all stale qgroups whose subvolume does not exist anymore, this is the level 0 qgroup like 0/subvolid. Higher level qgroups are not deleted even if they don't have any child qgroups.

limit [options] <size>|none [<qgroupid>] <path>

Limit the size of a qgroup to size or no limit in the btrfs filesystem identified by path. If qgroupid is not given, qgroup of the subvolume identified by path is used if possible.

Options

-c

limit amount of data after compression. This is the default, it is currently not possible to turn off this option.

-e

limit space exclusively assigned to this qgroup.

remove <src> <dst> <path>

Remove the relationship between child qgroup src and parent qgroup dst in the btrfs filesystem identified by path. Options

--rescan

(default since: 4.19) Automatically schedule quota rescan if the removed qgroup relation would lead to quota inconsistency. See QUOTA RESCAN for more information.

--no-rescan

Explicitly ask not to do a rescan, even if the removal will make the quotas inconsistent. This may be useful for repeated calls where the rescan would add unnecessary overhead.

show [options] <path>

Show all qgroups in the btrfs filesystem identified by <path>. Options

-p

print parent qgroup id.

-c

print child qgroup id.

-r

print limit of referenced size of qgroup.

-e

print limit of exclusive size of qgroup.

-F

list all qgroups which impact the given path(include ancestral qgroups)

-f

list all qgroups which impact the given path(exclude ancestral qgroups)

--raw

raw numbers in bytes, without the B suffix.

--human-readable

print human friendly numbers, base 1024, this is the default

--iec

select the 1024 base for the following options, according to the IEC standard.

--si

select the 1000 base for the following options, according to the SI standard.

--kbytes

show sizes in KiB, or kB with --si.

--mbytes

show sizes in MiB, or MB with --si.

--gbytes

show sizes in GiB, or GB with --si.

--tbytes

show sizes in TiB, or TB with --si.

--sort=[+/-]<attr>[,[+/-]<attr>]...

list qgroups in order of <attr>. <attr> can be one or more of qgroupid,rfer,excl,max_rfer,max_excl.

Prefix + means ascending order and - means descending order of attr. If no prefix is given, use ascending order by default.

If multiple attr values are given, use comma to separate.

--sync

To retrieve information after updating the state of qgroups, force sync of the filesystem identified by path before getting information.

## SPECIAL PATHS
For btrfs qgroup show subcommand, the path column may has some special strings:

<toplevel>

The toplevel subvolume

<under deletion>

The subvolume has been deleted (it's directory removed), but the subvolume metadata not not yet fully cleaned.

<squota space holder>

For simple quota mode only. By its design, a fully deleted subvolume may still have accounting on it, so even the subvolume is gone, the numbers are still here for future accounting.

<stale>

The qgroup has no corresponding subvolume anymore, and the qgroup can be cleaned up under most cases. The only exception is that, if the qgroup numbers are inconsistent and the qgroup numbers are not all zeros, some older kernels may refuse to delete such qgroups until a full rescan.

## QUOTA RESCAN
The rescan reads all extent sharing metadata and updates the respective qgroups accordingly.

The information consists of bytes owned exclusively (excl) or shared/referred to (rfer). There's no explicit information about which extents are shared or owned exclusively. This means when qgroup relationship changes, extent owners change and qgroup numbers are no longer consistent unless we do a full rescan.

However there are cases where we can avoid a full rescan, if a subvolume whose rfer number equals its excl number, which means all bytes are exclusively owned, then assigning/removing this subvolume only needs to add/subtract rfer number from its parent qgroup. This can speed up the rescan.

## EXAMPLES

### Make a parent group that has two quota group children
Given the following filesystem mounted at /mnt/my-vault

```
Label: none  uuid: 60d2ab3b-941a-4f22-8d1a-315f329797b2

       Total devices 1 FS bytes used 128.00KiB

       devid    1 size 5.00GiB used 536.00MiB path /dev/vdb
```

Enable quota and create subvolumes. Check subvolume ids.

```
$ cd /mnt/my-vault
$ btrfs quota enable .
$ btrfs subvolume create a
$ btrfs subvolume create b
$ btrfs subvolume list .
ID 261 gen 61 top level 5 path a
ID 262 gen 62 top level 5 path b
```

Create qgroup and set limit to 10MiB.

```
$ btrfs qgroup create 1/100 .
$ btrfs qgroup limit 10M 1/100 .
$ btrfs qgroup assign 0/261 1/100 .
$ btrfs qgroup assign 0/262 1/100 .
```

And check qgroups.

```
$ btrfs qgroup show .
qgroupid         rfer         excl
--------         ----         ----
0/5          16.00KiB     16.00KiB
0/261        16.00KiB     16.00KiB
0/262        16.00KiB     16.00KiB
1/100        32.00KiB     32.00KiB
```

## EXIT STATUS
btrfs qgroup returns a zero exit status if it succeeds. Non zero is returned in case of failure.

## AVAILABILITY
btrfs is part of btrfs-progs. Please refer to the documentation at https://btrfs.readthedocs.io.

## SEE ALSO
btrfs-quota(8), btrfs-subvolume(8), mkfs.btrfs(8)


btrfs-quota

title: btrfs-quota(8)

text:
# btrfs-quota(8)

## NAME
btrfs-quota - control the global quota status of a btrfs filesystem

## SYNOPSIS
btrfs quota <subcommand> <args>

## DESCRIPTION
The commands under btrfs quota are used to affect the global status of quotas of a btrfs filesystem. The quota groups (qgroups) are managed by the subcommand btrfs-qgroup(8).

NOTE:

Qgroups are different than the traditional user quotas and designed to track shared and exclusive data per-subvolume. Please refer to the section HIERARCHICAL QUOTA GROUP CONCEPTS for a detailed description.

### PERFORMANCE IMPLICATIONS
When quotas are activated, they affect all extent processing, which takes a performance hit. Activation of qgroups is not recommended unless the user intends to actually use them.

### STABILITY STATUS
The qgroup implementation has turned out to be quite difficult as it affects the core of the filesystem operation. Qgroup users have hit various corner cases over time, such as incorrect accounting or system instability. The situation is gradually improving and issues found and fixed.

## HIERARCHICAL QUOTA GROUP CONCEPTS
The concept of quota has a long-standing tradition in the Unix world. Ever since computers allow multiple users to work simultaneously in one filesystem, there is the need to prevent one user from using up the entire space. Every user should get his fair share of the available resources.

In case of files, the solution is quite straightforward. Each file has an owner recorded along with it, and it has a size. Traditional quota just restricts the total size of all files that are owned by a user. The concept is quite flexible: if a user hits his quota limit, the administrator can raise it on the fly.

On the other hand, the traditional approach has only a poor solution to restrict directories. At installation time, the harddisk can be partitioned so that every directory (e.g. /usr, /var, ...) that needs a limit gets its own partition. The obvious problem is that those limits cannot be changed without a reinstallation. The btrfs subvolume feature builds a bridge. Subvolumes correspond in many ways to partitions, as every subvolume looks like its own filesystem. With subvolume quota, it is now possible to restrict each subvolume like a partition, but keep the flexibility of quota. The space for each subvolume can be expanded or restricted on the fly.

As subvolumes are the basis for snapshots, interesting questions arise as to how to account used space in the presence of snapshots. If you have a file shared between a subvolume and a snapshot, whom to account the file to? The creator? Both? What if the file gets modified in the snapshot, should only these changes be accounted to it? But wait, both the snapshot and the subvolume belong to the same user home. I just want to limit the total space used by both! But somebody else might not want to charge the snapshots to the users.

Btrfs subvolume quota solves these problems by introducing groups of subvolumes and let the user put limits on them. It is even possible to have groups of groups. In the following, we refer to them as qgroups.

Each qgroup primarily tracks two numbers, the amount of total referenced space and the amount of exclusively referenced space.

referenced

space is the amount of data that can be reached from any of the subvolumes contained in the qgroup, while

exclusive

is the amount of data where all references to this data can be reached from within this qgroup.

### Subvolume quota groups
The basic notion of the Subvolume Quota feature is the quota group, short qgroup. Qgroups are notated as level/id, e.g. the qgroup 3/2 is a qgroup of level 3. For level 0, the leading 0/ can be omitted. Qgroups of level 0 get created automatically when a subvolume/snapshot gets created. The ID of the qgroup corresponds to the ID of the subvolume, so 0/5 is the qgroup for the root subvolume. For the btrfs qgroup command, the path to the subvolume can also be used instead of 0/ID. For all higher levels, the ID can be chosen freely.

Each qgroup can contain a set of lower level qgroups, thus creating a hierarchy of qgroups. Figure 1 shows an example qgroup tree.

```
                          +---+

                          |2/1|

                          +---+

                         /     \

                   +---+/       \+---+

                   |1/1|         |1/2|

                   +---+         +---+

                  /     \       /     \

            +---+/       \+---+/       \+---+
qgroups     |0/1|         |0/2|         |0/3|

            +-+-+         +---+         +---+

              |          /     \       /     \

              |         /       \     /       \

              |        /         \   /         \
extents       1       2            3            4
Figure 1: Sample qgroup hierarchy
```

At the bottom, some extents are depicted showing which qgroups reference which extents. It is important to understand the notion of referenced vs exclusive. In the example, qgroup 0/2 references extents 2 and 3, while 1/2 references extents 2-4, 2/1 references all extents.

On the other hand, extent 1 is exclusive to 0/1, extent 2 is exclusive to 0/2, while extent 3 is neither exclusive to 0/2 nor to 0/3. But because both references can be reached from 1/2, extent 3 is exclusive to 1/2. All extents are exclusive to 2/1.

So exclusive does not mean there is no other way to reach the extent, but it does mean that if you delete all subvolumes contained in a qgroup, the extent will get deleted.

Exclusive of a qgroup conveys the useful information how much space will be freed in case all subvolumes of the qgroup get deleted.

All data extents are accounted this way. Metadata that belongs to a specific subvolume (i.e. its filesystem tree) is also accounted. Checksums and extent allocation information are not accounted.

In turn, the referenced count of a qgroup can be limited. All writes beyond this limit will lead to a 'Quota Exceeded' error.

### Inheritance
Things get a bit more complicated when new subvolumes or snapshots are created. The case of (empty) subvolumes is still quite easy. If a subvolume should be part of a qgroup, it has to be added to the qgroup at creation time. To add it at a later time, it would be necessary to at least rescan the full subvolume for a proper accounting.

Creation of a snapshot is the hard case. Obviously, the snapshot will reference the exact amount of space as its source, and both source and destination now have an exclusive count of 0 (the filesystem nodesize to be precise, as the roots of the trees are not shared). But what about qgroups of higher levels? If the qgroup contains both the source and the destination, nothing changes. If the qgroup contains only the source, it might lose some exclusive.

But how much? The tempting answer is, subtract all exclusive of the source from the qgroup, but that is wrong, or at least not enough. There could have been an extent that is referenced from the source and another subvolume from that qgroup. This extent would have been exclusive to the qgroup, but not to the source subvolume. With the creation of the snapshot, the qgroup would also lose this extent from its exclusive set.

So how can this problem be solved? In the instant the snapshot gets created, we already have to know the correct exclusive count. We need to have a second qgroup that contains all the subvolumes as the first qgroup, except the subvolume we want to snapshot. The moment we create the snapshot, the exclusive count from the second qgroup needs to be copied to the first qgroup, as it represents the correct value. The second qgroup is called a tracking qgroup. It is only there in case a snapshot is needed.

### Use cases
Below are some use cases that do not mean to be extensive. You can find your own way how to integrate qgroups.

### Single-user machine
Replacement for partitions. The simplest use case is to use qgroups as simple replacement for partitions. Btrfs takes the disk as a whole, and /, /usr, /var, etc. are created as subvolumes. As each subvolume gets it own qgroup automatically, they can simply be restricted. No hierarchy is needed for that.

Track usage of snapshots. When a snapshot is taken, a qgroup for it will automatically be created with the correct values. Referenced will show how much is in it, possibly shared with other subvolumes. Exclusive will be the amount of space that gets freed when the subvolume is deleted.

### Multi-user machine
Restricting homes. When you have several users on a machine, with home directories probably under /home, you might want to restrict /home as a whole, while restricting every user to an individual limit as well. This is easily accomplished by creating a qgroup for /home , e.g. 1/1, and assigning all user subvolumes to it. Restricting this qgroup will limit /home, while every user subvolume can get its own (lower) limit.

Accounting snapshots to the user. Let's say the user is allowed to create snapshots via some mechanism. It would only be fair to account space used by the snapshots to the user. This does not mean the user doubles his usage as soon as he takes a snapshot. Of course, files that are present in his home and the snapshot should only be accounted once. This can be accomplished by creating a qgroup for each user, say 1/UID. The user home and all snapshots are assigned to this qgroup. Limiting it will extend the limit to all snapshots, counting files only once. To limit /home as a whole, a higher level group 2/1 replacing 1/1 from the previous example is needed, with all user qgroups assigned to it.

Do not account snapshots. On the other hand, when the snapshots get created automatically, the user has no chance to control them, so the space used by them should not be accounted to him. This is already the case when creating snapshots in the example from the previous section.

Snapshots for backup purposes. This scenario is a mixture of the previous two. The user can create snapshots, but some snapshots for backup purposes are being created by the system. The user's snapshots should be accounted to the user, not the system. The solution is similar to the one from section Accounting snapshots to the user, but do not assign system snapshots to user's qgroup.

### Simple quotas (squota)
As detailed in this document, qgroups can handle many complex extent sharing and unsharing scenarios while maintaining an accurate count of exclusive and shared usage. However, this flexibility comes at a cost: many of the computations are global, in the sense that we must count up the number of trees referring to an extent after its references change. This can slow down transaction commits and lead to unacceptable latencies, especially in cases where snapshots scale up.

To work around this limitation of qgroups, btrfs also supports a second set of quota semantics: simple quotas or squotas. Squotas fully share the qgroups API and hierarchical model, but do not track shared vs. exclusive usage. Instead, they account all extents to the subvolume that first allocated it. With a bit of new bookkeeping, this allows all accounting decisions to be local to the allocation or freeing operation that deals with the extents themselves, and fully avoids the complex and costly back-reference resolutions.

Example

To illustrate the difference between squotas and qgroups, consider the following basic example assuming a nodesize of 16KiB.

1.

create subvolume 256

2.

rack up 1GiB of data and metadata usage in 256

3.

snapshot 256, creating subvolume 257

4.

COW 512MiB of the data and metadata in 257

5.

delete everything in 256

At each step, qgroups would have the following accounting:

1.

0/256: 16KiB excl 0 shared

2.

0/256: 1GiB excl 0 shared

3.

0/256: 0 excl 1GiB shared; 0/257: 0 excl 1GiB shared

4.

0/256: 512MiB excl 512MiB shared; 0/257: 512MiB excl 512MiB shared

5.

0/256: 16KiB excl 0 shared; 0/257: 1GiB excl 0 shared

Whereas under squotas, the accounting would look like:

1.

0/256: 16KiB excl 16KiB shared

2.

0/256: 1GiB excl 1GiB shared

3.

0/256: 1GiB excl 1GiB shared; 0/257: 16KiB excl 16KiB shared

4.

0/256: 1GiB excl 1GiB shared; 0/257: 512MiB excl 512MiB shared

5.

0/256: 512MiB excl 512MiB shared; 0/257: 512MiB excl 512MiB shared

Note that since the original snapshotted 512MiB are still referenced by 257, they cannot be freed from 256, even after 256 is emptied, or even deleted.

Summary

If you want some of power and flexibility of quotas for tracking and limiting subvolume usage, but want to avoid the performance penalty of accurately tracking extent ownership life cycles, then squotas can be a useful option.

Furthermore, squotas is targeted at use cases where the original extent is immutable, like image snapshotting for container startup, in which case we avoid these awkward scenarios where a subvolume is empty or deleted but still has significant extents accounted to it. However, as long as you are aware of the accounting semantics, they can handle mutable original extents.

## SUBCOMMAND
disable <path>

Disable subvolume quota support for a filesystem.

enable [options] <path>

Enable subvolume quota support for a filesystem. At this point it's possible the two modes of accounting. The full means that extent ownership by subvolumes will be tracked all the time, simple will account everything to the first owner. See the section for more details. Options

-s|--simple

use simple quotas (squotas) instead of full qgroup accounting

rescan [options] <path>

Trash all qgroup numbers and scan the metadata again with the current config. Options

-s|--status

show status of a running rescan operation.

-w|--wait

start rescan and wait for it to finish (can be already in progress)

-W|--wait-norescan

wait for rescan to finish without starting it

## EXIT STATUS
btrfs quota returns a zero exit status if it succeeds. Non zero is returned in case of failure.

## AVAILABILITY
btrfs is part of btrfs-progs. Please refer to the documentation at https://btrfs.readthedocs.io.

## SEE ALSO
btrfs-qgroup(8), btrfs-subvolume(8), mkfs.btrfs(8)


btrfs-receive

title: btrfs-receive(8)

summary: receive subvolumes from send stream

text:
# btrfs-receive(8)

## NAME
btrfs-receive - receive subvolumes from send stream

## SYNOPSIS
btrfs receive [options] <path>

or

btrfs receive --dump [options]

## DESCRIPTION
Receive a stream of changes and replicate one or more subvolumes that were previously generated by btrfs send. The received subvolumes are stored to path, unless --dump option is given.

If --dump option is specified, btrfs receive will only do the validation of the stream, and print the stream metadata, one operation per line.

btrfs receive will fail in the following cases:

1.

receiving subvolume already exists

2.

previously received subvolume has been changed after it was received

3.

default subvolume has changed or you didn't mount the filesystem at the toplevel subvolume

A subvolume is made read-only after the receiving process finishes successfully (see BUGS below).

Options

-f <FILE>

read the stream from FILE instead of stdin,

-C|--chroot

confine the process to path using chroot(1)

-e

terminate after receiving an end cmd marker in the stream. Without this option the receiver side terminates only in case of an error on end of file.

-E|--max-errors <NERR>

terminate as soon as NERR errors occur while stream processing commands from the stream Default value is 1. A value of 0 means no limit.

-m <ROOTMOUNT>

the root mount point of the destination filesystem By default the mount point is searched in :file:/proc/self/mounts`. If /proc is not accessible, e.g. in a chroot environment, use this option to tell us where this filesystem is mounted.

--force-decompress

if the stream contains compressed data (see --compressed-data in btrfs-send(8)), always decompress it instead of writing it with encoded I/O

--dump

dump the stream metadata, one line per operation Does not require the path parameter. The filesystem remains unchanged. Each stream command is on one line in the form of key=value and separated by one or more spaces. Values that contain special characters (like paths or extended attributes) are encoded in C-like way, e.g. '\n' or octal escape sequence like '\NNN' where N is the char value. Same encoding as is used in /proc files.

-q|--quiet

(deprecated) alias for global -q option

-v

(deprecated) alias for global -v option

Global options

-v|--verbose

increase verbosity about performed actions, print details about each operation

-q|--quiet

suppress all messages except errors

## BUGS
btrfs receive sets the subvolume read-only after it completes successfully. However, while the receive is in progress, users who have write access to files or directories in the receiving path can add, remove, or modify files, in which case the resulting read-only subvolume will not be an exact copy of the sent subvolume.

If the intention is to create an exact copy, the receiving path should be protected from access by users until the receive operation has completed and the subvolume is set to read-only.

Additionally, receive does not currently do a very good job of validating that an incremental send stream actually makes sense, and it is thus possible for a specially crafted send stream to create a subvolume with reflinks to arbitrary files in the same filesystem. Because of this, users are advised to not use btrfs receive on send streams from untrusted sources, and to protect trusted streams when sending them across untrusted networks.

## EXIT STATUS
btrfs receive returns a zero exit status if it succeeds. Non zero is returned in case of failure.

## AVAILABILITY
btrfs is part of btrfs-progs. Please refer to the documentation at https://btrfs.readthedocs.io.

## SEE ALSO
btrfs-send(8), mkfs.btrfs(8)


btrfs-replace

title: btrfs-replace(8)

text:
# btrfs-replace(8)

## NAME
btrfs-replace - replace devices managed by btrfs with other device

## SYNOPSIS
btrfs replace <subcommand> <args>

## DESCRIPTION
btrfs replace is used to replace btrfs managed devices with other device.

## SUBCOMMAND
cancel <mount_point>

Cancel a running device replace operation.

start [options] <srcdev>|<devid> <targetdev> <path>

Replace device of a btrfs filesystem. On a live filesystem, duplicate the data to the target device which is currently stored on the source device. If the source device is not available anymore, or if the -r option is set, the data is built only using the RAID redundancy mechanisms. After completion of the operation, the source device is removed from the filesystem. If the srcdev is a numerical value, it is assumed to be the device id of the filesystem which is mounted at path, otherwise it is the path to the source device. If the source device is disconnected, from the system, you have to use the devid parameter format. The targetdev needs to be same size or larger than the srcdev.

NOTE:

The filesystem has to be resized to fully take advantage of a larger target device; this can be achieved with btrfs filesystem resize <devid>:max /path

Options

-r

only read from srcdev if no other zero-defect mirror exists. (enable this if your drive has lots of read errors, the access would be very slow)

-f

force using and overwriting targetdev even if it looks like it contains a valid btrfs filesystem. A valid filesystem is assumed if a btrfs superblock is found which contains a correct checksum. Devices that are currently mounted are never allowed to be used as the targetdev.

-B

no background replace.

--enqueue

wait if there's another exclusive operation running, otherwise continue

-K|--nodiscard

Do not perform whole device TRIM operation on devices that are capable of that. This does not affect discard/trim operation when the filesystem is mounted. Please see the mount option discard for that in btrfs(5).

status [-1] <mount_point>

Print status and progress information of a running device replace operation. Options

-1

print once instead of print continuously until the replace operation finishes (or is cancelled)

## EXAMPLES

### Replacing an online drive with a bigger one
Given the following filesystem mounted at /mnt/my-vault

```
Label: 'MyVault'  uuid: ae20903e-b72d-49ba-b944-901fc6d888a1

        Total devices 2 FS bytes used 1TiB

        devid    1 size 1TiB used 500.00GiB path /dev/sda

        devid    2 size 1TiB used 500.00GiB path /dev/sdb
```

In order to replace /dev/sda (devid 1) with a bigger drive located at /dev/sdc you would run the following:

```
btrfs replace start 1 /dev/sdc /mnt/my-vault/
```

You can monitor progress via:

```
btrfs replace status /mnt/my-vault/
```

After the replacement is complete, as per the docs at btrfs-filesystem(8) in order to use the entire storage space of the new drive you need to run:

```
btrfs filesystem resize 1:max /mnt/my-vault/
```

## EXIT STATUS
btrfs replace returns a zero exit status if it succeeds. Non zero is returned in case of failure.

## AVAILABILITY
btrfs is part of btrfs-progs. Please refer to the documentation at https://btrfs.readthedocs.io.

## SEE ALSO
btrfs-device(8), btrfs-filesystem(8), mkfs.btrfs(8)


btrfs-rescue

title: btrfs-rescue(8)

summary: recover a damaged btrfs filesystem

text:
# btrfs-rescue(8)

## NAME
btrfs-rescue - recover a damaged btrfs filesystem

## SYNOPSIS
btrfs rescue <subcommand> <args>

## DESCRIPTION
btrfs rescue is used to try to recover a damaged btrfs filesystem.

## SUBCOMMAND
chunk-recover [options] <device>

Recover the chunk tree by scanning the devices Options

-y

assume an answer of yes to all questions.

-h

help.

-v

(deprecated) alias for global -v option

NOTE:

Since chunk-recover will scan the whole device, it will be very slow especially executed on a large device.

fix-device-size <device>

fix device size and super block total bytes values that do not match Kernel 4.11 starts to check the device size more strictly and this might mismatch the stored value of total bytes. See the exact error message below. Newer kernel will refuse to mount the filesystem where the values do not match. This error is not fatal and can be fixed. This command will fix the device size values if possible.

```
BTRFS error (device sdb): super_total_bytes 92017859088384 mismatch with fs_devices total_rw_bytes 92017859094528
```

The mismatch may also exhibit as a kernel warning:

```
WARNING: CPU: 3 PID: 439 at fs/btrfs/ctree.h:1559 btrfs_update_device+0x1c5/0x1d0 [btrfs]
```

clear-ino-cache <device>

Remove leftover items pertaining to the deprecated inode cache feature. The inode cache feature (enabled by mount option "inode_cache") has been completely removed in 5.11 kernel.

clear-space-cache <v1|v2> <device>

Completely remove the on-disk data of free space cache of given version. Especially for v1 free space cache, clear_cache mount option would only remove the cache for updated block groups, the remaining would not be removed. Thus this command is provided to manually clear the free space cache.

clear-uuid-tree <device>

Clear the UUID tree, so that kernel can regenerate it at next read-write mount. Since kernel v4.16 there are more sanity check performed, and sometimes non-critical trees like UUID tree can cause problems and reject the mount. In such case, clearing UUID tree may make the filesystem to be mountable again without much risk as it's built from other trees. See also mount option rescan_uuid_tree (in btrfs-man5).

super-recover [options] <device>

Recover bad superblocks from good copies. Options

-y

assume an answer of yes to all questions.

-v

(deprecated) alias for global -v option

zero-log <device>

clear the filesystem log tree This command will clear the filesystem log tree. This may fix a specific set of problem when the filesystem mount fails due to the log replay. See below for sample stack traces that may show up in system log.

The common case where this happens was fixed a long time ago, so it is unlikely that you will see this particular problem, but the command is kept around.

NOTE:

Clearing the log may lead to loss of changes that were made since the last transaction commit. This may be up to 30 seconds (default commit period) or less if the commit was implied by other filesystem activity.

One can determine whether zero-log is needed according to the kernel backtrace:

```
? replay_one_dir_item+0xb5/0xb5 [btrfs]
? walk_log_tree+0x9c/0x19d [btrfs]
? btrfs_read_fs_root_no_radix+0x169/0x1a1 [btrfs]
? btrfs_recover_log_trees+0x195/0x29c [btrfs]
? replay_one_dir_item+0xb5/0xb5 [btrfs]
? btree_read_extent_buffer_pages+0x76/0xbc [btrfs]
? open_ctree+0xff6/0x132c [btrfs]
```

If the errors are like above, then zero-log should be used to clear the log and the filesystem may be mounted normally again. The keywords to look for are 'open_ctree' which says that it's during mount and function names that contain replay, recover or log_tree.

## EXIT STATUS
btrfs rescue returns a zero exit status if it succeeds. Non zero is returned in case of failure.

## AVAILABILITY
btrfs is part of btrfs-progs. Please refer to the documentation at https://btrfs.readthedocs.io.

## SEE ALSO
btrfs-check(8), btrfs-scrub(8), mkfs.btrfs(8)


btrfs-restore

title: btrfs-restore(8)

text:
# btrfs-restore(8)

## NAME
btrfs-restore - try to restore files from a damaged filesystem image

## SYNOPSIS
btrfs restore [options] <device> <path> | -l <device>

## DESCRIPTION
btrfs restore is used to try to salvage files from a damaged filesystem and restore them into path or just list the subvolume tree roots. The filesystem image is not modified.

If the filesystem is damaged and cannot be repaired by the other tools (btrfs-check(8) or btrfs-rescue(8)), btrfs restore could be used to retrieve file data, as far as the metadata are readable. The checks done by restore are less strict and the process is usually able to get far enough to retrieve data from the whole filesystem. This comes at a cost that some data might be incomplete or from older versions if they're available.

There are several options to attempt restoration of various file metadata type. You can try a dry run first to see how well the process goes and use further options to extend the set of restored metadata.

For images with damaged tree structures, there are several options to point the process to some spare copy.

## OPTIONS
-s|--snapshots

get also snapshots that are skipped by default

-x|--xattr

get extended attributes

-m|--metadata

restore owner, mode and times for files and directories

-S|--symlinks

restore symbolic links as well as normal files

-i|--ignore-errors

ignore errors during restoration and continue

-o|--overwrite

overwrite directories/files in path, e.g. for repeated runs

-t <bytenr>

use bytenr to read the root tree

-f <bytenr>

only restore files that are under specified subvolume root pointed by bytenr

-u|--super <mirror>

use given superblock mirror identified by <mirror>, it can be 0,1 or 2

-r|--root <rootid>

only restore files that are under a specified subvolume whose objectid is rootid

-d

find directory

-l|--list-roots

list subvolume tree roots, can be used as argument for -r

-D|--dry-run

dry run (only list files that would be recovered)

--path-regex <regex>

restore only filenames matching a regular expression (regex(7)) with a mandatory format ^/(|home(|/username(|/Desktop(|/.*))))$

The format is not very comfortable and restores all files in the directories in the whole path, so this is not useful for restoring single file in a deep hierarchy.

-c

ignore case (--path-regex only)

-v|--verbose

(deprecated) alias for global -v option

Global options

-v|--verbose

be verbose and print what is being restored

## EXIT STATUS
btrfs restore returns a zero exit status if it succeeds. Non zero is returned in case of failure.

## AVAILABILITY
btrfs is part of btrfs-progs. Please refer to the documentation at https://btrfs.readthedocs.io.

## SEE ALSO
btrfs-check(8), btrfs-rescue(8), mkfs.btrfs(8)


btrfs-scrub

title: btrfs-scrub(8)

text:
# btrfs-scrub(8)

## NAME
btrfs-scrub - scrub btrfs filesystem, verify block checksums

## SYNOPSIS
btrfs scrub <subcommand> <args>

## DESCRIPTION
Scrub is a validation pass over all filesystem data and metadata that detects data checksum errors, basic super block errors, basic metadata block header errors, and disk read errors.

Scrub is done on a per-device base, if a device is specified to btrfs scrub start, then only that device will be scrubbed. Although btrfs will also try to read other device to find a good copy, if the mirror on that specified device failed to be read or pass verification.

If a path of btrfs is specified to btrfs scrub start, btrfs will scrub all devices in parallel.

On filesystems that use replicated block group profiles (e.g. RAID1), read-write scrub will also automatically repair any damage by copying verified good data from one of the other replicas.

Such automatic repair is also carried out when reading metadata or data from a read-write mounted filesystem.

WARNING:

As currently implemented, setting the NOCOW file attribute (by chattr +C) on a file implicitly enables NODATASUM. This means that while metadata for these files continues to be validated and corrected by scrub, the actual file data is not. Furthermore, btrfs does not currently mark missing or failed disks as unreliable, so will continue to load-balance reads to potentially damaged replicas. This is not a problem normally because damage is detected by checksum validation, but because NOCOW files are not protected by checksums, btrfs has no idea which mirror is good thus it can return the bad contents to the user space tool.

Detecting and recovering from such failure requires manual intervention.

Notably, systemd sets +C on journals by default, and libvirt ≥ 6.6 sets +C on storage pool directories by default. Other applications or distributions may also set +C to try to improve performance.

NOTE:

Scrub is not a filesystem checker (fsck, btrfs-check(8)). It can only detect filesystem damage using the checksum validation, and it can only repair filesystem damage by copying from other known good replicas. btrfs-check(8) performs more exhaustive checking and can sometimes be used, with expert guidance, to rebuild certain corrupted filesystem structures in the absence of any good replica.

NOTE:

Read-only scrub on a read-write filesystem will cause some writes into the filesystem. This is due to the design limitation to prevent race between marking block group read-only and writing back block group items.

To avoid any writes from scrub, one has to run read-only scrub on read-only filesystem.

The user is supposed to run it manually or via a periodic system service. The recommended period is a month but it could be less. The estimated device bandwidth utilization is about 80% on an idle filesystem.

The scrubbing status is recorded in /var/lib/btrfs/ in textual files named scrub.status.UUID for a filesystem identified by the given UUID. (Progress state is communicated through a named pipe in file scrub.progress.UUID in the same directory.) The status file is updated every 5 seconds. A resumed scrub will continue from the last saved position.

Scrub can be started only on a mounted filesystem, though it's possible to scrub only a selected device. See btrfs scrub start for more.

### Bandwidth and IO limiting
NOTE:

The ionice(1) may not be generally supported by all IO schedulers and the options to btrfs scrub start may not work as expected.

In the past when the CFQ IO scheduler was generally used the ionice(1) syscalls set the priority to idle so the IO would not interfere with regular IO. Since the kernel 5.0 the CFQ is not available.

The IO scheduler known to support that is BFQ, but first read the documentation before using it!

For other commonly used schedulers like mq-deadline it's recommended to use cgroup2 IO controller which could be managed by e.g. systemd (documented in systemd.resource-control). However, starting scrub like that is not yet completely straightforward. The IO controller must know the physical device of the filesystem and create a slice so all processes started from that belong to the same accounting group.

```
$ systemd-run -p "IOReadBandwidthMax=/dev/sdx 10M" btrfs scrub start -B /
```

Since linux 5.14 it's possible to set the per-device bandwidth limits in a BTRFS-specific way using files /sys/fs/btrfs/FSID/devinfo/DEVID/scrub_speed_max. This setting is not persistent, lasts until the filesystem is unmounted. Currently set limits can be displayed by command btrfs scrub limit.

```
$ echo 100m > /sys/fs/btrfs/9b5fd16e-1b64-4f9b-904a-74e74c0bbadc/devinfo/1/scrub_speed_max
$ btrfs scrub limit /
UUID: 9b5fd16e-1b64-4f9b-904a-74e74c0bbadc
Id      Limit      Path
--  ---------  --------

 1  100.00MiB  /dev/sdx
```

## SUBCOMMAND
cancel <path>|<device>

If a scrub is running on the filesystem identified by path or device, cancel it. If a device is specified, the corresponding filesystem is found and btrfs scrub cancel behaves as if it was called on that filesystem. The progress is saved in the status file so btrfs scrub resume can continue from the last position.

limit [options] <path>

Show or set scrub limits on devices of the given filesystem. Options

-d|--devid DEVID

select the device by DEVID to apply the limit

-l|--limit SIZE

set the limit of the device to SIZE (size units with suffix), or 0 to reset to unlimited

-a|--all

apply the limit to all devices

--raw

print all numbers raw values in bytes without the B suffix

--human-readable

print human friendly numbers, base 1024, this is the default

--iec

select the 1024 base for the following options, according to the IEC standard

--si

select the 1000 base for the following options, according to the SI standard

--kbytes

show sizes in KiB, or kB with --si

--mbytes

show sizes in MiB, or MB with --si

--gbytes

show sizes in GiB, or GB with --si

--tbytes

show sizes in TiB, or TB with --si

resume [-BdqrR] <path>|<device>

Resume a cancelled or interrupted scrub on the filesystem identified by path or on a given device. The starting point is read from the status file if it exists. This does not start a new scrub if the last scrub finished successfully.

Options

see scrub start.

start [options] <path>|<device>

Start a scrub on all devices of the mounted filesystem identified by path or on a single device. If a scrub is already running, the new one will not start. A device of an unmounted filesystem cannot be scrubbed this way. Without options, scrub is started as a background process. The automatic repairs of damaged copies are performed by default for block group profiles with redundancy. No-repair can be enabled by option -r.

Options

-B

do not background and print scrub statistics when finished

-d

print separate statistics for each device of the filesystem (-B only) at the end

-r

run in read-only mode, do not attempt to correct anything, can be run on a read-only filesystem Note that a read-only scrub on a read-write filesystem can still cause writes into the filesystem due to some internal limitations. Only a read-only scrub on a read-only filesystem can avoid writes from scrub.

-R

raw print mode, print full data instead of summary

--limit <limit>

set the scrub throughput limit for each device. If the scrub is for the whole fs, it's the same as btrfs scrub limit -a -l <value>. If the scrub is for a single device, it's the same as btrfs scrub limit -d <devid> -l <value>.

The value is bytes per second, and accepts the usual KMGT prefixes. After the scrub is finished, the throughput limit will be reset to the old value of each device.

-f

force starting new scrub even if a scrub is already running, this can useful when scrub status file is damaged and reports a running scrub although it is not, but should not normally be necessary

Deprecated options

-c <ioprio_class>

set IO priority class (see ionice(1) manual page) if the IO scheduler configured for the device supports ionice. This is only supported by BFQ or Kyber but is not supported by mq-deadline. Please read the section about IO limiting.

-n <ioprio_classdata>

set IO priority classdata (see ionice(1) manpage)

-q

(deprecated) alias for global -q option

status [options] <path>|<device>

Show status of a running scrub for the filesystem identified by path or for the specified device. If no scrub is running, show statistics of the last finished or cancelled scrub for that filesystem or device.

Options

-d

print separate statistics for each device of the filesystem

-R

print all raw statistics without postprocessing as returned by the status ioctl

--raw

print all numbers raw values in bytes without the B suffix

--human-readable

print human friendly numbers, base 1024, this is the default

--iec

select the 1024 base for the following options, according to the IEC standard

--si

select the 1000 base for the following options, according to the SI standard

--kbytes

show sizes in KiB, or kB with --si

--mbytes

show sizes in MiB, or MB with --si

--gbytes

show sizes in GiB, or GB with --si

--tbytes

show sizes in TiB, or TB with --si

A status on a filesystem without any error looks like the following:

```
# btrfs scrub start /
# btrfs scrub status /
UUID:             76fac721-2294-4f89-a1af-620cde7a1980
Scrub started:    Wed Apr 10 12:34:56 2023
Status:           running
Duration:         0:00:05
Time left:        0:00:05
ETA:              Wed Apr 10 12:35:01 2023
Total to scrub:   28.32GiB
Bytes scrubbed:   13.76GiB  (48.59%)
Rate:             2.75GiB/s
Error summary:    no errors found
```

With some errors found:

```
Error summary:    csum=72

  Corrected:      2

  Uncorrectable:  72

  Unverified:     0
```

- Corrected -- number of bad blocks that were repaired from another copy

- Uncorrectable -- errors detected at read time but not possible to repair from other copy

- Unverified -- transient errors, first read failed but a retry succeeded, may be affected by lower layers that group or split IO requests

- Error summary -- followed by a more detailed list of errors found

- csum -- checksum mismatch

- super -- super block errors, unless the error is fixed immediately, the next commit will overwrite superblock

- verify -- metadata block header errors

- read -- blocks can't be read due to IO errors

It's possible to set a per-device limit via file sysfs/fs/btrfs/FSID/devinfo/scrub_speed_max. In that case the limit is printed on the Rate: line if option -d is specified, or without it on a single-device filesystem. Read more about tat in section about scrub IO limiting.

```
Rate:             989.0MiB/s (limit 1.0G/s)
```

On a multi-device filesystem with at least one device limit the overall stats cannot print the limit without -d so there's a not that some limits are set:

```
Rate:             36.37MiB/s (some device limits set)
```

## EXIT STATUS
btrfs scrub returns a zero exit status if it succeeds. Non zero is returned in case of failure:

1

scrub couldn't be performed

2

there is nothing to resume

3

scrub found uncorrectable errors

## AVAILABILITY
btrfs is part of btrfs-progs. Please refer to the documentation at https://btrfs.readthedocs.io.

## SEE ALSO
mkfs.btrfs(8)


btrfs-select-super

title: btrfs-select-super(8)

text:
# btrfs-select-super(8)

## NAME
btrfs-select-super - overwrite primary superblock with a backup copy

## SYNOPSIS
btrfs-select-super -s number <device>

## DESCRIPTION
Destructively overwrite all copies of the superblock with a specified copy. This helps in certain cases, for example when write barriers were disabled during a power failure and not all superblocks were written, or if the primary superblock is damaged, e.g. accidentally overwritten.

The filesystem specified by device must not be mounted.

NOTE:

Prior to overwriting the primary superblock, please make sure that the backup copies are valid!

To dump a superblock use the btrfs inspect-internal dump-super command.

Then run the check (in the non-repair mode) using the command btrfs check -s where -s specifies the superblock copy to use.

Superblock copies exist in the following offsets on the device:

- primary: 64KiB (65536)

- 1st copy: 64MiB (67108864)

- 2nd copy: 256GiB (274877906944)

A superblock size is 4KiB (4096).

## OPTIONS
-s|--super <N>

use Nth superblock copy, valid values are 0 1 or 2 if the respective superblock offset is within the device size

## SEE ALSO
btrfs(8)