Linux file system kernel module

sysfs — _The_ filesystem for exporting kernel objectsВ¶

10 January 2003

What it is:В¶

sysfs is a ram-based filesystem initially based on ramfs. It provides a means to export kernel data structures, their attributes, and the linkages between them to userspace.

sysfs is tied inherently to the kobject infrastructure. Please read Everything you never wanted to know about kobjects, ksets, and ktypes for more information concerning the kobject interface.

Using sysfs¶

sysfs is always compiled in if CONFIG_SYSFS is defined. You can access it by doing:

Directory Creation¶

For every kobject that is registered with the system, a directory is created for it in sysfs. That directory is created as a subdirectory of the kobject’s parent, expressing internal object hierarchies to userspace. Top-level directories in sysfs represent the common ancestors of object hierarchies; i.e. the subsystems the objects belong to.

Sysfs internally stores a pointer to the kobject that implements a directory in the kernfs_node object associated with the directory. In the past this kobject pointer has been used by sysfs to do reference counting directly on the kobject whenever the file is opened or closed. With the current sysfs implementation the kobject reference count is only modified directly by the function sysfs_schedule_callback().

Attributes¶

Attributes can be exported for kobjects in the form of regular files in the filesystem. Sysfs forwards file I/O operations to methods defined for the attributes, providing a means to read and write kernel attributes.

Attributes should be ASCII text files, preferably with only one value per file. It is noted that it may not be efficient to contain only one value per file, so it is socially acceptable to express an array of values of the same type.

Mixing types, expressing multiple lines of data, and doing fancy formatting of data is heavily frowned upon. Doing these things may get you publicly humiliated and your code rewritten without notice.

An attribute definition is simply:

A bare attribute contains no means to read or write the value of the attribute. Subsystems are encouraged to define their own attribute structure and wrapper functions for adding and removing attributes for a specific object type.

For example, the driver model defines struct device_attribute like:

It also defines this helper for defining device attributes:

For example, declaring:

is equivalent to doing:

Note as stated in include/linux/kernel.h “OTHER_WRITABLE? Generally considered a bad idea.” so trying to set a sysfs file writable for everyone will fail reverting to RO mode for “Others”.

For the common cases sysfs.h provides convenience macros to make defining attributes easier as well as making code more concise and readable. The above case could be shortened to:

static struct device_attribute dev_attr_foo = __ATTR_RW(foo);

the list of helpers available to define your wrapper function is:

assumes default name_show and mode 0444

assumes a name_store only and is restricted to mode 0200 that is root write access only.

fore more restrictive RO access currently only use case is the EFI System Resource Table (see drivers/firmware/efi/esrt.c)

assumes default name_show, name_store and setting mode to 0644.

which sets the name to NULL and is used as end of list indicator (see: kernel/workqueue.c)

Subsystem-Specific Callbacks¶

When a subsystem defines a new attribute type, it must implement a set of sysfs operations for forwarding read and write calls to the show and store methods of the attribute owners:

[ Subsystems should have already defined a struct kobj_type as a descriptor for this type, which is where the sysfs_ops pointer is stored. See the kobject documentation for more information. ]

When a file is read or written, sysfs calls the appropriate method for the type. The method then translates the generic struct kobject and struct attribute pointers to the appropriate pointer types, and calls the associated methods.

Reading/Writing Attribute Data¶

To read or write attributes, show() or store() methods must be specified when declaring the attribute. The method types should be as simple as those defined for device attributes:

Читайте также:  Guiformat для windows 10

IOW, they should take only an object, an attribute, and a buffer as parameters.

sysfs allocates a buffer of size (PAGE_SIZE) and passes it to the method. Sysfs will call the method exactly once for each read or write. This forces the following behavior on the method implementations:

On read(2), the show() method should fill the entire buffer. Recall that an attribute should only be exporting one value, or an array of similar values, so this shouldn’t be that expensive.

This allows userspace to do partial reads and forward seeks arbitrarily over the entire file at will. If userspace seeks back to zero or does a pread(2) with an offset of ‘0’ the show() method will be called again, rearmed, to fill the buffer.

On write(2), sysfs expects the entire buffer to be passed during the first write. Sysfs then passes the entire buffer to the store() method. A terminating null is added after the data on stores. This makes functions like sysfs_streq() safe to use.

When writing sysfs files, userspace processes should first read the entire file, modify the values it wishes to change, then write the entire buffer back.

Attribute method implementations should operate on an identical buffer when reading and writing values.

Writing causes the show() method to be rearmed regardless of current file position.

The buffer will always be PAGE_SIZE bytes in length. On i386, this is 4096.

show() methods should return the number of bytes printed into the buffer.

show() should only use sysfs_emit() or sysfs_emit_at() when formatting the value to be returned to user space.

