Inode numbers in linux

Everything You Need to Know About inodes in Linux

What is inode in Linux? What is it used for? Why is it important and how to check inode in Linux? This guide explains all the important aspects of inodes.

I have a strange question for you.

Has your Linux system ever complained that you had no space left while you clearly still have more than enough?

It happened to me, that I had many GB left, but my Linux system complained that no space was left. This is when I learned about inodes.

inodes in brief

Inodes stores metadata for every file on your system in a table-like structure usually located near the beginning of a partition. They store all the information except the file name and the data.

Every file in a given directory is an entry with the filename and inode number. All other information about the file is retrieved from the inode table by referencing the inode number.

Inodes numbers are unique at the partition level. Every partition has its own inode table.

If you run out of inodes, you cannot create new files even if you have space left on the given partition.

What is inode in Linux?

Inode stands for Index Node. Although history is not quite sure about that, it is the most logical and best guess they came up with. It used to be written I-node, but the hyphen got lost over time.

An inode is a data structure … … that stores all the information about a file except its name and its actual data.

Inodes stores metadata about the file it refers to. This metadata contains all the information about the said file.

  • Size
  • Permission
  • Owner/Group
  • Location of the hard drive
  • Date/time
  • Other information

Every used inode refers to 1 file. Every file has 1 inode. Directories, character files, and block devices are all files. They each have 1 inode.

For each file in a directory, there is an entry containing the filename and the inode number associated with it.

Inodes are unique at the partition level. You can have two files with the same inode number given they are on different partitions. Inodes information is stored in a table-like structure in the strategic parts of each partition, often found near the beginning.

How to check inode in Linux?

You can easily list the inodes number with the following command:

The following pictures show my root directory with corresponding inode numbers.

displaying inode numbers in Linux

The amount of inodes each file system has is decided when you create the filesystem. For most users, the default number of inodes is more than sufficient.

The default setting when creating a filesystem will create 1 inode per 2K bytes of space. This gives plenty of inodes for most systems. You will more than likely run out of space before you run out of inodes. If need be, you can specify how many inodes to create when creating a file system.

Читайте также:  Streaming linux to android

If you run out of inodes, you will be unable to create new files. Your system will also be unable to do so. This is not a situation most users will encounter but it is possible.

For example, a mail server will store a huge amount of very small files. Lots of those files will be below 2K bytes. It is also expected to grow constantly. Therefore a mail server is at risk of running out of inodes way before running out of space.

Some file systems like Btrfs, JFS, XFS have implemented dynamic inodes. They can increase the number of inodes available if needed.

How does inode work?

When a new file is created, it is assigned an inode number and a file name. An inode number is a unique number within that file system. Both name and inode number are stored as entries in a directory.

When I ran the ls command “ls -li /” the file name and inodes number are what was stored in the directory /. The remaining information user, group, file permissions, size, etc was retrieved from the inode table using the inode number.

You can list inode information for each file system with the df command in Linux:

A soft link or symbolic link is a well-known feature of Linux. But what happens with Inodes when you create a symbolic link in Linux? In the next picture I have a directory called “dir1“, a file named “file1” and inside “dir1” I have a soft link called “slink1” which points to “../file1

Now I can list recursively and show the inode information.

As expected, dir1 and file1 have different inode numbers. But so does the soft link. When you create a soft link, you create a new file. In its metadata, it points to the target. For every soft link you create, you use one inode.

After creating a hard link in dir1 with the ln command:

Listing of inodes number gives me the following information:

You can see that “file1″ and “hlink1” have the same inode number. Truthfully, hard links are possible because of inodes. A hard link does not create a new file. It only provides a new name for the same data.

In older versions of Linux, it was possible to hard link a directory. It was even possible to have a given directory be its own parent. This was made possible because of inode implementation. This is now restricted to prevent users from creating a very confusing structure of directories.

Other implications of inodes

The way inodes work is also why it is impossible to create a hard link across the different file systems. Allowing such a task would open the possibility of having conflicting inode numbers. A soft link on the other hand can be created across the different file systems.

Because a hard link has the same inode number as the original file, you can delete the original file and the data is still available through the hard link. All you did, in this case, is remove one of the names pointing to this inode number. The data linked to this inode number will remain available until all names associated with it are deleted.

Читайте также:  Remove linux with windows

Inodes are also a big reason why a Linux system can update without the need to reboot. This is because one process can use a library file while another process replaces that file with a new version. Therefore, creating a new inode for the new file. The already running process will keep using the old file while every new call to it will result in using the new version.

Another interesting feature that comes with inodes is the ability to store the data in the inode itself. This is called Inlining. This storing method has the advantage of saving space because no data block will be needed. It also increases the lookup time by avoiding more disk access to get the data.

Some file system like ext4 has an option called inline_data. When enabled, it allows the operating system to store data this way. Due to size limitations, inlining only works for very small files. Ext2 and later will often store soft link information this way. That is if the size is no more than 60 Bytes.

