Manjaro Difference between revisions of "Btrfs/ru"

Difference between revisions of "Btrfs/ru"

From Manjaro
(Created page with "смотрите@ https://forum.manjaro.org/t/howto-resize-a-btrfs-filesystem/152999")
(Created page with "Файловая система BTRFS также может быть безопасно расширена с помощью '''gparted'''. При этом выполняют...")
Tags: Mobile web edit Mobile edit
Line 429: Line 429:
==== расширение ====
==== расширение ====


<div lang="en" dir="ltr" class="mw-content-ltr">
Файловая система BTRFS также может быть безопасно расширена с помощью '''gparted'''. При этом выполняются все необходимые действия, такие как:
A BTRFS file system can also be safely expanded with '''gparted'''. All necessary steps are taken such as:
* Расширение раздела
* Extend partition
* Монтирование файловой системы
* Mount file system
* Расширение файловой системы
* Expand file system
* Размонтирование файловой системы
* Unmount file system
</div>


= Параметры Btrfs =
= Параметры Btrfs =

Revision as of 11:04, 25 March 2024

Other languages:
English • ‎Türkçe • ‎русский

Btrfs - это современная CoW файловая система

Современная Copy on Write файловая система для Linux, нацеленная на реализацию расширенных возможностей, а также на отказоустойчивость, ремонт и простое администрирование. Btrfs - это не только файловая система, но и менеджер томов, программный рейд, инструмент резервного копирования, а также flash-friendly.

Поскольку Btrfs отличается от других - некоторые вещи кажутся незнакомыми и странными. Если вы хотите узнать подробности и самые новые вещи, то btrfs.wiki.kernel.org или btrfs.readthedocs.io. Разработка Btrfs началась в 2007 году. С тех пор Btrfs является частью ядра Linux и находится в стадии активной разработки. Кодовая база и файловая система Btrfs являются стабильными. Однако новые функции все еще находятся в стадии разработки. Основными возможностями и преимуществами являются:

  • Снэпшоты, которые не делают полную копию файлов.
  • Менеджер томов объединяет разделы, разбивает на подтома
  • RAID - поддержка программных RAID 0, RAID 1, RAID 10.
  • Автовосстановление - контрольные суммы для данных и метаданных, автоматическое обнаружение тихих повреждений данных

(смотри btrfs@kernel.org, btrfs.readthedocs.io, Btrfs@ARC-wiki, Btrfs@wikipedia)


Знакомы с btrfs-сленгом?

Поскольку Btrfs отличается от других, вы найдете некоторые слова, имеющие особое значение при использании btrfs. Это может стать источником путаницы.

Том Btrfs
Том представляет собой пул необработанного хранилища и состоит из одного или нескольких устройств. Размер тома будет равен сумме размеров всех устройств, входящих в этот раздел. В большинстве случаев вы будете использовать только один том. Также можете добавлять/удалять устройства в любое время. Обычно не приходится монтировать тома Btrfs.
блок
Блок - это просто кусок памяти, который Btrfs может использовать для размещения данных. Подумайте о блоке (обычно 1GiB) как о странице в книге. Книга - это раздел, а блок - это одна страница. Когда вы начинаете работу - все страницы пусты. При записи данных в раздел записывается одна страница (="блок") за другой.
устройство
Устройство" - это некоторое устройство linux. Это может быть раздел, например /dev/sdz1 или /dev/sdz2. Или это может быть необработанное дисковое устройство типа /dev/sdz без каких-либо разделов. Раздел Btrfs состоит из как минимум одного устройства.
subvolume
A Btrfs subvolume is an independently mountable POSIX file-tree and not a block device. It is the part of a volume that will be mounted writeable into your Linux system. By convention the names of subvolumes start with @ (@, @home, @snapshots ...). All subvolumes share the space of the Btrfs volume. You may create subvolumes at will. (You may think of subvolumes as sort of "dynamic partitions" inside a Btrfs volume)
default subvolume
The default subvolume of a Btrfs volume is special. When you mount, you normally have to name a subvolume to mount. When you don't name a subvolume, the default subvolume will be used. The default subvolume can be changed to any subvolume. It is advisable to set that subvolume as default, that is used for mounting linux "/" this is often the subvolume with the name "@"
▶ Btrfs volume-root "/", Btrfs layout
A volume contains one ore more subvolumes. But they are not stored in form of a simple list. These subvolumes are stored in a tree-like structure like in a filesystem. Sometimes called the "top-level subvolume" or "root of the volume". But be careful this is not linux-root "/", but Btrfs volume-root "/". There are several basic schemas to layout subvolumes in a volume
snapshot
A snapshot looks nearly the same as a subvolumes. But don´t get confused. When we talk about snapshots we usually mean a "Read-Only (ro) photograph of a subvolume". While the subvolume changes with time. A snapshot stays in the state of the subvolume at the time we made it. You can mount snapshots into your linux system, but you only can read the content. And the content will never change while this snapshot exists. When creating snapshots you have to watch out for the Btrfs-layout in use.