store() should return the number of bytes used from the buffer. If the entire buffer has been used, just return the count argument.

show() or store() can always return errors. If a bad value comes through, be sure to return an error.

The object passed to the methods will be pinned in memory via sysfs referencing counting its embedded object. However, the physical entity (e.g. device) the object represents may not be present. Be sure to have a way to check this, if necessary.

A very simple (and naive) implementation of a device attribute is:

(Note that the real implementation doesn’t allow userspace to set the name for a device.)

Top Level Directory Layout¶

The sysfs directory arrangement exposes the relationship of kernel data structures.

The top level sysfs directory looks like:

devices/ contains a filesystem representation of the device tree. It maps directly to the internal kernel device tree, which is a hierarchy of struct device .

bus/ contains flat directory layout of the various bus types in the kernel. Each bus’s directory contains two subdirectories:

devices/ contains symlinks for each device discovered in the system that point to the device’s directory under root/.

drivers/ contains a directory for each device driver that is loaded for devices on that particular bus (this assumes that drivers do not span multiple bus types).

fs/ contains a directory for some filesystems. Currently each filesystem wanting to export attributes must create its own hierarchy below fs/ (see ./fuse.txt for an example).

dev/ contains two directories char/ and block/. Inside these two directories there are symlinks named : . These symlinks point to the sysfs directory for the given device. /sys/dev provides a quick way to lookup the sysfs interface for a device from the result of a stat(2) operation.

More information can driver-model specific features can be found in Documentation/driver-api/driver-model/.

TODO: Finish this section.

Current Interfaces¶

The following interface layers currently exist in sysfs:

Источник

Kernel module (Русский)

Модули ядра — это отдельные кусочки кода, которые могут быть загружены и выгружены из ядра по мере необходимости. Они расширяют функциональность ядра без необходимости перезагрузки системы.

Contents

Обзор

Чтобы создать модуль ядра, вы можете прочитать The Linux Kernel Module Programming Guide. Модуль можно сконфигурировать как вкомпилированный, а можно как загружаемый. Чтобы иметь возможность динамически загружать или выгружать модуль, его необходимо сконфигурировать как загружаемый модуль в настройке ядра (в этом случае строка, относящаяся к модулю должна быть отмечена буквой M ).

Модули хранятся в /usr/lib/modules/kernel_release . Чтобы узнать текущую версию вашего ядра, используйте команду uname -r .

Получение информации

Чтобы узнать, какие модули ядра загружены в настоящий момент:

Чтобы показать информацию о модуле:

Чтобы вывести список опций, с которыми загружен модуль:

Чтобы отобразить настройки для всех модулей:

Чтобы отобразить настройки для отдельного модуля:

Чтобы узнать зависимости модуля (или его псевдонима), включая сам модуль:

Читайте также:  Mipsel linux ��� ���

Автоматическое управление модулями

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

Чтобы дополнительные модули ядра загружались автоматически в процессе загрузки, создаются статические списки в конфигурационных файлах в директории /etc/modules-load.d/ . Каждый конфигурационный файл называется по схеме /etc/modules-load.d/

.conf . Эти конфигурационные файлы содержат список названий модулей ядра, которые необходимо грузить, разделённых переносом строки. Пустые строки и строки, в которых первым непробельным символом является # или ; , игнорируются.

Смотрите modules-load.d(5) для дополнительной информации.

Управление модулями вручную

Управление модулями ядра производится с помощью утилит, предоставляемых пакетом kmod . Вы можете использовать эти утилиты вручную.

Загрузка модуля из другого места (для тех модулей, которых нет в /lib/modules/$(uname -r)/ ):

Альтернативный вариант выгрузки модуля:

Настройка параметров модуля

Чтобы передать параметр модулю ядра, вы можете воспользоваться конфигурационным файлом в modprobe или использовать командную строку ядра.

С помощью файлов в /etc/modprobe.d/

Файлы в директории /etc/modprobe.d/ можно использовать для передачи настроек модуля в udev, который через modprobe управляет загрузкой модулей во время загрузки системы. Конфигурационные файлы в этой директории могут иметь любое имя, оканчивающееся расширением .conf . Синтаксис следующий:

С помощью командной строки ядра

Если модуль вкомпилирован в ядро, вы также можете передать параметры модулю с помощью командной строки ядра. Для всех стандартных загрузчиков, подойдёт следующий синтаксис:

Просто добавьте это в загрузчике в строку с ядром, как описано в параметрах ядра.

Создание псевдонимов

Псевдонимы (алиасы) — это альтернативные названия для модуля. Например: alias my-mod really_long_modulename означает, что вы можете использовать modprobe my-mod вместо modprobe really_long_modulename . Вы также можете использовать звёздочки в стиле shell, то есть alias my-mod* really_long_modulename будет иметь тот же эффект, что и modprobe my-mod-something . Создайте алиас:

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

