What is superblock linux
Первый элемент этой структуры (суперблок) — одинаков для всех групп, а все остальные — индивидуальны для каждой группы. Суперблок хранится в первом блоке каждой группы блоков (за исключением группы 1, в которой в первом блоке расположена загрузочная запись). Суперблок является начальной точкой файловой системы. Он имеет размер 1024 байта и всегда располагается по смещению 1024 байта от начала файловой системы. Наличие нескольких копий суперблока объясняется чрезвычайной важностью этого элемента файловой системы. Дубликаты суперблока используются при восстановлении файловой системы после сбоев.
Информация, хранимая в суперблоке, используется для организации доступа к остальным данным на диске. В суперблоке определяется размер файловой системы, максимальное число файлов в разделе, объем свободного пространства и содержится информация о том, где искать незанятые участки. При запуске ОС суперблок считывается в память и все изменения файловой системы вначале находят отображение в копии суперблока, находящейся в ОП, и записываются на диск только периодически. Это позволяет повысить производительность системы, так как многие пользователи и процессы постоянно обновляют файлы. С другой стороны, при выключении системы суперблок обязательно должен быть записан на диск, что не позволяет выключать компьютер простым выключением питания. В противном случае, при следующей загрузке информация, записанная в суперблоке, окажется не соответствующей реальному состоянию файловой системы.
Суперблок имеет следующую структуру.
Название поля | Тип | Комментарий |
1.2em s_inodes_count | ULONG | Число индексных дескрипторов в файловой системе |
s_blocks_count | ULONG | Число блоков в файловой системе |
s_r_blocks_count | ULONG | Число блоков, зарезервированных для суперпользователя |
s_free_blocks_count | ULONG | Счетчик числа свободных блоков |
s_free_inodes_count | ULONG | Счетчик числа свободных индексных дескрипторов |
s_first_data_block | ULONG | Первый блок, который содержит данные. В зависимости от размера блока, это поле может быть равно 0 или 1 |
s_log_block_size | ULONG | Индикатор размера логического блока: 0 = 1 Кб; 1 = 2 Кб; 2 = 4 Кб |
s_log_frag_size | LONG | Индикатор размера фрагментов (кажется, понятие фрагмента в настоящее время не используется) |
s_blocks_per_group | ULONG | Число блоков в каждой группе блоков |
s_frags_per_group | ULONG | Число фрагментов в каждой группе блоков |
s_inodes_per_group | ULONG | Число индексных дескрипторов (inodes) в каждой группе блоков |
s_mtime | ULONG | Время, когда в последний раз была смонтирована файловая система |
s_wtime | ULONG | Время, когда в последний раз производилась запись в файловую систему s_mnt_count USHORT Счетчик числа монтирований файловой системы. Если этот счетчик достигает значения, указанного в следующем поле ( s_max_mnt_count ), файловая система должна быть проверена (это делается при перезапуске), а счетчик обнуляется |
s_max_mnt_count | SHORT | Число, определяющее, сколько раз может быть смонтирована файловая система |
s_magic | USHORT | «Магическое число» ( 0xEF53 ), указывающее, что файловая система принадлежит к типу ex2fs |
s_state | USHORT | Флаги, указывающее текущее состояние файловой системы (является ли она чистой ( clean ) и т.п.) |
s_errors | USHORT | Флаги, задающие процедуры обработки сообщений об ошибках (что делать, если найдены ошибки) |
s_pad | USHORT | Заполнение s_lastcheck ULONG Время последней проверки файловой системы |
s_checkinterval | ULONG | Максимальный период времени между проверками файловой системы |
s_creator_os | ULONG | Указание на тип ОС, в которой создана файловая система |
s_rev_level | ULONG | Версия (revision level) файловой системы |
s_reserved | ULONG[235] | Заполнение до 1024 байт |
Next: Group Descriptors Up: Структура дискового раздела ext2 Previous: Структура дискового раздела ext2 Contents Index Alex Otwagin 2002-12-16
Источник
Superblock Definition
A superblock is a record of the characteristics of a filesystem, including its size, the block size, the empty and the filled blocks and their respective counts, the size and location of the inode tables, the disk block map and usage information, and the size of the block groups.
The term filesystem can refer to an entire hierarchy of directories, or directory tree, that is used to organize files on a computer system. On Unix-like operating systems, the directories start with the root directory (designated by a forward slash), which contains a series of subdirectories, each of which, in turn, contains further subdirectories, etc. A variant of this definition is the part of the entire hierarchy of directories (or of the directory tree) that is located on a single disk or partition. A partition is a logically independent section of a hard disk drive (HDD) that contains a single type of filesystem.
An inode is a data structure on a filesystem on a Unix-like operating system that stores all the information about a file except its name and its actual data. A data structure is a way of storing data so that it can be used efficiently; different types of data structures are suited to different types of applications, and some are highly specialized for specific types of tasks.
A request to access any file requires access to the filesystem’s superblock. If its superblock cannot be accessed, a filesystem cannot be mounted (i.e., logically attached to the main filesystem) and thus files cannot be accessed. Any attempt to mount a filesystem with a corrupted or otherwise damaged superblock will likely fail (and usually generate an error message such as can not read superblock).
Because of the importance of the superblock and because damage to it (for example, from physical damage to the magnetic recording medium on the disk) could erase crucial data, backup copies are created automatically at intervals on the filesystem (e.g., at the beginning of each block group). For each mounted filesystem, Linux also maintains a copy of its superblock in memory.
An ext2 filesystem, the basic Linux filesystem type, is divided into block groups, each of which contains, by default, 8192 blocks. The default block size on the same filesystem is 4096 bytes.
Thus there are backup copies of the superblock at block offsets 8193, 16385, 24577, etc. If the ext2 filesystem is used, that the filesystem has block groups each comprised of 8192 blocks can be confirmed with the dumpe2fs command as follows:
device_name is the name of the partition on which the filesystem resides. The output of dumpe2fs is piped (i.e., sent) to the less command because it can be long and thus in order to read it one screenful at a time. It can be seen that dumpe2fs also provides a great deal of additional information about the filesystem, including the block size.
For example, the following will provide the location of the primary and backup superblocks on the first partition of the first HDD:
On most systems it will be necessary to be the root user (i.e., administrative user) in order to use dumpe2fs. On home computers and other systems for which the user has access to the root password, that user can become root by issuing the su (i.e., substitute user) command and then supplying the password as prompted. It will also likely be necessary to use the full pathname of dumpe2fs by adding /sbin to its beginning, i.e.,
If a filesystem cannot be mounted because of superblock problems, it is likely that e2fsck, and the related fsck command, which are used to check and repair the filesystem, will fail as well, at least initially. Fortunately, however, e2fsck can be instructed to use one of the superblock copies instead by issuing a command similar to the following:
e2fsck -f -b block_offset device
block_offset is the offset to a superblock copy, and it is usually 8193. The -f option is used to force e2fsck to check the filesystem. When using superblock backup copies, the filesystem may appear to be clean, in which case no check is needed, but -f overrides this. For example, to check and repair the filesystem on /dev/hda2 (i.e., the second partition of the first HDD) if it has a defective superblock, the following can be used:
This command can be executed from an appropriate emergency floppy disk, and it is possible that it will allow the designated filesystem to be mounted again.
The equivalent to the superblock on Microsoft Windows filesystem is the file allocation table (FAT), which records which disk blocks hold the topmost directory. On Unix-like operating systems the superblock is virtually always held in memory, whereas it is not for older operating systems such as MS-DOS.
The superblock acquired its name from the fact that the first data block of a disk or of a partition was used to hold the meta-data (i.e., data about data) about the partition itself. Superblock are now independent of the concept of the data block, but it remains the data structure that holds information about each mounted filesystem.
Created August 14, 2005.
Copyright © 2005 The Linux Information Project. All Rights Reserved.
Источник
Understanding UNIX / Linux filesystem Superblock
This is second part of “Understanding UNIX/Linux file system”, part I is here. Let us take an example of 20 GB hard disk. The entire disk space subdivided into multiple file system blocks. And blocks used for what?
Unix / Linux filesystem blocks
The blocks used for two different purpose:
- Most blocks stores user data aka files (user data).
- Some blocks in every file system store the file system’s metadata. So what the hell is a metadata?
In simple words Metadata describes the structure of the file system. Most common metadata structure are superblock, inode and directories. Following paragraphs describes each of them.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Superblock
Each file system is different and they have type like ext2, ext3 etc. Further each file system has size like 5 GB, 10 GB and status such as mount status. In short each file system has a superblock, which contains information about file system such as:
- File system type
- Size
- Status
- Information about other metadata structures
If this information lost, you are in trouble (data loss) so Linux maintains multiple redundant copies of the superblock in every file system. This is very important in many emergency situation, for example you can use backup copies to restore damaged primary super block. Following command displays primary and backup superblock location on /dev/sda3:
# dumpe2fs /dev/hda3 | grep -i superblock
Output:
Continue reading rest of the Understanding Linux file system series (this is part II):
- Part I – Understanding Linux superblock
- Part II – Understanding Linux superblock
- Part III – An example of Surviving a Linux Filesystem Failures
- Part IV – Understanding filesystem Inodes
- Part V – Understanding filesystem directories
- Part VI – Understanding UNIX/Linux symbolic (soft) and hard links
- Part VII – Why isn’t it possible to create hard links across file system boundaries?
Источник
Что такое суперблок, инод, дентри и файл?
Из статьи Анатомия файловой системы Linux М. Тима Джонса я прочитал, что Linux рассматривает все файловые системы с точки зрения общего набора объектов, и это объекты суперблок , inode , dentry и файл . Несмотря на то, что остальная часть параграфа объясняет вышеизложенное, мне не очень понравилось это объяснение.
Может ли кто-нибудь объяснить мне эти термины?
Прежде всего, и я понимаю, что это не был один из терминов из вашего вопроса, вы должны понимать метаданные . Вкратце и украденные из Википедии, метаданные — это данные о данных. То есть метаданные содержат информацию о части данных. Например, если я владею автомобилем, у меня есть набор информации об автомобиле, который не является частью самого автомобиля. Информация, такая как регистрационный номер, марка, модель, год выпуска, информация о страховке и так далее. Вся эта информация в совокупности называется метаданными. Как вы увидите, в файловых системах Linux и UNIX метаданные существуют на нескольких уровнях организации.
Суперблок , по существу , метаданные файловой системы и определяет тип файловой системы, размера, состояние, а также информации о других структурах метаданных (метаданные метаданных). Суперблок очень важен для файловой системы и поэтому хранится в нескольких избыточных копиях для каждой файловой системы. Суперблок — это структура метаданных очень высокого уровня для файловой системы. Например, если суперблок раздела / var становится поврежденным, то рассматриваемая файловая система (/ var) не может быть смонтирована операционной системой. Обычно в этом случае вам нужно запустить fsck который автоматически выберет альтернативную резервную копию суперблока и попытается восстановить файловую систему. Сами резервные копии хранятся в группах блоков, распределенных по файловой системе, причем первые хранятся со смещением в 1 блок от начала раздела. Это важно в случае необходимости ручного восстановления. Вы можете просмотреть информацию о резервном копировании суперблока с помощью команды, dumpe2fs /dev/foo | grep -i superblock которая полезна в случае попытки восстановления вручную. Предположим, что команда dumpe2fs выводит строку Backup superblock at 163840, Group descriptors at 163841-163841 . Мы можем использовать эту информацию, а также дополнительные знания о структуре файловой системы, чтобы попытаться использовать эту резервную копию суперблока: /sbin/fsck.ext3 -b 163840 -B 1024 /dev/foo . Обратите внимание, что для этого примера я принял размер блока 1024 байта.
Инода существует, или, файловую систему и представляет собой метаданные о файле. Для ясности все объекты в системе Linux или UNIX являются файлами; актуальные файлы, каталоги, устройства и так далее. Обратите внимание, что среди метаданных, содержащихся в inode, нет имени файла, как думают люди, это будет важно позже. Inode содержит по существу информацию о владельце (пользователь, группа), режиме доступа (права на чтение, запись, выполнение) и типе файла.
Dentry это клей , который держит дескрипторы и файлы вместе, связывая номер индексных дескрипторов файлов с именами файлов. Dentries также играют роль в кэшировании каталогов, что в идеале позволяет хранить наиболее часто используемые файлы для быстрого доступа. Обход файловой системы является еще одним аспектом dentry, поскольку он поддерживает связь между каталогами и их файлами.
Файл , в дополнение к тому , что люди , как правило , думают о том, когда представлены слова, на самом деле просто блок логически связанных произвольных данных. Сравнительно очень скучно, учитывая всю работу, проделанную (выше), чтобы отслеживать их.
Я полностью понимаю, что несколько предложений не дают полного объяснения какой-либо из этих концепций, поэтому, пожалуйста, не стесняйтесь спрашивать дополнительные детали, когда и где это необходимо.
Источник