Установка gentoo на ssd
Author: Jonathan Vasquez (fearedbliss)
Status: This guide is no longer being maintained.
Preface
This guide will show you how to install Gentoo Linux on x86_64 with:
Considerations
Получение Gentoo stage3
Скриншот страницы для получения Gentoo stage3
Раздел "Details (contents, hashes, and signatures)" внизу страницы и ссылка "Stage 3" приведёт нас к странице загрузки автобилдов Gentoo. Оставляю это здесь, потому что это неочевидное место для такой нужно ссылки:
Нам понадобится следующее:
Воспользуемся BASH переменными для удобства и сделаем небольшой скрипт для скачивания stage3 и проверки его подписей:
После получения stage3 архива и перед его использованием - необходимо проверить скачанный архив и его подписи. Рекомендовал бы воспользоваться уже имеющимся скриптом расположенным в проекте Gentoo, но здесь некоторые неудобства вызваны тем, что в RESCUE образе от Hetzner основанном на Debian поставляется mawk вместо gawk. Опции в gawk и mawk отличаются, поэтому проверку будем проводить в chroot окружении.
При желании, можете модифицировать скрипт под опции в скрипте для под mawk и выполнять проверку в Debian. Я это опущу и как описано выше - проверку выполню в chroot окружении Gentoo.
Required Tools
Download the System Rescue CD + ZFS ISO
Linux
We will be creating a UEFI Bootable USB since this guide will be showing you how to install Gentoo Linux on ZFS with UEFI Enabled.
For the following commands, we will assume that your USB is /dev/sdg.
Format the USB
Create the FAT32 Filesystem on the USB
We will now create the FAT32 filesystem on the USB. This needs to be FAT32 since this is the filesystem used in the UEFI Specification.
The label we will use for this partition will be in the following format SYSRCDXYZ, where XYZ is the version number of the System Rescue CD you downloaded.
For example, if you are using System Rescue CD 6.1.6, the label will be SYSRCD616.
Make folders to mount USB and ISO
Mount your USB and your ISO
Copy files over from ISO to USB
And that's it! You now have a Bootable UEFI USB.
Windows
Rufus is the USB Utility I recommend when on Windows. You can Download Rufus here.
- Start Rufus
- Select your USB Device from the Device drop down.
- Select your ISO by clicking SELECT.
- Partition Scheme: MBR
- Target system: BIOS or UEFI
- Volume label: SYSRCD613 (Change last 3 numbers for the version of your System Rescue CD ISO)
- File system: FAT32
- Cluster size: 4096 bytes (Default)
- Click START.
This should be all that's necessary to have a Bootable UEFI USB.
Additional configuration
Partitioning
Sizes of SSD internal data structures (blocks and pages) varies across different devices. Filesystems operates on data structures of different sizes. For optimal performance filesystem data structures should aim not to cross boundaries of underlying SSD internal data structures. Thus effectively minimizing the number of required internal SSD operations. This can be achieved by aligning start of each partition — the common alignment is to 1 MiB.
Both parted and fdisk partitioning utilities support partition alignment. For parted , there is -a optimal option. Recent versions of fdisk should use optimal alignment by default [7] .
It is possible to easily check the alignment for given partition using parted :
For further details about the partitioning, follow dedicated handbook chapter.
blkdiscard
blkdiscard utility from sys-apps/util-linux-2.23 (or later) discards all data blocks on given device.
LVM aligns to MiB boundaries and passes discards to underlying devices by default. No additional configuration is required.
In order to discard all unused space in a Volume Group (VG) use the blkdiscard utility:
Alternatively, there is a discard option in lvm.conf which makes LVM discard entire Logical Volume (LV) on lvremove , lvreduce , pvmove and other actions that free Physical Extents (PE) in a VG.
dm-crypt/LUKS
For discards to pass through encrypted LUKS devices, they have to be opened with the --allow-discards option.
When root-device exists on LUKS, enabling discards depends on the Initramfs implementation. When using genkernel for creating your initramfs, pass the following kernel option:
When using dracut for creating the initramfs, pass the following kernel option:
To evaluate if discard is enabled on a LUKS device, you can check if the output of the following command contains the string allow_discards :
Formatting
Similarly to partitions, performance can be improved if a filesystem is configured the way it can align its data structures with device's internal structures sizes — namely its erase block size.
This configuration gets important in case of a software RAID, when one really should know the erase block size [8] . Consider this information when making your purchase.
Configuring for erase block size
When device's erase block size is known, it can be used when creating a filesystem.
For example for ext4 using mkfs.ext4 on an average-sized partition, it will apply 4KiB blocks [9] . Using -E stride and -E stripe-width options, it is possible to set the alignment to erase block size. Both options should be set as erase block size / block size.
For a drive with 512KiB erase block size, it makes 512KiB / 4KiB = 128:
List of devices with known erase block sizes
- OCZ drives; stride an stripe-width are 128
- Crucial M500 240GB; stride and stripe-width are 2048
Note
Page size is 16KiB, there are 512 pages per block [11] . 16KiB * 512 = 8192KiB for erase block size. 8192KiB / 4KiB = 2048 for stride and stripe-width size.
- SanDisk z400s; stride an stripe-width are 4096
See also
-
— describes the setup of an internal SATA or PATA (IDE) rotational hard disk drive. — flash memory chips connected to a system via the PCI-E bus.
References
- This page was last edited on 23 February 2022, at 14:24.
© 2001–2022 Gentoo Foundation, Inc.
Gentoo is a trademark of the Gentoo Foundation, Inc. The contents of this document, unless otherwise expressly stated, are licensed under the CC-BY-SA-3.0 license. The Gentoo Name and Logo Usage Guidelines apply.
I have 3GB of ram, should I create a swap partition ( if yes, how much ) or not?
edit: Should I use ext2 for the boot partition or ext4? I have an SSD? I know there's not much difference, but I want my system be fast as possible. ( even If it's impossible to see, even if it is 0.000001% faster )
Holy cow, I love gentoo. I learned a lot in a week and I haven't installed the system yet xD
Ya gonna need at least 7GB of RAM to compile certain packages, so go for at least 10GB (RAM+SWAP).
I'm in agreement with this. As for your question update with the boot partition, ext2 if not doing UEFI.
And be careful with the -j setting on make - if you have 4 CPU cores with it set to -j5 and 3GB of RAM, it may starve out on a lot of packages trying to run 5 compile threads that could each be in GB territory.
You probably need a swap partition, but even with one you'll still have trouble compiling large packages like LLVM due to severe lack of RAM. An SSD is the only reasonable place to put your swap partition/file; a hard drive is painfully slow for the kind of random accesses that a swap partition sees.
How big should it be? I have 3GB and I do not intend to use hibernation.
I'm tired so I'll dumb this down a bit mostly to shorten it for myself and do some stupid napkin-level estimates just to give a sense of the scales.
RAM + Swap needs to be able to contain the maximum memory usage of all things you're running or the kernel will start taking processes behind the barn.
The difference in performance between RAM and an SSD is 2-3 orders of magnitude. If we count RAM performance as 100 times the SSD, we can then say that while a computer can perform a task in 2 minutes using RAM it could take (1minute * 1 + 1 minute * 100 = 101 minutes) 1h41m for the same task using half RAM and half swap. Doing a "1 hour" 30GB chrome browser compilation w 3GB RAM + 27GB swap becomes painfully slow.
If the compilation continuously pushes your applications out of RAM so that you're working from swap, your 3 second chrome startup suddenly is 5minutes. You won't like using your computer in this state. Especially if chasing fractions of a percent in speed.
I might be out of date, but with 16GB you should be able to compile everything that's not large enough to be offered as binaries too.
В статье пошагово разберём установку Gentoo в инфраструктуре одного из наверное самых доступных и известных зарубежных хостеров с KVM виртуализацией - Hetzner.
Статья написана с целью описать установку Gentoo с:
шифрованным корневым разделом (LUKS)
без размещения ключа для расшифровки на виртуальной машине.
разблокировка шифрованного раздела только при подключении по SSH до загрузки ОС - как наиболее простой и безопасный способ передачи ключа.
Создание виртуальной машины.
Создание LUKS для корневого раздела ( rootfs ) .
Получение Gentoo stage3.
Настройка и сборка ядра и initramfs.
Boot your system into the ISO
Since this is highly computer dependent, you will need to figure out how to boot your USB on your system and get to the live environment. You may need to disable Secure Boot if that causes your USB to be rejected. Make sure your system BIOS/UEFI is set up to boot UEFI devices, rather than BIOS devices (Legacy).
Confirm that you booted in UEFI Mode
After you booted into the Live CD, make sure that you booted into UEFI mode by typing the following:
If the above directory is empty or doesn't exist, you are not in UEFI mode. Reboot and boot into UEFI mode.
Warning
Continuing the installation without being in UEFI mode will most likely yield an unbootable system. If you want to install in BIOS mode, you will need a different setup.
Настройка ядра:
Устанавливаем символьную ссылку /usr/src/linux на текущую версию ядра:
Используем параметр menuconfig для make при настройки ядра:
Для включения/отключения опции ядра необходимо установить выделение на выбираемом пункте/модуле и используя клавишу обозначить выбор, при этом выделение в нижнем меню
необходимо установить на
Сохранить - для сохранения изменений нужно установить выделение на кнопке в нижнем меню, подтвердить выбор кнопкой Enter на клавиатуре и ещё раз подтвердить название файла сохранения (.config).
Выход - для выхода достаточно установить выделение на кнопке в нижнем меню и подтвердить выбор.
Включаем модуль virtio в ядре:
Включаем dm-crypt:
Включаем поддержку файловых систем ext2 и XFS:
Включаем поддуржку крипто-алгоритмов в ядре:
Cовременные процессоры уже имеют поддержку AES-NI инструкций. Вот список процессоров с поддержкой AES-NI инструкций.
AES-NI инструкции предназначены для ускорения работы приложений использующих шифрование по алгоритму AES.
При включении пунктов, необходимо исходить из того - какие алгоритмы были заданы при создании LUKS раздела командой cryptsetup .
Включаем подписи модулей ядра:
Пункт "Require modules to be validly signed" можно будет включить после успешной загрузки системы, пересобрав ядро. Также этот пункт можно включить через параметры ядра при загрузке. В статье мы это опустим, т.к. подпись, проверка и загрузка подписанных модулей значительно увеличит статью. Но тема отлично описана в документации.
Сборка ядра, модулей и initramfs:
В genkernel мы используем опции для генерации initramfs c запуском SSH на порту 22022, для этого нам понадобился dropbear .
во время загрузки (grub2) воспользуемся другими ключами для SSH сервера, отличных от тех что мы используем в ОС ( /etc/ssh_host__key ).
будут сгенерированы отдельные SSH ключи.
публичную часть ключа используем для исключения MITM. Добавив публичную часть ключа у себя на рабочей машине в ~/.ssh/known_hosts.
положим в initramfs публичную часть нашего SSH ключа для авторизации.
Получаем публичную часть ключа сгенерированного для initramfs . Нужна будет вторая строка с ключом.
Вносим полученный ключ к себе на рабочую машину с которой подключаемся к ВМ в ~/.ssh/known_hosts в формате (необходимо заменить REMOTE_HOST_IP адресом вашего сервера, оставив квадратные скобки):
Задаём пароль для root-a:
Необходимо сохранить пароль в надёжном месте:
Выходим из chroot окружения и перезагружаем ВМ:
Подключение по SSH для разблокировки LUKS:
Виртуальная машина отправлена в reboot и будет доступна по порту 22022 для SSH подключения.
Открываем LUKS раздел:
Продолжаем загрузку Gentoo:
Далее можно подключаться по SSH к системе с Gentoo на 22 порту.
Возможно статья сэкономит времени новичкам и не только, также поможет тем кто знакомится с Linux или Gentoo, начинает создавать виртуалки(контейнеры) на чужом железе(в облаке).
Preface
This guide will show you how to install Gentoo Linux on x86_64 with:
Создание виртуальной машины (ВМ)
Для примера будем использовать ВМ на тарифе CPX11 со следующими параметрами - 2 vCPU (AMD EPYC 2nd Gen), 2GB RAM, 40GB NVMe SSD.
Под спойлером будет несколько скриншотов пошагового создания ВМ, перевода в её в RESCUE режим (режим при котором система будет загружена по PXE).
Создание ВМ в панели Hetzner (пошагово в скриншотах):
Создание ВМ в панели Hetzner. Шаг №1. Создание ВМ в панели Hetzner. Шаг №2. Создание ВМ в панели Hetzner. Шаг №3. Список имющихся ВМ в панели Hetzner. Созданная ВМ в панели Hetzner.
Отправляем ВМ в RESCUE режим. Hetzner использует Debian для RESCUE.
Перевод ВМ в RESCUE. Шаг №1 Перевода ВМ в RESCUE. Шаг №2 Перевод ВМ в RESCUE. Шаг №3
ВМ будет перезагружена в RESCUE по PXE.
Initial setup
Assumptions
- Only installing Gentoo on a single drive (Multiple drives in the same pool should automatically work).
- The /boot pool is featureless and unencrypted.
- The /boot/efi is an unencrypted FAT32 partition as per UEFI spec.
- Your swap partition is outside of ZFS and on a dedicated partition.
- GRUB 2.04+ is being used
- My modified System Rescue CD + ZFS iso is being used.
- bliss-initramfs is being used as your initramfs.
- bliss-kernel is being used as your kernel.
You are free to substitute any of the above for whatever you want. However, support will only be provided from me when the above configuration is used. Also, this guide is the way I install Gentoo, not exactly the way the handbook has it.
External resources
-
— Drives internal structures explained. — Aligning explained by Ted T'so. — ext4 aligning discussion
Discard (trim) support
Device's support of discard (sometimes referred to as trim) should be verified before performing any form of discarding on the drive.
It is possible to use lsblk utility from sys-apps/util-linux:
A device supporting discard has non-zero values in the columns of DISC-GRAN (discard granularity) and DISC-MAX (discard max bytes). In the example listing above, the /dev/sda device supports discard while /dev/sdb does not.
Contents
Установка Gentoo
Распаковываем архив:
Копируем ssh ключ:
Копируем публичный SSH ключ для доступа уже в создаваемую систему после перезагрузки. Публичную часть ключа мы указывали в панели управления Hetzner перед загрузкой виртуальной машины в RESCUE. И пока мы в RESCUE - он раположен по стандартному пути /root/.ssh/authorized_keys
Создаем resolv.conf или можно скопировать из RESCUE системы:
Завершаем подготовку chroot окружения:
Переключаемся в chroot (Gentoo):
Далее следуют операции в chroot окружении Gentoo. Т.е. команды будут выполняться в Gentoo, а не Debian, с которого была загружена ВМ в RESCUE.
Проверяем stage3 архив:
Проверка прошла успешно.
Синхронизируем дерево portage:
Выбираем профиль portage:
Для получения списка доступных профилей выполните:
В статье используем профиль - default/linux/amd64/17.1 (stable), под номером 1.
Указываем часовой пояс:
Добавим немного удобства при сборке в emerge:
-jN - опция для GCC. Указывает во сколько потоков будет проходить компиляция. Руководством рекомендуется использовать на единицу больше от количества доступных ядер/потоков процессора.
--jobs - указывает сколько ставить одновременно пакетов.
--load-average - указывает нагрузку на процессор при превышении которой запуск на установку следующих билдов будет приостановлен.
Т.е. при указанных настройках у вас может быть запущено на сборку 9 копий gcc для различных компонентов пакетов. После завершения сборки одного из пакетов если нагрузка на процессор также не превышает указанного числа, будет запущена установка следующего пакета с возможной параллельной компиляцией тремя копиями gcc.
FEATURES:
Переменная FEATURES содержит список опций portage. Опции влияют на поведение Portage. Является инкрементной переменной, добавление значений в которую не будет переопределять значения из профиля Gentoo.
candy - включает идикатор прогресса при подсчёте зависимостей emerge для сборки пакета.
compress-build-logs - включает сжатие для логов при сборке пакета. Пока поддерживается только gzip сжатие.
parallel-fetch - скачивание необходимых для копиляции компнентов в фоновом режиме.
parallel-install - отключает блокировку при установке пакетов, позволяет запускать одновременно несколько сборок, не дожидаясь завершения запущенной сборки.
Настраиваем локализацию:
Указываем необходимые опции для сборки dropbear, grub2:
Собираем необходимые пакеты:
Настраиваем сеть:
О маршрутизации в Hetzner Cloud.
Для создаваемых ВМ необходимо указывать 172.31.1.1 в качестве маршрута по умолчанию.
Модифицируем файл /etc/fstab под наши нужды.
Т.к. ранее мы указывали LABEL для файловых систем, пришло время их использовать:
Устанавливаем загрузчик GRUB2 на диск /dev/sda :
Закомментируем имеющуюся строку GRUB_CMDLINE_LINUX в /etc/default/grub:
Periodic fstrim jobs
There are multiple ways how to setup a periodic block discarding process. As of 2018, the default recommended frequency is once a week [12] .
Run fstrim on all mounted devices that support discard on a weekly basis:
Similarly, it is possible to run fstrim only for a selected mount point:
SSDcronTRIM
There is also a semi-automatic cron job available on GitHub called SSDcronTRIM which has the following features:
- Distribution independent script (developed on a Gentoo system).
- The script decides every time depending on the disk usage how often (monthly, weekly, daily, hourly) each partition has to be trimmed.
- Recognizes if it should install itself into /etc/cron. , /etc/cron.d or any other defined directory and if it should make an entry into crontab .
- Checks if the kernel meets the requirements, the filesystem is able to and if the SSD supports trimming.
SSDcronTRIM-LUKS
There is also a semi-automatic cron job available on GitHub called SSDcronTRIM-LUKS with dm-crypt/LUKS support.
systemd timer
sys-apps/util-linux on systemd-enabled systems comes with a timer unit executing a weekly fstrim. Enable it with:
Reducing amount of writes
The flash-based SSDs have a limited write lifetime - the number of writes performed [6] . Thus when using a SSD, administrators generally want to reduce the amount of writes.
Portage TMPDIR on tmpfs
When building packages via Portage it is possible to perform the operations on tmpfs and get the tmpfs' benefits. See Portage TMPDIR on tmpfs guide.
Temporal files on tmpfs
Warning
Remember that all data in tmpfs reside in volatile memory. So data on tmpfs will be lost after system reboot, shutdown or crash!
It is possible to mount desired mount points as tmpfs. Since tmpfs stores files in volatile memory all the I/O operations directed to the given mount points are not performed on the solid state disk. This reduces the amount of writes and also improves performance.
This is an example of both /tmp and /var/tmp being mounted as tmpfs:
Warning
/var/tmp will typically also be used by Portage (under the /var/tmp/portage directory). If it is too small, it will lead to build errors. Refer to Portage TMPDIR on tmpfs for appropriately sizing /var/tmp .
XDG cache on tmpfs
When running a Gentoo desktop, many programs, using X Window System (Chromium, Firefox, Skype, etc.) make frequent disk I/O every few seconds to cache [14] .
The cache directory location usually complies to XDG Base Directory Specification [15] , namely to the XDG_CACHE_HOME environment variable. The default cache location is ~/.cache , which is usually mounted on a hard drive and could be moved to tmpfs.
To remap the cache directory location create a script that exports to directory under /tmp :
Warning
if [ $ ]; then is required, so that no /tmp/.cache directory is created by root and apps don't misbehave trying to acquire access the directory.
Warning
Note that making above change may have undesired results for secure programs. For example, the GNOME keyring may not automatically unlock anymore. After making the change, when strange behaviors, review the /var/log/messages file. Messages like the following may be present:
May 5 10:02:52 localhost gnome-keyring-daemon[5561]: couldn't bind to control socket: /home/david/.cache/keyring-hRt5QC/control: No such file or directory
Web browser profile(s) and cache on tmpfs
The web browser profile/s, cache, etc. can be relocated to tmpfs. The corresponding I/O associated with using the browser gets redirected from the SSD drive to tmpfs' volatile memory, resulting in reduced wear to the physical drive and also improving browser speed and responsiveness.
You can relocate the browser components mentioned above with the utility www-misc/profile-sync-daemon:
systemd
Close all the browsers, start and enable the daemon:
Now it is possible to view all symlinks by printing the status of the started daemon:
OpenRC
Next add the users whose browser(s) profile(s) will get symlinked to a tmpfs or another mountpoint in the variable USERS :
Finally, close all the browsers, start and enable the daemon:
Now it is possible to view all symlinks by printing the status of the started daemon:
Introduction
The term Solid State Drive is commonly used for flash-based block devices. Compared to conventional HDD, flash-based technology offers a much faster access time, lower latency, silent operation, power savings (no moving parts), and more. However, the flash-based technology brings a few issues which require some special system attention and care.
Разметка диска
Дожидаемся завершения развертывания ВМ (примерно минуту). Для ВМ будет выделен внишний IP, по нему подключаемся по SSH.
После авторизации нам демонстрируют информацию о нашей виртуальной машине:
Из выводимой информации видим - сить используется Virtio . Нам эта информация понадобится далее при настройке параметров ядра.
Получаем список подключенных дисков их разделов:
Удаляем разметку диска:
Создаём необходимую разметку диска:
Проверям что получилось:
Partition
We will now partition the drive and aim to create the following layout:
Warning
There are many UEFI motherboard firmwares that are extremely buggy. We will attempt to use a 512 MiB FAT32 partition configuration to increase success.
Open up your drive in GNU parted and tell it to use optimal alignment:
Warning
Keep in mind that all of the following operations will affect the disk immediately. GNU parted does not stage changes like fdisk or gdisk.
Всем привет. Сейчас система на 500гб HDD (занято около 20гб). Нужно перенести ее на 120гб SSD. Как это сделать максимально быстро и удобно? Clonzilla не подходит - у нее проблемы с разворачиванием копии бОльшего диска на меньший.
с помощью rsync нельзя скопировать файлы?
Конфигурацию ведра сохрани, и поставь все заново. Хомяка перенесешь. Это более человечно.
cp -av что куда
P.S. ФС отмонтированна, конечно
record ★★★★★ ( 31.12.17 13:15:43 )
Последнее исправление: record 31.12.17 13:16:52 (всего исправлений: 2)
Согласен, но уж очень долго.
Потом, я так понимаю, chroot в перенесенный / и установка GRUB, верно?
Делай всё точно так же, как и при установке Gentoo, только в данном случае заместо распаковки stage3 у тебя просто скопированная уже установленная система и в которой уже установлены все нужные пакеты, нужно только донастроить загрузчик.
Ну и не запутайся и с обычной схемой, /dev/sda1, /dev/sdb1 и т.д.
kostik87 ★★★★★ ( 31.12.17 13:36:18 )
Последнее исправление: kostik87 31.12.17 13:39:00 (всего исправлений: 1)
Да просто потом проблем больше будет. Подумай ещё раз.
Ему сейчас нужно действовать согласно Gentoo Handbook, только вместо распакованного stage3 у него уже собранная система, её нужно скопировать на подготовленные файловые системы ны ssd, затем в соответствии с Gentoo Handbook, опять же, отредактировать /etc/fstab, сделать chroot и прописать загрузчик в MBR, ну либо в соответствие с EFI сделать настройки.
Зачем ему ещё раз собирать систему, если он заменил только накопитель?
В /etc/fstab нужно будет только дописать соответствующие опции монтирования файловых систем для ssd trim.
rsync'ком прекрасно можно переехать.
На заборе тоже написано много, но не всегда так. В идеальной ситуации ты прав. В идеальной.
imul ★★★★★ ( 31.12.17 13:52:20 )
Последнее исправление: imul 31.12.17 13:57:47 (всего исправлений: 2)
Тебе нужен rsync.
Сейчас система на 500гб HDD (занято около 20гб)
Ничо се! Здесь Arch занимает целых 80ГБ
И прежде всего, раздели SSD на партиции с USB Windows. Так нужно.
Допустим, ты написал фигню и не хочешь это признать.
По делу, скажи в чём принципиальное отличие от установки системы с нуля, создания файловых систем, распаковки stage3, последующего chroot, сборки ядра, установки загрузчика, правки конфигурационных файлов, от копирования на те же файловые системы уже установленной системы, chroot`а в неё, правки /etc/fstab и прописывания загрузчика?
У него из специфичного для Gentoo оборудования ничего не изменилось. Процессор тот же, его смена повлияет на CFLAGS, но он не менялся, материнская плата с контроллером жёстких дисков та же, видео карта таже.
В общем, всё оборудование тоже, за исключением накопителя. А это значит, что если он будет собирать систему заново, то в случае, если система у него уже актуальна и при сборке он скопирует /etc/portage/make.conf и прочие конфиги из /etc/portage, а так же /var/lib/portage/world, то после сборки системы он получить абсолютно такую же систему, с теми же оптимизациями под процессор и такими же USE флагами.
Так что смысла собирать систему нет.
Разве что только сравнить некоторое незначительное изменение сборки пакетов из-за более производительных дисковых операций на SSD по сравнению с HDD.
Так что никаких объектиных причин собирать систему заново против простого копирования уже собранной, с сохранением прав доступа и последующей правки конфигов нет.
Если ты этого не понимаешь, то это твоя проблема.
Удачи в новом году.
Надо записывать UUID партиций заранее на бумажку.
Особенно /boot и /root.
Потом, я так понимаю, chroot в перенесенный / и установка GRUB, верно?
Необязательно так.
Если hdd и ssd - диски на одной матплате (а не в сети и т.п.),
можно настроить grub, как обычно это делается после обновлении ядра в старой системе на hdd. Найдутся все системы, если их несколько.
Запись о загрузке с sdd появится в меню grub.
grub-mkconfig -o /boot/grub/grub.cfg
grub-install -v --recheck /dev/sdX
P.S. Потом, загрузившись в новую систему, снова можно настроить grub.
record ★★★★★ ( 31.12.17 14:08:31 )
Последнее исправление: record 31.12.17 14:14:02 (всего исправлений: 4)
This article provides guidelines for basic maintenance, such as enabling discard/trim support, for SSDs (Solid State Drives) on Linux. It presumes the user has a basic understanding of partitioning and formatting disk drives.
Slowing wear out
Each write operation performed on a NAND flash cell causes its wear. This fact limits the SSD lifespan. The cell endurance varies with used technology [6] . On the other hand, read operations are straightforward and do not cause cell wear.
A basic method increasing SSD lifespan is to uniformly distribute writes across all the blocks. This method is called wear leveling and is deployed via SSD firmware.
From system point of view, it is appropriate to generally reduce amount of writes.
Создание LUKS раздела и файловых систем
Подключаем модуль ядра для работы с LUKS:
Создаем файловую систему для раздела /boot .
В этом разделе будут расположены grub2, ядро и initramfs.
В качестве файловой системы - используем ext2, активно писать в этот раздел не планируем, поэтому нет необходимости в журналировании:
Создаём секретный ключ, желательно НЕ на виртуальной машине которую разворачиваем. Не забывам сохранить у себя в надёжном месте.
Утилита сryptsetup c опцией benchmark помогает определить наиболее производительный алгоритм шифрования:
По результатам бенчмарка AES заметно опережает остальных. Мы будем использовать aes-xts с размером ключа 512 бит.
При создании потребуется ввести подтверждение заглавными буквами - YES, только затем уже ввести ключ/пароль для раздела.
Создание LUKS раздела с AES-XTS шифрованием:
Открываем LUKS том для установки системы (Gentoo):
Дополняем LUKS том необходимыми опциями для работы с SSD:
Добавляем в LUKS раздел allow-discard , чтобы функция TRIM передавалась по направлению Filesystem -> LUKS -> Disk(sda)
Указываем метки (LABEL) для файловых систем.
Это нам понадобится для удобства работы с fstab.
указание метки для раздела /boot с ext2 :
указание метки для корневого раздела / с xfs.
если для ext2 можно указать LABEL без размонтирования раздела, то для xfs так не получится, поэтому лучше указать метку сразу:
Проверяем получившуюся разметку диска с разделами:
Создаём необходимые директории и монтирируем разделы:
Dealing with empty blocks
Generally, traditional filesystems do not erase deleted data blocks but only flags them as such. Due to nature of flash memory cells any write operation has to be done to empty cells only. Thus writing to physically non-empty cells, flagged as deleted by a filesystem, requires their erasure which makes the operation slower than writing to empty cells. This problem is further amplified by hardware limitations.
For modern kernels it is possible to hint the deleted (not-used) data blocks to SSD. The described mechanism is called discard. Names of implementations differ — TRIM for ATAPI and UNMAP for SCSI. Filesystem's support is required in order to use discard. Majority of modern filesystems (like Ext4 [1] , XFS [2] or Btrfs [3] ) support discard. Also there are filesystems developed primarily for flash-based devices, such as F2FS.
There are two basic approaches to issue the discard command — using mount discard option ( -o discard ) for continuous discard [4] or periodic calls of fstrim utility [5] .
Mounting
For rootfs it is usually recommended to periodically use fstrim utility. Using the discard mount option results in continuous discard that could potentially cause degradation of older or poor-quality SSDs [5] .
The following command can be used manually or be setup as a periodic job to run once a week [12] :
Note
On a btrfs system, running the fstrim command on any mounted subvolume will perform the discard command on the device.
For mount points with a low amount of disk writes occurring on a SSD it should be safe to use the discard mount option in /etc/fstab . Also it is recommended to use the mount option when maintaining performance is required [13] .
Given the considerations above, a discard-enabled /etc/fstab could look like this:
Once the /etc/fstab has been modified, remount all filesystems mentioned there via:
Читайте также: