- Btrfs установка и использование
- Btrfs установка
- Использование btrfs
- Установка из существующей системы или с live usb
- ArchLinux: установка системы на subvolume BTRFS
- Опубликовано mfc166 в 01.03.2021 01.03.2021
- Настройка сети
- Разметка дисков
- Создание разделов
- Создание файловой системы
- Создание subvolume
- Монтирование и подготовка к установке
- Установка
- Arch linux btrfs установка
- About
Btrfs установка и использование
Btrfs установка
Установите пакет пользовательских утилит.
lsblk — подсветить все разделы чтобы определиться, что монтировать.
Так как Btrfs не может содержать swap-файл, необходимо заранее позаботиться о разделе с подкачкой, если он вам нужен.
Создаём файловую систему на разделе. Для разделов от 1ГБ и меньше, чтобы более эффективно использовать пространство, рекомендуется передать ключ -M к параметрам mkfs.btrfs .
При желании можно задать лэйбл ключом -L.
Затем создадим два подтома под корень и домашние каталоги пользователей.
Отмонтируем корень ФС.
Для того, чтобы монтировать подтом подобно обычному разделу диска, команде mount нужно указывать опцию subvol.
Монтируем корень. Сжатие zstd, или lzo.
Создаём директорию и монтируем в неё наш будущий каталог пользователей.
Дальше действуем по вики, т.е. выбираем зеркала и ставим базовую систему. При генерации initramfs mkinitcpio будет ругаться на отсутствие fsck.btrfs — это нормальное явление. Уберём этот хук fsck из конфига, т.к. для Btrfs он не требуется.
Вот данная строка в файле.
И пересоздадим initramfs.
И ещё момент по поводу загрузчика, не знаю как другие, а grub точно умеет грузиться с Btrfs, так что выбрать лучше именно его. Так же не забудьте установить пакет btrfs-progs и позаботиться о бэкапах.
Использование btrfs
Монтируем корень ФС.
Каталоги абсолютно идентичны, и пока мы не начнём изменять файлы, снимки места не занимают.
Откат: грузимся с live CD, монтируем корень ФС и переименовываем подтома. Так же подтома можно переименовать прямо в рабочей системе, если загрузка удачна.
Либо грузимся как обычно, а в меню grub указываем подтом с бэкапом rootflags=subvol=backup .
Копирование при записи (CoW). Если использовать команду cp с ключом —reflink=auto , то копия файла не будет занимать место на диске. И впоследствии, допустим, при изменении скопированного файла, записываться на диск будут только изменённые блоки.
“Онлайн” — проверка ФС. При которой осуществляется чтение всех данных/метаданных с перепроверкой контрольных сумм, при наличии ошибок обнаружение их и исправление по возможности.
Если опустить ключ -B , процесс уйдёт в фон, и о ходе выполнения можно будет узнать командой.
Рекомендуется проводить проверку регулярно (еженедельно). “Оффлайн” — проверка ФС (на отмонтированном разделе). При отсутствии ошибок утилита возвратит 0.
Установка из существующей системы или с live usb
lsblk — подсветить все разделы что бы определиться что монтировать.
Так как Btrfs не может содержать swap-файл, необходимо заранее позаботиться о разделе с подкачкой, если он вам нужен.
Внимание! это отформатирует весь ваш диск, с потерей данных! В данном примере установка идет на весь диск, а не разделы, если вам нужен swap учтите этот момент.
Создадим два подтома под root @ и домашний каталог пользователя @home .
И отмонтируем корень ФС.
Создаём директорию и монтируем в неё наш будущий каталог пользователей.
Устанавливаем базовые пакеты.
Создаем директорию и монтируем boot, если нужно.
Начиная с ядра 5.0 можно создать swap-файл, swap-файл должен располагаться целиком на одном устройстве, создаваться с отключенным COW и сжатием.
Источник
ArchLinux: установка системы на subvolume BTRFS
Опубликовано mfc166 в 01.03.2021 01.03.2021
Всем привет, на связи Уханов. Давно хотел написать заметку про BTRFS, но тема это огромная и когда-нибудь я её закончу. Сегодня же поговорим об установке ArchLinux на subvolume BTRFS. Почему я выбрал именно связку BTRFS + ArchLinux, а не Debian например? Ведь он мне так нравится, это Debian? Я ведь все проекты делаю именно на нём.
Ответ кроется в установщике — программе, которая даёт нам удобный набор инструментов для установки системы, но одновременно ограничивает наши возможности функционалом этих инструментов.
Файловая система BTRFS обладает огромным функционалом и рассказывать о ней можно очень долго. Меня на стадии установки системы интересуют два механизма: поддержка многодисковых конфигураций (multiple device support) и subvolumes. И вот именно на этом, начальном этапе Debian поставил меня в трудное положение: я могу отформатировать в BTRFS диски по-отдельности и никаких мне subvolume.
Потому я решил использовать ArchLinux — там нет инсталлятора и ничто не ограничит полёт фантазии. Приступим: у меня есть виртуальная машина с 4 дисками: их я использую для создания RAID10.
Настройка сети
Установку начнём с определения сетевого адаптера и получения ip адреса. В первом поможет команда
В её выводе мы увидим имя адаптера. В нашем случае это enp0s3. Так и запишем в параметрах dhcpcd
Ура, адрес получили. Настроим время:
Разметка дисков
До начала разбиения дисков, установка ничем не отличается от обычного сценария. А вот при настройке разделов возникают вопросы и было-бы неплохо понять некоторые моменты.
- Форматирование диска в BTRFS без создания разделов. Такой сценарий вполне возможен: вы форматировать в BTRFS диск без создания на нём разделов. Монтировать его будете так-же: без указания номера раздела — просто диск. Используя так называемые partitionless диски вы рискуете столкнуться с проблемами установки на них загрузчика.
- Раздел подкачки использовать необязательно — его можно заменить на файл подкачки. Это обеспечит вам некоторую свободу от отказа диска. В случае, если выйдет из строя диск с разделом подкачки, система завалится с отказом.
- Постарайтесь не выделять /usr в отдельный раздел — проблем будет меньше.
Создание разделов
Для управления разделами я предпочитаю пользоваться программой cfdisk. Быстро и просто создаём по одному разделу на каждом из четырёх наших дисков
Создание файловой системы
У нас есть четыре раздела по одному на диск и пришло время их отформатировать. Нам предстоит создать файловую систему и настроить RAID10. Нам для этого пригодится всего одна команда:
Начнём с подготовки массива под систему: вводим в консоль команду, которая соберёт первые два диска массив уровня RAID1.
Команда возвращает нам результат своей работы. По скриншоту видно, что я использовал ключ -f, что не обязательно в работе. Просто мои диски были ранее уже форматированы в btrfs.
При этом видно, что метаданные в чередовании не участвуют: только зеркалирование.
Создание subvolume
Теперь смонтируем всю эту музыку.
Монтировать BTRFS можно используя любой раздел — участник массива. В нашем случае /dev/sda1.
Перейдём в каталог /mnt
Создадим subvolume для корня системы, домашнего каталога, каталога var и для снапшотов (об этом потом).
Проверим результат командой:
Теперь выйдем из каталога mnt и отмонтируем наш массив командой:
Монтирование и подготовка к установке
Нам предстоит смонтировать subvolume, который мы запланировали как корневой каталог, создать на нём точки монтирования и смонтировать туда остальные subvolume. Монтировать будем с опцией сжатия файловой системы zstd.
Корень есть, создадим точки монтирования одной командой:
Результат можно посмотреть и командой mount и при помощи df.
Установка
Далее в принципе установка проходит штатно и можно ориентироваться на мою прошлую заметку.
После выполнения pacstrap мы получим предупреждения от mkinitcpio.
Не будем игнорировать предупреждения и установим необходимое командой:
И добавим hook btrfs в mkinitcpio.conf:
Последнее отличие будет в установке загрузчика. Нам потребуется установить загрузчик командой:
Она потянет за собой и обычный Grub. Загрузчик устанавливаем по очереди на каждый диск — участник массива. Это позволит загрузить систему в случае выхода из строя любого из них.
Мы установили Archlinux на многодисковую конфигурацию BTRFS с использованием subvolume и уровнем отказоустойчивости RAID10. Главное отличие subvolume от разделов в том, что у них общее пространство и не будет ситуации с нехваткой места на каком-то разделе.
В следующий раз подробнее поговорим о функционале BTRFS и о том, что с ней можно делать.
Источник
Arch linux btrfs установка
Arch installation on a BTRFS root filesystem
This is a cheatsheet with all the instructions to perform an installation of Arch Linux using BTRFS filesystem in /
Please, read the entire document before proceeding because it includes two different approaches. The key is to include /boot directory in the snapshots for root in order to be able to rollback the entire system without any problem it it is needed. Lets proceed!
The installation has been done on a Mountain Onyx laptop.
- Screen: 15,6″ Full HD IPS Mate
- CPU: Intel® Core™ i7 6700HQ — 4C/8T
- RAM: 8GB DDR3L 1600 SODIMM
- Hard Disk: SSD 240GB M.2 550MB/s
- GPU: Nvidia GTX 960M 2GB GDDR5 + Intel i915 (Skylake)
- UEFI
Approach 1 [UEFI, GPT and GRUB]
I have been following Official Arch Installation Guide. Arch ISO booted in UEFI mode using systemd-boot. It was configured a wired connection too.
This is the selected layout for the UEFI/GPT system:
Mount point | Partition | Partition type | FS Type | Bootable flag | Size |
---|---|---|---|---|---|
/boot/efi | /dev/sda1 | EFI System Partition | FAT32 | Yes | 512 MiB |
[SWAP] | /dev/sda2 | Linux swap | SWAP | No | 16 GiB |
/ | /dev/sda3 | Linux | BTRFS | No | 222 GiB |
After creating the partitions using fdisk, it was necessary to format them. Again, I followed the guide without a problem.
IMPORTANT: I used -L option with mkfs command in order to create a label for / (called arch).
The only partition formated with BTRFS was /dev/sda3, which contains the whole root system. BTRFS was selected to enable snapshots support in order to avoid any possible problem with Arch updates. Sometimes, I have experimented that certain critical package updates can break the system. If it occurs, it is a good idea to have some snapshot to rollback the entire root filesystem. tmp subvolume has been created in order to avoid the inclusion of temporal files within the snapshots of rootvol. tmp snapshots never will be created, because all the files stored within tmp are temporal. This is the layout defined:
And these are the commands:
Next, create all the directories needed and mount all the partitions (/boot/efi included) in order to start the installation:
Installing Arch Linux
Proceed with the installation according to the official guide.
After executing genfstab -U /mnt >> /mnt/etc/fstab to generate fstab file using UUIDs for the partitions, I edited fstab in order to remove completely subvolids for example (they are not needed and it makes rollback much more easy) and adding compression to BTRFS mounted points and this is the result. Please, be aware of /mnt/defvol mounting point. This directory is very important because the WHOLE BTRFS volume will be mounted here and you will have access to all subvolumes and snapshots created after the installation)
In order to enable BTRFS on initramfs image, I added btrfs on HOOK inside /etc/mkinitcpio.conf. Then, it was necessary to execute mkinitcpio -p linux again. If you install linux-lts kernel (Long Term Support), you will have to execute mkinitcpio -p linux-lts
I installed intel-ucode package because I have an Intel CPU.
If you want to have BTRFS snapshots integrated from booting you will have to install GRUB. Thanks to grub-btrfs package, you will be able to boot your system directly from any snapshot of ROOT created. All these snapshots will be populated in the GRUB menu.
GRUB is totally compatible with EFI systems. Install grub and efibootmgr:
Install the GRUB EFI application executing this command (please, choose the directory where EFI application will be stored, in my case /boot/efi, the partition created before):
Generate the main grub.cfg configuration file:
Additional packages installed
A bunch of useful packages has been installed too: tlp for energy saving and advanced power management, reflector for optimizing Arch mirrors repositories, yay for compiling and installing packages easily from AUR repository, snapd to install snap packages, btrfs-progs to manage BTRFS filesystem.
Finish the steps in the Wiki
Automated snapshots and system updates
Recently I have developed a graphical tool for creating BTRFS snapshots, balancing filesystems and upgrading the system safetly. It works in Arch Linux and Debian, Ubuntu or derivatives. For more information, please check ButterManager. Please, read the documentation in order to configure it before the first use.
If you prefer another option, I have also created a very simple script called upgrade-system.sh. You can store it within /usr/bin/upgrade-system.sh and it can be invoked for performing system upgrades. Before starting the installation of the packages updated, the script creates a new snapshot. Then, pacman, yay and snapd are launched to upgrade the system. If something went wrong, you can restore the root filesystem using the last snapshot created. This script can be found here
In this folder you can find all the configuration files edited or created during the installation process.
Approach 2 [BIOS,MBR and GRUB]
First, it was necessary to disable UEFI mode and enabling legacy BIOS. Then, I partitioned the system using only two partitions: sda1 for / (including boot partition and home and sda2 for swap. I installed GRUB as a boot loader.
Graphics and Optimus installation
The laptop has two graphic cards: Integrated: Intel i915 and discrete NVIDIA GTX 960M. Then, it is interesting to have optimus technology enabled and working fine. This way, NVIDIA graphics card will only be used when a game is executed, saving power and extending battery life. These are the steps followed to have this technology working on this hardware (it was a little tricky).
++Note:++ For a stable installation, it is recommended a LTS system instead of a cutting edge one. Because of this, I installed linux-lts and linux-lts-headers instead of normal kernel and nvidia-lts and bbswitch-lts from the repository.
For the graphics cards installation and Optimius:
Install video graphic drivers: Intel including vulkan support and bumblebee with NVIDIA
We will add three kernel boot parameters in GRUB. Edit /etc/default/grub and change GRUB_CMDLINE_LINUX_DEFAULT. The line should be like this (I have removed quiet in order to see all the details of the booting process and check that evrything is OK):
The three kernel boot parameters added are:
- Kernel boot parameter for Skylake i915 GPU.
- If you are using kernel 4.8 or higher, add kernel boot parameter pcie_port_pm=off as you can see here for avoiding error «Could not insert ‘nvidia’: No such device»
- Kernel boot parameter acpi_osi=»!Windows 2015″ for avoiding the system freezes when we enable bumblebeed.service.
Finally, execute sudo grub-mkconfig -o /boot/grub/grub.cfg in order to rebuild grub configuration with all these changes.
Add modules intel_agp and i915 (intel_agp must go always before i915) as you can see here within mkinitcpio.conf in order to enable KMS during the initramfs stage. This will avoid a black screen and will prevent the system to freeze. Rebuild initramfs using mkinitcpio -p linux or mkinitcpio -p linux-lts depending on the kernel you have installed.
Install bbswitch for graphic cards power management: sudo pacman -S bbswitch (if you are using linux-lts or custom kernel, bbswitch-dkms is recommended)
Finally, execute lspci and take note of the ID for the NVIDIA card (01:00.1 in my case for example). Edit this file sudo nano /etc/bumblebee/xorg.conf.nvidia and uncomment the line BusID «PCI:01:00:0» writing there the ID you obtained before.
For launching Steam games and use NVIDIA graphics card, open Steam —> Library —> right click on the game you want to launnch —> Set Launch Options -> Type: optirun -b primus %command%
For launching wine games and use NVIDIA graphics card, launch the game with env WINEPREFIX=»/home/egarcia/.wine» /usr/bin/optirun -b primus wine C:\windows\command\start.exe /Unix /home/egarcia/.wine/dosdevices/c:/users/Public/Escritorio/Hearthstone.lnk. Another method is, for example to execute Battle.net with wine, execute de exe file using optirun -b primus wine «C:\Program Files (x86)\Battle.net\Battle.net.exe»
Normally, bluetooth chipset (intel/ibt-11-5.sfi) should work out of the box, but there is a problem loading btusb kernel module. In order to make it work, it is necessary to create a script in /usr/bin called start-bluetooth.sh with this content:
++Tip:++ If you want, you can create a desktop launcher and locate it within
/.local/share/applications with this content:
Problem with Docker and BTRFS
More than a problem is a caveat. If the main filesystem for root is BTRFS, docker will use BTRFS storage driver (Docker selects the storage driver automatically depending on the system’s configuration when it is installed) to create and manage all the docker images, layers and volumes. It is ok, but there is a problem with snapshots. Because /var/lib/docker is created to store all this stuff in a BTRFS subvolume which is into root subvolume, all this data won’t be included within the snapshots. In order to allow all this data be part of the snapshots, we can change the storage driver used by Docker. The preferred one is overlay2 right now. Please, check out this reference in order to select the proper storage driver for you. You must know that depending on the filesystem you have for root, some of the storage drivers will not be allowed.
For using overlay2:
- Install docker
- Create a file called storage-driver.conf within /etc/systemd/system/docker.service.d/. If the directory doens’t exist, create the directory first.
- This is the content of storage-driver.conf
- Create /var/lib/docker/ and disable CoW (copy on write for BTRFS):
- Add your user to docker group in order to use docker command without sudo superpowers!
Pulseaudio high battery consuption
Using Energy Information application provided by KDE Plasma, I realized that pulseaudio daemon was eating the energy of my battery in a very strange way. Then I realized that it was a bug described here. To fix this bug, it is necessary to manually force power save for the audio codec:
Before proceeding, in a terminal launch the following command:
if the result is different from:
then try the following commands
Log out and log in again to get pulseaudio restarted.
No sound over the headphones after suspending
This laptop is a Clevo and there is a known issue about this model: after suspending, there is no sound over the headphones anymore.
To solve this issue:
After this, edit /etc/default/grub and add this flag to GRUB_CMDLINE_LINUX_DEFAULT:
Then, rebuild grub configuration:
Restructuring BTRFS Layout on Antergos or another distribution
- I have installed Antergos (Arch-based distro easy to install and to go without too much configuration) on a PC (using BIOS legacy mode instead UEFI) that I needed to work inmediately. I used BTRFS too for the installation, but the problem is that you cannot choose the layout you want for your BTRFS volume. Instead, all the root system is installed directly in the top volume itself, but I want a more refined layout (the layout defined above) in order to manage all the snapshots in a more proper way. Because of that, I detailed all the steps I made in order to mmigrate my installation to a customize layout. Once the system is installed, reboot and open a terminal to see the structure of the BTRFS volume for /:
Create all the subvolumes on / except rootvol subvolume:
Now, it is necessary to make a read-write snapshot of / into _active/rootvol
Reboot the system using Archlinux LiveCD or Antergos LiveCD. Once the system is booted, mount all the structure within /mnt using as root /_active/rootvol (in my case, / is in /dev/sda1 and /home is in /dev/sdb2):
Chroot the new system:
Add btrfs as HOOK within /etc/mkinitcpio.conf and rebuild images:
Create a new directory called defvol within /mnt
Modify fstab to reflect the changes (remember to modify / entry and point it to /_active/rootvol. Add /tmp line too). It is interesting to add /mnt/defvol in order to mount the entire volume as it is described above too. Systemd sometimes creates /var/lib/machines subvolume so add it too. The fstab file should look like this:
# UUID=238a2358-8bf6-47a9-907f-47eaece88632 /home ext4 defaults,rw,relatime,data=ordered 0 0 UUID=ce5c80f2-9edd-42f6-b920-d8ae43ac461b / btrfs defaults,rw,noatime,compress=lzo,ssd,discard,space_cache,autodefrag,inode_cache,subvol=_active/rootvol 0 0 UUID=ce5c80f2-9edd-42f6-b920-d8ae43ac461b /var/lib/machines btrfs defaults,rw,noatime,compress=lzo,ssd,discard,space_cache,autodefrag,inode_cache,subvol=/var/lib/machines 0 0 UUID=ce5c80f2-9edd-42f6-b920-d8ae43ac461b /mnt/defvol btrfs defaults,rw,noatime,compress=lzo,ssd,discard,space_cache,autodefrag,inode_cache,subvol=/ 0 0 UUID=4621e43f-3b86-4fa2-9d9e-823a564572f4 swap swap defaults 0 0 «>
Reinstall GRUB (in my case, the PC was installed in BIOS legacy mode and GRUB is installed on /dev/sda):
Exit chroot and unmount everything.
Reboot. Once the system is booted, check if / is pointing to /_active/rootvol. If everything is working fine, all the files within the root of the volume can be deleted.
At this point, only _active, _snapshots and var should exist within /mnt/defvol. Go to /mnt/defvol/_active/rootvol and you can safely delete _active and _snapshots:
DONE. 🙂 This is the original post from I got the inspiration to do this stuff.
Do you want to contact me?
About
This is a cheatsheet with all the instructions to perform an installation of Arch Linux using BTRFS filesystem in /
Источник