Linux проверка целостности данных

fsck (Русский)

Состояние перевода: На этой странице представлен перевод статьи fsck. Дата последней синхронизации: 10 июля 2021. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

fsck (file system check) — утилита для проверки и восстановления файловых систем Linux. Проверка файловых систем разных физических дисков выполняется параллельно, что позволяет значительно её ускорить (см. fsck(8) ).

Процесс загрузки Arch включает в себя процедуру fsck, поэтому проверка файловых систем на всех носителях выполняется автоматически при каждой загрузке. По этой причине обычно нет необходимости выполнять её через командную строку.

Проверка при загрузке

Механизм

Существует два возможных варианта:

  1. mkinitcpio предоставляет хук fsck для проверки корневой файловой системы перед монтированием. Корневой раздел должен быть смонтирован на запись и чтение (параметр ядра rw ) [1].
  2. systemd проверяет все файловые системы, которым задано значение fsck больше 0 (либо параметром fstab, либо в пользовательском файле юнита). Корневая файловая система изначально должна быть смонтирована только на чтение (параметр ядра ro ), и лишь позже перемонтирована на чтение-запись в fstab. Имейте в виду, что опция монтирования defaults подразумевает rw .

Рекомендуется по умолчанию использовать первый вариант. Если вы устанавливали систему в соответствии с руководством, то использоваться будет именно он. Если вы хотите вместо этого использовать вариант 2, то удалите хук fsck из mkinitcpio.conf и задайте параметр ядра ro . Кроме того, параметром ядра fsck.mode=skip можно полностью отключить fsck для обоих вариантов.

Принудительная проверка

Если вы используете base -хук mkinitcpio, то можно принудительно выполнять fsck во время загрузки, задав параметр ядра fsck.mode=force . Проверена будет каждая файловая система на машине.

В качестве альтернативы можно воспользоваться службой systemd systemd-fsck@.service(8) , которая проверит все настроенные файловые системы, которые не были проверены в initramfs. Тем не менее, проверка корневой файловой системы этим способом может стать причиной задержки в время загрузки, поскольку файловая система будет перемонтироваться.

Примечание: Если вы используете другие дистрибутивы GNU/Linux, то учтите, что старые методы проверки вроде файлов forcefsck для каждой файловой системы или команды shutdown с флагом -F будут работать только с SysVinit и ранними версиями Upstart; работать с systemd они не будут. Решение, предложенное выше, является единственным рабочим для Arch Linux.

Читайте также:  Flashrom как пользоваться linux

Советы и рекомандации

Восстановление повреждённых блоков

Следующая команда позволяет восстановить повреждённые участки файловых систем ext2/ext3/ext4 и FAT:

Важно: Разрешение на восстановление запрошено не будет. Подразумевается, что вы уже ответили «Да», запустив команду на выполнение.

Интерактивное восстановление повреждённых блоков

Полезно в том случае, если файлы на загрузочном разделе были изменены, а журнал не обновился соответствующим образом. В этом случае размонтируйте загрузочный раздел и выполните:

Изменение частоты проверки

Примечание: Команды tune2fs и dumpe2fs работают только с файловыми системами ext2/ext3/ext4.

По умолчанию fsck проверяет файловую систему каждые 30 загрузок (вычисляется отдельно для каждого раздела). Чтобы изменить частотку проверок, выполните:

Здесь 20 — число загрузок между проверками. Если задать значение 1 , то проверка будет выполняться при каждой загрузке, а значение 0 отключит сканирование.

Текущую частоту проверок и опции монтирования конкретного раздела можно узнать командой:

# dumpe2fs -h /dev/sda1 | grep -i 'mount count'

Параметры fstab

fstab — файл системных настроек, который используется для передачи ядру Linux информации о том, какие разделы (файловые системы) монтировать и в какие точки дерева файловой системы.

Записи в /etc/fstab выглядят примерно следующим образом.

/dev/sda1 / ext4 defaults 0 1 /dev/sda2 /other ext4 defaults 0 2 /dev/sda3 /win ntfs-3g defaults 0 0 

Шестое поле каждой строки (выделено) — опция fsck:

  • 0 — не проверять.
  • 1 — файловая система (раздел), которая должна быть проверена первой; для корневого раздела ( / ) должно использоваться именно это значение.
  • 2 — прочие файловые системы, которые должны быть проверены.

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

Не запускается fsck для отдельного раздела /usr

  1. Убедитесь, что используются соответствующие хуки в /etc/mkinitcpio.conf , а также что вы не забыли пересоздать initramfs после последнего редактирования этого файла.
  2. Проверьте fstab! Только корневому разделу должен быть задан параметр 1 в последнем поле, все остальные разделы должны иметь либо 2 , либо 0 . Также проверьте файл на наличие иных опечаток.

ext2fs: no external journal