Inodes are not something you interact directly with, but they play an important role. If a partition is to contain many very small files, like a mail server, knowing what they are and how they work can save you a lot of problems down the road.

I hope you liked this article and learned something new and important about inode in Linux. Subscribe to our website to learn more Linux-related information.

Источник

Что такое Inode

Inode — это структура данных в которой хранится информация о файле или директории в файловой системе. В файловой системе Linux, например Ext4, у файла есть не только само его содержимое, например, тот текст, но и метаданные, такие как дата создания, доступа, модификации и права. Вот эти метаданные и хранятся в Inode. У каждого файла есть своя уникальная Inode и именно здесь указано в каких блоках находятся данные файла.

Это довольно низкоуровневое понятие, но обычным пользователям приходится взаимодействовать с ним когда эти самые Inode заканчиваются. Возможно вы уже встречались с ошибкой когда место на диске ещё есть, но программа не может создать файл, потому что Inode закончились. В этой статье мы подробно разберемся что такое Inode, а также попытаемся выяснить как избежать связанных с ними проблем.

Что такое Inode в Linux?

Как я уже сказал выше, Inode или I-node или индексный дескриптор — это структура данных, в которой хранятся метаданные файла и перечислены блоки с данными файла. Но начать надо с файловой системы. Файловые системы Ext используют блоки для хранения данных. По умолчанию размер одного блока равен 4092 байта. В начале раздела расположен суперблок, в котором находятся метаданные всей файловой системы, а ним идут несколько зарезервированных блоков, а затем размещена таблица Inode и только после неё блоки с данными. Таким образом, все Inode размещены в начале раздела диска.

Директории — это тоже Inode типа директория, в которых вместо содержимого файла содержится список имён файлов и номера их Inode. Корневая папка в Ext4 имеет номер Inode — 2. Вы можете посмотреть информацию о ней с помощью утилиты debugfs. Утилите в параметрах надо передать диск, на котором расположена файловая система:

Читайте также:  Команды для линукс centos

sudo debugfs /dev/nvme0n1p5

Затем выполните такую команду:

Здесь указано, что эта Inode имеет тип Directory, права 755. Её владелец и группа root, потому что идентификатор пользователя 0. Чуть ниже расположена информация про время создания, модификации и доступа. А в самом низу находятся блоки с данными этой Inode. Именно там хранится список файлов и папок директории. Вы можете посмотреть содержимое блока командой dump_block:

Утилита выведет данные в HEX и ASCII формате, и в них будет видно имена папок. Но увидеть номера Inode здесь не получится без дополнительных программ. Проще всего их можно посмотреть с помощью команды ls:

Здесь в первом же столбике находится номер Inode для файла или папки. Для примера можно посмотреть ещё информацию про testfile с номером Inode 1128:

В разделе EXTENTS есть номер блока, в котором находятся данные файла. В данном случае это 6596316. В нём можно посмотреть содержимое файла:

debugfs: block_dump 6596316

Вот так это всё работает на уровне файловой системы. Посмотреть Inode идентификаторы файлов можно также с помощью команды ls. Для этого надо передать ей опцию -i:

Здесь они будут тоже в первой колонке. Обратите внимание, что у каждого файла, папки или символической ссылки уникальный номер Inode. Исключение составляют только жесткие ссылки. Количество Inode в файловой системе ограничено, оно определяется при инициализации файловой системы. Посмотреть текущее количество Inode можно командой tune2fs:

sudo tune2fs -l /dev/nvme0n1p5

Нужная информация находится в поле Inode count. Посмотреть Inode можно с помощью утилиты df передав ей опцию -i:

Как видите, на моём корневом разделе использовано 29% Inode, а блоков у меня уже использовано 95%. Но если бы у меня было очень много мелких файлов, то место бы ещё осталось, а доступные Inode закончились. Тогда бы возникла ошибка создания файла, даже несмотря на то, что место ещё есть. Чтобы избежать такой ситуации надо тщательно планировать как вы будете использовать файловую систему.

Вы не можете изменить количество Inode для существующей файловой системы, зато можете указать для новой с помощью опции -N. Например:

mkfs -t ext4 -N 3000000 /dev/nvme0n1p5

В данном случае будет создана файловая система с тремя миллионами индексов Inode. Ещё можно не указывать точное количество Inode, а указать количество байт в одной Inode, это может быть удобно, если вы знаете средний размер ваших файлов, которые будут хранится в файловой системе. Например:

mkfs -t ext4 -i 2K /dev/nvme0n1p5

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

Выводы

В этой статье мы рассмотрели что такое Inode в Linux, а также что произойдёт если доступное количество Inodes закончатся. Будьте осторожны при создании файловой системы и думайте какие файлы в ней будут размещены и сколько их там будет чтобы избежать проблем с Inode.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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