It is possible to make a writeable(rw) subvolume out of a ro-snapshot. This is the way roll back does work.

▶ Self-healing
This is no magic. Because of the nature of Btrfs as CopyOnWrite filesystem and because of the checksums, it is possible to check the filesystem and repair some errors. This does happen silently.
  • Без RAID можно исправить некоторые мелкие неполадки, возникшие из-за отключения питания. (Это делается при повторном монтировании файловой системы)
  • С RAID1 можно восстановить некоторые части файлов, поврежденные в результате сбоев на одном устройстве. (Это делается при следующем чтении файла).
scrub
A scrub is like an inspection of your car. The mechanic will look at all parts, and will tell you if something is amiss. If he finds very small problems, he will repair this automatically without asking for permission, and with minimal extra cost.
balance
A balance is like renovating your home. Sometimes it is necessary to renovate a room, sometimes you will renovate your home completely. But you don't do it once in every week ;-) With balance, the furniture will be transported around and rearranged. You need to do this when changing RAID-levels.

Вы также можете взглянуть на Глоссарий Btrfs

Управление томами

Том - это пул необработанной памяти. Состоит из одного или нескольких устройств. Размер тома будет равен сумме всех включенных в него устройств, если только вы не используете RAID.

Если вы используете более одного устройства - прочтите также раздел о RAID. Вы можете добавлять/удалять устройства в любое время, чтобы увеличить/уменьшить размер тома. При добавлении/удалении устройств можно также перемещать том с одного устройства на другое (без изменения UUID).

Обычно вы не монтируете сам том Btrfs, а монтируете подтома. Бывают случаи, когда целесообразно монтировать сам корневой том Btrfs. Тогда вы сможете изменить компоновку тома. Все (доступные для записи) подтома внутри тома можно перемещать внутри него с помощью mv. Перемещение подтомов не затронет данные, но мгновенно изменит компоновку тома.

Если не указано иное, дополнительные устройства обрабатываются как J ust a B unch o f D isks (JBOD).

Подсказка
В большинстве случаев рекомендуется использовать только один том

Extend a volume

This is very easy because btrfs incorporates a volume manager. You only have to look for a free device. You may use a partition like /dev/sdz4 or you may use a raw device like /dev/sdz. Then add this device to your existing volume with btrfs device add. You may need to do a balance afterwards to redistribute some chunks.

root # btrfs device add [/dev/sdz4] / COPY TO CLIPBOARD

Dont´t format the partition!
To add a device it should have NO filesystem on it. The btrfs volume manager will include the free storage of the device into the existing filesystem.

Move a volume (to another disk)

There are a lot of ways you can move a "normal" filesystem from one disk to another. But there are dangers with moving btrfs volumes that do not exist with other filesystems! Don´t ever move a btrfs volume with a tool that does not say it is 100% btrfs-proof. When at any time there are 2 partitions in one computer that have the same filesystem UUID, one ore both filesystems may be destroyed. Under the topic tips you will find an easy way to do move a volume without any danger

Do NOT
  • make a block-level copy of a Btrfs filesystem to another block device
  • use LVM snapshots, or any other kind of block level snapshots
  • turn a copy of a filesystem that is stored in a file into a block device with the loopback driver
  • try to mount either the original or the copy while both are visible to the same kernel
See why at Block-level copies of devices@btrfs.wiki.kernel.org
Tip: move a volume
There is an easy and secure way to move a volume to another disk/device. If you use Btrfs itself to move the volume, there will be no danger. You even can do this while the volume is in use. See how to in "tips"

Подтом

Подтом - это независимое монтируемое файловое дерево POSIX, а не блочное устройство. Это та часть тома, которая будет монтироваться с возможностью записи в вашу Linux-систему. Если вы не заботитесь о моментальных снимках и резервном копировании, то можно было бы использовать только один подтом для всего. Но тогда вы не сможете использовать возможности Btrfs. Предположим, что вам это важно.

Все подтома разделяют пространство тома Btrfs. Вы можете создавать подтома по своему усмотрению. (Можно рассматривать подтома как своего рода "динамические разделы" внутри тома Btrfs)