Запрет загрузки

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

Некоторые модули загружаются как часть initramfs. Команда mkinitcpio -M напечатает все автоматически обнаруженные модули: для предотвращения initramfs от загрузки каких-то из этих модулей, занесите их в чёрный список в /etc/modprobe.d/modprobe.conf . Команда mkinitcpio -v отобразит все модули, которые необходимы некоторым хукам (например, filesystems хук, block хук и т.д.). Не забудьте добавить этот .conf файл в секцию FILES в /etc/mkinitcpio.conf , если вы этого ещё не сделали, пересоберите initramfs после того, как вы запретили загрузку модулей, а затем перезагрузитесь.

С помощью файлов в /etc/modprobe.d/

Создайте .conf файл в /etc/modprobe.d/ и добавьте строку для каждого модуля, который вы хотите запретить, используя ключевое слово blacklist . Например, если вы хотите запретить загружать модуль pcspkr :

Можно изменить такое поведение. Команда install заставляет modprobe запускать вашу собственную команду вместо вставки модуля в ядро как обычно. Поэтому вы можете насильно сделать так, чтобы модуль никогда не загружался:

Это запретит данный модуль и все модули, зависящие от него.

С помощью командной строки ядра

Вы также можете запрещать модули из загрузчика.

Источник

/proc/filesystems: Find out what filesystems supported by Linux kernel

S o, How do you find out or see which filesystems are supported by the Linux kernel? The answer is simple. Use /proc/filesystems file. It is the file used to detect filesystems supported by running kernel. You can quickly run grep command or cat command to display the list of all supported file system. nodev indicates that the file system is not associated with a physical device such as /dev/sdb1. If you see ext3 or vfat, it means you will be able to mount ext3 and vfat based file systems. This page explains filesystems supported by Linux using various commands.

How to see which filesystems are supported by the Linux

Following cat command will quickly tell you what filesystems supported by currently running Linux kernel:
$ cat /proc/filesystems
Sample outputs:

For example, if the iso9660 fllesystem not listed, you can not mount standard CD-ROM file system. To add support simply recompile Linux kernel with iso9660 filesystem support.

Читайте также:  Git use ssh key windows

Finding out Linux kernel modules

Type the following ls command to list the Linux kernel modules related to filesystem:
ls /lib/modules/$(uname -r)/kernel/fs/*/*ko

Click to enlarge image

Get a list of currently loaded Linux kernel modules

Run any one of the following command:
cat /proc/modules
OR use the lsmod command along with grep command to filter out filesystems such as zfs:
lsmod
lsmod | grep zfs
Sample outputs:

  • 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

Please note that the lsmod is an awesome command which nicely formats the contents of the /proc/modules, showing what kernel modules are currently loaded.

Linux based systems comes with the modprobe command, to add and remove modules from the Linux Kernel. To load zfs module, run:
sudo modprobe zfs
sudo modprobe -v zfs
See “how to load Linux kernel driver/modules automatically boot time” for more information.

Conclusion

You learned how to use various Linux command line utilities to list supported filesystems. See Linux wiki for more information here.

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

What does “nodev” in the beginning of a line mean?

It’s not always true. For example you will not see nfs and nfs4 in /proc/filesystems after reboot. But still you can mount remote nfs directory if needed packages are installed in the system. After successful mounting nfs and nfs4 will appear in /proc/filesystem. Tested on Ubuntu 11.10

i can still mount vfat usb drive even vfat not found in /proc/filesystems.But after mounting, it appears in /proc/filesystems too! Tested on kernel 2.4.35.4

The “nodev” string in the first column means that filesystem does not require a block device to be mounted, it’s so called virtual filesystem.

How to troubleshoot apache log errors. can u please explain step by step process in linux ??/

Just adding my 2 cents here. The only way to be sure about what filesystems are supported by the kernel or not is to check its configuration file. In my case, it is
and look for the filesystem type.
I searched for ISO9660 (for example) and found the following:

# CD-ROM/DVD Filesystems
#
CONFIG_ISO9660_FS=m
CONFIG_JOLIET=y
CONFIG_ZISOFS=y
CONFIG_UDF_FS=m
CONFIG_UDF_NLS=y

The “m” means it was compiled as a module but not automatically inserted into the kernel.
In order to load it into the kernel, we must run the following command:
modprobe -a isofs
(where isofs is the alias of the corresponding module)
And then iso9660 will show up in the /proc/filesystems file.

(on a side note, the aliases for modules can be found in /lib/modules, then look for the directory of your kernel, and read the file modules.alias)

Sorry, I forgot to include the path to my kernel’s configuration file. Here it is:
/boot/config-3.2.0-4-686-pae

I got a list of loadable filesystems this way:

ls /lib/modules/$(uname -r)/kernel/fs/*/*ko

Источник

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