Иногда (например, из-за внезапного отключения питания) файловые системы ext(3/4) могут повредиться так сильно, что восстановить их обычным способом не удастся. Как правило, при этом fsck выводит сообщение о том, что не удалось найти журнал (no external journal). В этом случае выполните команды ниже.

Отмонтируйте раздел от соответствующего каталога:

Запишите на раздел новый журнал:

Запустите fsck, чтобы восстановить раздел:

Источник

fsck

fsck stands for «file system check» and it is used to check and optionally repair one or more Linux file systems. Normally, the fsck program will try to handle file systems on different physical disk drives in parallel to reduce the total amount of time needed to check all of the file systems (see fsck(8) ).

Читайте также:  Vbox linux additions debian

The Arch Linux boot process conveniently takes care of the fsck procedure for you and will check all relevant partitions on your drive(s) automatically on every boot. Hence, there is usually no need to resort to the command-line.

Boot time checking

Mechanism

There are two players involved:

  1. mkinitcpio offers you the option to fsck your root file system before mounting it via the fsck hook. If you do this, you should mount root read-write via the appropriate rw kernel parameter.[1]
  2. systemd will fsck all file systems having a fsck pass number greater than 0 (either with #fstab options or a user-supplied unit file). For the root file system, it also has to be mounted read-only initially with the kernel parameter ro and only then remounted read-write from fstab (note that the defaults mount option implies rw ).

The first option is the recommended default, and what you will end up with if you follow the Installation guide. If you want to go with option 2 instead, you should remove the fsck hook from mkinitcpio.conf and use ro on the kernel command-line. The kernel parameter fsck.mode=skip can be used to make sure fsck is disabled entirely for both options.

Forcing the check

If you use the base mkinitcpio hook, you can force fsck at boot time by passing fsck.mode=force as a kernel parameter. This will check every file system you have on the machine.

Alternatively, systemd provides systemd-fsck@.service(8) , which checks all configured file systems, which were not checked in the initramfs. However, checking the root file system this way causes a delay in the boot process, because the file system has to be remounted.

This article or section needs expansion.

Note: For those accustomed to use other GNU/Linux distributions, the old tricks consisting in writing a file with the name forcefsck to the root of each file system or using the command shutdown with the -F flag were only working for the old SysVinit and early versions of Upstart and are not working with systemd. The aforementioned solution is thus the only one working for Arch Linux.

Automatically answer yes to all repair questions

The boot time fsck checks might end up saying «UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY.»

This happens when you need to apply some changes to fix the file system which are not considered completely safe, and thus require fsck to be run manually.

You can set fsck to automatically apply all suggested change (i.e. answer yes to all questions) by setting the fsck.repair kernel command line option to yes . (Other possible values are no and preen .) Check the documentation systemd-fsck@.service(8) for the meaning of these options.

Читайте также:  Shared memory linux api

Tips and tricks

Attempt to repair damaged blocks

To automatically repair damaged portions of an ext2/ext3/ext4 or FAT file system, run:

Warning: This will not ask if you want to repair it, as the answer is Yes when you run it.

Repair damaged blocks interactively

This is useful for when files on the boot partition have changed, and the journal failed to properly update. In this case, unmount the boot partition, and run the following code to repair damaged portions:

Changing the check frequency

Note: The following commands tune2fs and dumpe2fs work only with ext2/ext3/ext4 file systems.

By default, fsck checks a file system every 30 boots (counted individually for each partition). To change the frequency of checking, run:

In this example, 20 is the number of boots between two checks.

Note that 1 would make it scan at every boot, while 0 would stop scanning altogether.

If you wish to see the frequency number and the current mount count for a specific partition, use:

# dumpe2fs -h /dev/sda1 | grep -i 'mount count'

fstab options

fstab is a system configuration file and is used to tell the Linux kernel which partitions (file systems) to mount and where on the file system tree.

A typical /etc/fstab entry may look like this:

/dev/sda1 / ext4 defaults 0 1 /dev/sda2 /other ext4 defaults 0 2 /dev/sda3 /win ntfs-3g defaults 0 0 

The 6th column (in bold) is the fsck option.

  • 0 — do not check.
  • 1 — first file system (partition) to check; / (root partition) should be set to 1 .
  • 2 — all other file systems to be checked.

Troubleshooting

Can’t run fsck on a separate /usr partition

  1. Make sure you have the required hooks in /etc/mkinitcpio.conf and that you remembered to re-generate your initramfs image after editing this file.
  2. Check your fstab! Only the root partition needs 1 at the end, everything else should have either 2 or 0 . Carefully inspect it for other typos, as well.

ext2fs: no external journal

There are times (due to power failure) in which an ext(3/4) file system can corrupt beyond normal repair. Normally, there will be a prompt from fsck indicating that it cannot find an external journal. In this case, run the following commands:

Unmount the partition based on its directory

Write a new journal to the partition

# tune2fs -j /dev/partition 

Run an fsck to repair the partition

Источник

Оцените статью
Adblock
detector