When making snapshots (or send/receive) every subvolume will be handled separately. For example when you have 2 subvolumes(@, @home), and make a snapshot of one of them(@), this snapshot will contain every bit of data of all files in this subvolume(@), but none of the data from the other subvolume(@home). So if you make a few subvolumes, you are able to follow different strategies for snapshots of them. And you can restore each of them separately.

По соглашению имена подтомов начинаются с @ (@home, @snapshots ...).


Подтом @

Это подтом, на котором будет располагаться ваша полная система manjaro. Он монтируется в "/" в вашу файловую систему. Для защиты работающей системы manjaro можно делать моментальные снимки этого подтома (или резервные копии с функцией отправки/получения). Если произойдет что-то плохое, вы сможете откатиться к одному из снимков или восстановить одну из резервных копий этого подтома без потери данных в /home.

Для того чтобы откат был возможен, он должен содержать все данные, необходимые для правильной работы manjaro! Сюда входят:

  • конфиг вашего загрузчика (/boot/brub/grub.cfg)
  • initramdisk (/boot/initramfs-5.10-x86_64.img)
  • kernel (/boot/vmlinuz-5.10-x86_64)
  • kernel-modules (/usr/lib/modules/5.10.59-1-MANJARO/*)
  • программы (/usr/bin/*)
  • конфигурации (/etc/*)
  • библиотеки (/usr/lib/*)
  • ваша учетная запись root (/root/*)
  • остальные системные файлы (/usr/*)

Подтом @home

Это подтом, в котором хранятся все пользовательские данные. При откате на "@" он не изменится. Снимки /home можно делать с разной частотой и по разным причинам. Если снимки "@" полезны для отката, то снимки @home полезны для неудаления случайно удаленных (или перезаписанных) пользователями файлов.

Подтом @snapshots, @home.snapshots

Снимки целесообразно "хранить" НЕ внутри того подтома, с которого они были сняты. Так что @ или @home может быть правильным местом для хранения снимков.

Подтом @...

Иногда для некоторых участков файловой системы требуется использовать другие специальные стратегии создания снимков (или вообще не создавать снимков). Если это необходимо - создайте еще один подтом.

To have access to the root(/) of your volume, you need to mount this separately. (Please do not confuse this with "/" of the file system)

root # mount -t btrfs -o subvol=/,defaults [/dev/sdz2] /mnt COPY TO CLIPBOARD

Now you are able to create a new subvolume in a flat layout.

root # btrfs subvolume create [/mnt/@tests] COPY TO CLIPBOARD


This will be shown by

root # ls -l /mnt COPY TO CLIPBOARD


root # btrfs subvolume list /mnt COPY TO CLIPBOARD


This subvolume tests is empty. And it is not mounted by default. So if you want to use it, you have to mount it by fstab or other means. Now lets delete it again.

root # btrfs subvolume delete [/mnt/@tests] COPY TO CLIPBOARD


root # umount /mnt COPY TO CLIPBOARD


Снэпшот

A snapshot looks nearly the same as a subvolume. But snapshots really are "read-only photographs of a subvolume". While the subvolume changes with time. The snapshot is frozen in the state of the subvolume at the time you made it. A snapshot is read-only. Therefore it is guaranteed not to change. In a snapshot you will find all files of the subvolume frozen in time. A snapshot is not a substitute for a backup!

Where to place snapshots
When creating snapshots you have to watch out for the volume layout in use. see@wiki.archlinux

Снимки (если они делаются регулярно) могут быть использованы для:

  • Сравнения файлов конфигурации, созданных в разное "время".
  • Объединения файлов конфигурации
  • Восстановления случайно удаленных/перезаписанных файлов
  • Отката системы
  • Основы для резервного копирования с отправкой/получением
  • Основы для создания резервной копии
  • Для чего вы используете моментальные снимки?

Создание и удаление моментальных снимков лучше всего выполнять автоматически:

Создание снимков

Создание моментального снимка - это очень быстро и почти бесценно. После создания снимка все последующие записи будут проходить как в обычном CoW. Но ни одно из мест, занятых файлами в снимке, не будет использовано повторно. По мере записи все новых и новых файлов файловая система будет расти, поскольку она не сможет повторно использовать файлы в моментальном снимке. Новый снимок будет дополнительно замораживать все созданные или измененные файлы с момента последнего снимка и так далее. Если вы не освободите (удалите) ни один снимок, то в конечном итоге у вас "скоро закончится место" (диск заполнен).

Высвобождение моментальных снимков

При удалении снимка не удаляются файлы, фактически используемые другими снимками или подтомом, из которого они были взяты. Чтобы освободить место, Btrfs проверяет каждый файл в снапшоте, используется ли он или нет. Если нет, то место для этого файла/версии станет свободным. (Это значительно упрощено) Поэтому удаление моментальных снимков является дорогостоящим. И Btrfs будет делать эту работу в фоновом режиме. Вы можете заметить это, потому что при удалении снимка не будет немедленного выигрыша в свободном пространстве. Через некоторое время вы заметите, что часть пространства освободилось.

Не забывайте удалять моментальные снимки, иначе скоро у вас возникнут проблемы - "нехватка места". Btrfs необходимо некоторое свободное пространство для управления своей работой. Если ваш том заполнен более чем на 80%, то нужно быстро сообразить, что делать.

  • ++++ Добавить какой-нибудь раздел/устройство на том.
  • +++ Удалить ненужные снимки
  • + Удалить некоторые файлы (это поможет только в том случае, если они не являются частью какого-либо моментального снимка)

Откат к снапшоту

Если вам нужно откатиться на моментальный снимок - необходимо заменить реальный подтом выбранным моментальным снимком.

  1. Сделать снимок(ro) фактического подтома (для последующего использования)
  2. Удалите подтом из его фактического места
  3. Создайте новый подтом(rw) из моментального снимка, выбранного для отката.
  4. Сделайте этот новый подтом томом по умолчанию (необязательно)
  5. Не забудьте удалить сделанный снимок через несколько дней.

посмотреть на форуме: Ручной откат с помощью btrfs

Please also have a look at snapper-rollback@github and at snapshot-layout@wiki.archlinux for the suggested flat layout and the reasoning. (Rollback example )

Don't forget to remove snapshots before you run out of space
Every time you take a snapshot you only use the "rest of the volume" for storing everything you change from this time on. At some point in time you have to release the snapshot. Don´t use your space up. Btrfs needs space to breath. Don't use more then 80% or you will get into trouble."
NO Snapshots together with quotas
There are reports about massive problems when using quotas together with snapshots (snapper, timeshift). Please have a look at: Known_issues@btrfs.kernel.org

Btrfs RAID

With Btrfs you no longer need to use mdadm to create mirrored volumes or to create RAIDs. This is already included in btrfs, and very easy to use. There are even advanced features bult in:

  • Add devices to the volume This will integrate a device into the mounted volume
    root # btrfs device add [/dev/sdz7] / COPY TO CLIPBOARD

  • Remove devices from the volume. This will not delete any data, but remove the device from the volume. Bevorehand all data will be copied to the remaining devices of the volume.
    root # btrfs device delete [/dev/sdz8] / COPY TO CLIPBOARD


  • Use devices with different sizes in one volume
  • Switch the volume between RAID levels
  • Convert data to different RAID levels
  • Do this while the volume is mounted and being used
Raid Levels
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 (of btrfs). See RAID@wikipedia,RAID profiles@btrfs.readthedocs

RAID 0 (not Just a Bunch of Disks)

Using one ore more devices to build a volume. This volume has the capacity of all the used devices together(1+2+3+4...). This is an very easy way to expand your volume when you need more space. You even can add 2 or 3 devices at a time. When you want to replace a device, you can add the new device, then remove the old device. Btrfs will move all data as necessary. To distribute all data to all devices you may want to balance the volume. Btrfs will stripe the data to all devices.

If one device fails, everything is lost
Be aware that when one of the devices fails your complete volume may be lost if you use RAID 0

1 устройство

В большинстве случаев тома запускаются с 1 устройства. Если имеется только одно устройство, то метаданные будут дублироваться на этом устройстве. Даже при такой простой настройке вы получаете преимущества от большинства возможностей Btrfs.

2 и более устройств

По умолчанию метаданные будут зеркалироваться на двух устройствах, а данные будут чередоваться на всех имеющихся устройствах. Однако если в томе имеется 2 и более устройств, то следует рассмотреть возможность использования RAID 1.

RAID 1 (зеркальный), 1C3, 1C4

When using Raid 1 btrfs mirrors data and metadata. This way it is possible to repair data when one copy gets damaged. This could happen when one device fails, when power was lost while writing, ... After enabling RAID1 all new data and metadata is automatically mirrored. To mirror your existing data and metadata, you have to balance your complete volume.

Автоматическое восстановление

Для сохранения целостности тома Btrfs выполняет раздельную проверку CRC - контрольных сумм блоков метаданных и блоков данных. При каждом чтении блока данных проверяется контрольная сумма. Если контрольная сумма показывает, что данные плохие, Btrfs пытается получить хорошую копию из зеркалированного блока. Затем плохой блок снова записывается с хорошими данными из зеркального блока. Это происходит в фоновом режиме. Файловая система была восстановлена, о чем сообщается в syslog. Это можно сделать принудительно с помощью команды btrfs scrub.

RAID 10 (автоматический)

При использовании достаточного количества устройств (4...) с RAID 1, Btrfs распределит все данные таким образом, что они будут не только зеркальными, но и чередующимися.

RAID 5

Еще не сохранено
Не рекомендуется смотрите Parity RAID@btrfs.wiki.kernel.org

RAID 6

Ещё не сохранено
Не рекомендуется смотрите Parity RAID@btrfs.wiki.kernel.org

Обслуживание Btrfs

Btrfs, как и любая файловая система, нуждается в обслуживании. Чем больше вы используете расширенные возможности btrfs, тем больше вы должны следить за правильным обслуживанием. Посмотрите также Btrfs_Maintenance.

Фрагментация

Файлы на btrfs имеют тенденцию к некоторой фрагментации, когда они часто добавляются или изменяются. Если вы используете механический диск с медленной скоростью поиска, возможно, стоит время от времени (например, раз в месяц) дефрагментировать некоторые часто используемые файлы.

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

Базы данных

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

Файлы журналов

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

Balance

When adding devices or changing the RAID-level of your volume, it may be necessary to balance your volume. While balancing, btrfs will read ALL (or a subset of all) chunks in, and write them out again using the actual RAID-level. It will stripe these files over all available devices equally. While this happens, the volume will keep being usable, but you may see some heavy load on it. Also this may take a very long time because ALL data must be read AND written again. Don´t worry about shutdown. When you shutdown your computer while the balance is running, the balance will pause. After you restart the computer the balance will restart and continue until it is finished.

Possible bug when using a swap file:
Never use a full-balance on a machine with a swapfile, since it will ignore +C Attributes. You may also have a look at [1]

Filters

Because a complete balance may take a long time, there is the possibility of filters in balance. When using a filter only those chunks will be balanced, that are named by the filter.

  • balance all chunks that are less than 50% full. This will take some time !
root # btrfs balance start -musage=50 -dusage=50 / COPY TO CLIPBOARD

  • balance all chunks that are less than 90% full. This will take some time !
root # btrfs balance start -musage=90 -dusage=90 / COPY TO CLIPBOARD


Merging chunks

As you use your volume, you will be creating some files, deleting some, modifying some. Then some parts of the chunks are empty. But this is not a coherent space that can be easily reused. Usually this is not a problem for btrfs and will be cleaned up automatically over time. However, if space is scarce (> 80% full), it is advisable to merge free areas together. This can be done by using balance with a filter.

After removing a device

When you remove a device from a volume, btrfs will automatically balance all "chunks" that where on the removed device. These chunks are placed on another device of the volume. So you don't need to balance by yourself after removing a device.

After adding a device

When you add a device there will be no automatic balance. Only when further using the volume, btrfs will use the additional free space according to the actual RAID-level.

After changing RAID-level

When you changed RAID-levels (for example from RAID 0 to RAID 1) there is no automatic duplication of the chunks. Only when writing further, btrfs will respect the changed RAID-level. This may not be what you intended. To complete the conversion to another RAID-level you need to tell btrfs to rewrite chunks where needed. You do this with a manual balance:

смотри: btrfs filesystem balance

Скраб

Скраб тома btrfs подобен осмотру дома. Работает ли свет во всех комнатах? Не разряжена ли батарейка в дымовой сигнализации? Нужно ли заменить огнетушитель? Не протекает ли какой-нибудь кран? Время от времени рекомендуется обращать внимание на такие вещи. И сразу же исправлять!

Check & repair on the fly

Every time btrfs reads a file, it checks the corresponding checksums. When btrfs is in RAID 0 and detects a 'damaged' file, it only can tell you that the file is damaged. You may delete it, or replace it from your backup. When running in RAID 1 btrfs has 2 copies of every file. So if one file seems to be damaged, btrfs will read the other copy. If this other copy is ok, btrfs will automatically create another good copy of the file, and then afterwards delete the defect copy. You won't even notice this 'automatic' repair.

Full check

Sometimes you may want to check ALL files, and to get a report of defects, because:

  • Some files are read very seldom, and you don't want "bitrott"
  • You want to check your data completely for any faults
  • Once in a while you want to make sure all is well
  • You want to force your disk/device to verify all data
  • ...

This is when you use btrfs scrub. Scrub will read ALL data of your complete volume. While this is done, all files and metadata will be checked by the checksums and all problems will be reportet. Because this will read and verify your complete volume (eventually a few Terra-byte), it may take some time. Scrub will not waste time in checking unused chunks. While checking you can enable automatic repair for RAID 1 or disable it. If you disable automatic repair, scrub will work completely readonly, and will change nothing on your volume.

Очистка может выполняться автоматически (например, каждый месяц) или вручную.


Notice
Имейте в виду, что Scrub не проверяет структуру файловой системы, а только проверяет контрольные суммы данных и блоков дерева. Вы также можете посмотреть на проверку дерева

Ручная очистка выполняется с помощью:

root # btrfs scrub start -Bd / COPY TO CLIPBOARD


Решение проблем

Конец свободного пространства

Avoid to get out of space with btrfs!

Don't be stingy on storage space when creating a btrfs volume. A btrfs volume should normally only be 80% full. Then it is advisable to adjust the volume. In an emergency, 90% are okay too. But that is neither advantageous for the Btrfs volume nor for an SSD.

Don't forget to include the snapshots in the bill
Manjaro is a rolling release distribution. There will be a lot of changes over time.
Tip: Check how close you are to "out of space".
Look at Device unallocated: (not at Free (estimated):) 1
root # btrfs filesystem usage / COPY TO CLIPBOARD

Get out of jail

This said, there is an easy way out: Give btrfs more space ;-)

  • add a partition (for example a extern USB-Stick with 8GB) to the btrfs-volume with
    root # btrfs device add /dev/[sdz4] / COPY TO CLIPBOARD


  • From now on this usb-partition belongs to your volume! Do not boot without it. Do not reboot at all in this stage! This stick has to stay until btrfs device remove has completed.
  • look for old snapshots you don´t need, remove them now
  • or delete some files you do not need
  • Do this until your disk will be not more then 95% full

Не пугайтесь, если btrfs не сразу отобразит свободное место. После следующего шага (балансировка) оно станет видимым.

  • balance your volume with a filter(50%) This will take some time !
root # btrfs balance start -musage=50 -dusage=50 / COPY TO CLIPBOARD

Tip: Want to watch the volume clean up ?
user $ pamac install procps-ng COPY TO CLIPBOARD

After that inside a terminal:
root # watch -n 60 btrfs filesystem usage -h / COPY TO CLIPBOARD

  • balance your volume with a filter(95%) This will take some more time !
root # btrfs balance start -musage=95 -dusage=95 / COPY TO CLIPBOARD


  • remove the added partition from the volume with
    root # btrfs device remove /dev/[sdz4] / COPY TO CLIPBOARD

  • This will take some time ! Do not reboot until this step is complete.
  • Now you may remove the USB-Stick.

Не попасть в беду

  • Подумайте, как расширить том btrfs до двойного размера
  • поищите, нет ли программы, заполняющей ваш диск
  • ищите моментальные снимки!
  • не забудьте удалить старые снимки (лучше всего это делать автоматически)

Corrupted checksums

[ 9364.354241] BTRFS error (device nvme0n1p3): block=58469742080 write time tree block corruption detected

This ERROR or similar may lead to Messages like:

Configuration file "/home/user/.config/dolphinrc" not writable. Please contact your system administrator.

because btrfs does mount this partition readonly when it detects corrupted blocks.

Теперь вам нужно выяснить, ПОЧЕМУ контрольная сумма блока btrfs говорит о том, что она повреждена.

  • In some cases the underlying device may beginn to fail ! => replace it (consider using RAID10)
  • In other cases a corruption may have happened even before the block had been written to disk
    • corruption in RAM
    • some software-bug ???
    • ssd gone bad ??? example

What the Btrfs developers say:

Смотрите также: Tree-ckecker

Советы

Создание тома

There is an easy and secure way to move a volume to another disk/device. If you use Btrfs itself to move the volume, there will be no danger. You even can do this while the volume is in use.

  • Create the partition you want to use as destination without formatting it. Or remove the filesystem when one is present
  • Add the destination device to your volume by
    root # btrfs device add /dev/[destination] [path to filesystem] COPY TO CLIPBOARD

  • Remove the source device from your volume by
    root # btrfs device remove /dev/[source] [path to filesystem] COPY TO CLIPBOARD


Btrfs will notice, that it is necessary for this setup to move all data from the source device to the destination device. And it will start immediately to move data in the background. Meanwhile you can use your PC as you want.

  • Empty Blocks will not be moved
  • Compressed data will remain compressed
  • All Snapshots will remain
  • The UUID of the filesystem will remain the same, but btrfs will be aware of this
  • If you used the UUID to identify your volume, you even wont´t need to edit /boot/grub/grub.cfg and /etc/fstab
  • Only, don't shutdown while the move of the volume is not complete.

If you want to watch the volume move, inside a terminal:

user $ pamac install procps-ng COPY TO CLIPBOARD


root # watch -n 60 btrfs filesystem show / COPY TO CLIPBOARD


Изменение размера файловой системы/устройства btrfs

При изменении размера файловой системы необходимо также изменить размер раздела (устройства), на котором она находится. Вы не можете изменить размер смонтированного раздела с помощью gparted! Поэтому нужно предварительно отмонтировать его или использовать живой образ manjaro с USB для изменения размера раздела и файловой системы.

При изменении размера существующих файловых систем настоятельно рекомендуется иметь текущие резервные копии. Однако изменение размера возможно без проблем при использовании gparted.

сокращение

What you need to understand is that you can only safely shrink a file system if it is not too full. Shrinking a file system can take a long time because BTRFS may need to move data that was in the area to be freed to the remaining area.

Using gparted you can safely shrink a BTRFS file system. All necessary steps are taken such as:

  • Mount file system
  • Shrink file system
  • Unmount file system
  • Shrink partition

смотрите@ https://forum.manjaro.org/t/howto-resize-a-btrfs-filesystem/152999

расширение

Файловая система BTRFS также может быть безопасно расширена с помощью gparted. При этом выполняются все необходимые действия, такие как:

  • Расширение раздела
  • Монтирование файловой системы
  • Расширение файловой системы
  • Размонтирование файловой системы

Параметры Btrfs

Compression

Compression can only be set per volume. So if you set different "levels" of compression for different mounts in the fstab, only the first "level" will be applied. see@btrfs.readthedocs.io

Grub needs to load the kernel and initrd
When you use compression on kernel, initrd, or grub config files, grub needs to decompress these files. Otherwise you will not be able to boot. GRUB introduced zstd support in 2.04. Maybe you need to update grub and reinstall it

Шифрование

Может быть в будущем.

Send + receive = backup

Some wiki-posts in the forum:

Quota groups

Quota support in Btrfs is implemented at the subvolume level.

For more info see Quota_support@btrfs.kernel.org

Reports about problems
There are reports about massive problems when using quotas (especially together with snapshots, snapper, timeshift). Please have a look at: Known_issues@btrfs.kernel.org

Зональный режим

Начиная с версии 5.12

= Инструменты для работы с Btrfs. Для получения полной информации обо всех инструментах для btrfs выполните поиск в arch wiki и на форуме manjaro по запросу "btrfs". В следующем разделе описаны лишь некоторые команды. Особенно те, которые часто неправильно интерпретируются. Команды, описанные ранее, опущены.

btrfs (the command)

Be aware that some sub-commands of btrfs will not work as normal user. Other sub-commands do work but will give only partial info. So best use them as root or with sudo.

help, version

help together with man btrfs or info btrfs will get you an overview over the usable options on your install.
user $ btrfs help COPY TO CLIPBOARD

With the version of btrfs given here you can look at changelog.
user $ btrfs version COPY TO CLIPBOARD

device

scan will give no visible results 😜

root # btrfs device scan COPY TO CLIPBOARD

stats will give a list of errors detected in the past. This all should be 0, or you may be in trouble.

root # btrfs device stats / COPY TO CLIPBOARD

What to look for in device usage:

  • RAID-level of Data, Metadata and System
  • Unalocated:

Don't ever let Unalocated: get below 5% of your volume (or double the size you need for your next update)! If this goes too low, you will get into "out of space" trouble

root # btrfs device usage / COPY TO CLIPBOARD

Without sudo this will give very wrong results for everything displayed. Dont´t use this without sudo !


btrfs filesystem df /

btrfs filesystem du

btrfs filesystem show

btrfs filesystem usage

btrfs scrub status

btrfsck

Это совсем не то, что вы думаете 😜

Рекомендации

We recommend using Btrfs with UEFI and GPT
Partition Filesystem Size Partition type
/dev/sda1 Fat32 1GiB EFI system partition
/dev/sda2 Btrfs 1Gib - 8EiB Btrfs Volume
/dev/sda3 swap 4GiB, at least your RAM-size Swap partition (optional)
IF you don't have UEFI, you may use Btrfs with BIOS and GPT
Partition Filesystem Size Partition type
/dev/sda1 (bootloader) 4MiB BIOS boot partition
/dev/sda2 Btrfs 1Gib - 8EiB Btrfs Volume
/dev/sda3 swap 4GiB, at least your RAM-size Swap partition (optional)

Please be aware that the information on this page is a simplified version of the reality. Is is written to make the reader understand a little of these complex things. To get an in depth understanding it will be neccesary to read further at btrfs.wiki.kernel.org or other places.

Additional Information

Why not btrfs ?

A lot of people say: "I don't use btrfs because it is experimental and is not stable. You can´t use it in production. It is not safe!".

Not stable ?

The status of btrfs was experimental for a long time, but the core functionality is considered good enough for daily use. (from kernel.org)

If you see statements declaring Btrfs as not stable, please look for the date of them. Some seem to date from 10 years ago. So if you want to give Btrfs a chance, you have to look for newer statements. Maybe even look at Btrfs Kernel Wiki as that sure is the best information regarding Btrfs

Experimental ?

Btrfs is feature-rich! There are new features being implemented and these should be considered experimental for a few releases when the bugs get ironed out when number of brave users help stabilizing it.(from kernel.org)

Some features are not implemented yet. Others are only partly implemented. Some are experimental and not suggested for production use. As is always the case in Linux-land you decide what to use, and so you are responsible for your own decisions.

Not usable for production ?

  • Distro support for Btrfs as main filesystem
  • Some companies do use Btrfs in production@wiki.btrfs.kernel.org
  • Some manufacturers do deploy devices where Btrfs is installed by default.

Difficult to repair ?

Indeed, when you search for the usual ways to repair a file system like FAT or Ext4 then you don't find good information about repairing btrfs. This is not because it is difficult to repair Btrfs, but because repairing Btrfs does work very differently.

What's this "Copy on Write"

When you want to get the most out of using Btrfs you do need to know some things about this file system. Then you are able to use it properly and to your advantage. Btrfs is not difficult, but different to some extend.

Write in place (FAT32)

Most older file systems do write "in place". This means that some data or metadata will be written "over" the previous data at the same place.

For example this is the case for FAT32 file systems. The File Allocation Table is at a fixed place on this file system. When the "FAT" changes (because a file got bigger and needs more blocks), this new FAT must be written with the new data to the same place as before. When the disk is ejected before (or while) this data is written, the file system will be corrupted. And the FAT does change a lot.

The danger of corruption is especially big while metadata (like filename, permission, usage of disk space ...) is being written.

Write to a metadata-log (Ext4)

There is a solution to this with newer file systems like Ext4. Instead of writing metadata "in place", metadata is written into an "endless" log. Then it is not possible to be corrupted while overwritten. This is possible because metadata is only a very small part of the data in a file system.

There has to be an additional mechanism to make this safe. Sometimes this is called "barriers", and there have to be checksums that tell when a part of the log is corrupted.

This does protect the file system itself, but not the files in it. Because a file may be overwritten in place, and then the old file is lost, and the new one may not have been written completely.

Copy on Write! (Btrfs)

Copy on Write is a "new" concept. It means the file system will try to never write over existing data. How is this even possible?

  • Files are appended at the end of a "data page"
  • Metadata is appended at a "metadata page"
  • Inside a page nothing is ever overwritten
  • When a page is full the file system will use the next free page
  • Deleting a file does not write/clean its data, but writes metadata, that marks this file as deleted
  • Overwriting a file does first append the new file to the actual "data page", then appends the metadata for this file to the "metadata page".
  • Changing small parts of a file will write only the new parts, then link the rest to the old file
  • there are checksums for data and metadata

Downsides

  • Management of space is complex
  • There are 2 sorts of pages (data / metadata)
  • There has to be a clean-up-process who makes the space of deleted files reusable, so that the disk does not run out of free pages
  • It must be avoided to write data unnecessarily, because then the clean-up would also be very expensive

Advantages

  • It is possible to detect nearly any corruption because of the checksums
  • When the power is lost, or the disk is disconnected, all old data is save. WHY?
    • Every bit of "old" data from before the power loss or the disconnection is present because it is NOT overwritten
    • Only the newly written data may be partly damaged
    • The metadata may also be partly damaged
    • When mounting the volume it is possible by analyzing checksums and metadata to find the point in the filesystem where all was good
    • Btrfs will automatically roll back to this point, then it can mount the file system writable
  • CoW - это прочный фундамент, на котором можно строить
    • Снимки
    • RAID
    • Управление томами
    • Сжатие
    • Шифрование (возможно, в будущем)


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

Используйте форум!

Хорошей идеей будет искать на форуме сообщения, связанные с btrfs.

Btrfs быстро развивается! Смотрите также:

Cookies help us deliver our services. By using our services, you agree to our use of cookies.