Hardware: работа с устройствами в Linux (udev, uname, lspci, lscpu, lsusb, sensors; drivers-modules insmod/rmmod, lsmod, depmod, modprobe, modinfo)

udev / block-character dev
udev - это демон, который отвечает за виртуальную файловую систему /dev.
/etc/udev/ - каталог настроек демона.
/etc/udev/rules.d/ - каталог с правилами, по которым udev создаёт файлы устройств в /dev.
70-persistent-net.rules - правило для создания сетевых интерфейсов.
  • (Hardware linux, nic) В общем случае если NIC есть в списке lspci, но отсутствует в ip a/ifconfig, а точнее ему не присвоено имя сервисом udev путем создания файла в директории /dev/ (осуществляется по ID устройства) – она не привязана к ядру, возможные причины:
    • драйвер неизвестен
    • девайс находится в userspace (dpdk)
    • девайс находится в выделенном netns
ls -ltr /etc/udev/
total 12
-rw-r--r-- 1 root root 281 Feb 14 2019 udev.conf

Для необходимости изменения названия (что в целом не рекомендуется) в сравнении с выдаваемым udev по умолчанию нужно использовать rules или глобальный конфиг udev.conf (менее желательно). Так же когда есть конфликт с названиями интерфейсов в Linux может помочь заглянуть в файл /etc/udev/rules.d/70-persistent-net.rules

/etc/udev/rules.d/70-persistent-net.rules
Он может пригодиться при миграции с одной системы (с одним неймингом) на другую (с другим неймингом), при выходе из строя сетевой карты и желании сохранить номер старой, когда сетевые интерфейсы которые должны подняться, по какой-то причине не поднимаются…

Есть блочные и символные устройства:

Each piece of hardware in the system has an associated file used by the kernel to communicate with it. This type of file is called a device file. There are two types of device files: a character (or raw) device file and a block device file.
The first character in each line entry tells if the file type is block or character. Ab denotes a block device file and a c represents a character device file.

[root@host1 ~]# ll /dev/sd*
brw-rw----. 1 root disk 8, 0 Aug 4 14:13 /dev/sda
brw-rw----. 1 root disk 8, 1 Aug 4 14:13 /dev/sda1
brw-rw----. 1 root disk 8, 2 Aug 4 14:13 /dev/sda2

[root@host1 ~]# ll /dev/usb*
crw-------. 1 root root 250, 0 Aug 4 14:13 /dev/usbmon0
crw-------. 1 root root 250, 1 Aug 4 14:13 /dev/usbmon1
crw-------. 1 root root 250, 2 Aug 4 14:13 /dev/usbmon2

[root@host1 ~]# file /dev/sda
/dev/sda: block special

[root@host1 ~]# file /dev/usbmon0
/dev/usbmon0: character special


 
uname
uname –a – смотрим тип ОС, hostname, версию ядра, разрядность (x86_64 indicates a running 64-bit kernel. If you use see i386, i486, i586 or i686, you’re running a 32-bit kernel). По отдельным опциям –s (kernel name), –n (node name), –r (kernel release), –v (kernel build date), –m (hardware name), –p (processor type), –i (hardware platform), and –o (OS name) можно посмотреть specific info.
# uname –a
Linux host1.example.com 3.10.0-123.el7.x86_64 #1 SMP Mon May 5 11:16:57 EDT 2014 x86_64 x86_64 x86_64 GNU/Linux

The information returned by the second command is:
Linux Kernel name
host1.example.com Hostname of this system
3.10.0-123.el7.x86_64 Kernel release
#1 SMP Mon May 5 11:16:57 EDT 2014 Date and time of this kernel built
x86_64 Machine hardware name
x86_64 Processor type
x86_64 Hardware platform
GNU/Linux Operating system name
lspci
lspci – команда для просмотра устройств включенных от PCI bus (и не только – CPU, Ethernet, Wi-Fi, VGA, PCI, USB, AUDIO, etc). Фактическое устройство по факту может отличаться от того, которое отражено в названии lspci! (напр. Intel Core i7 вместо XEON или вместе – PCI bridge: Intel Corporation Xeon E7 v3/Xeon E5 v3/Core i7 PCI). Имя отображается в соответствии с установленным драйвером. Наиболее корректно для идентификации устройства использовать ID (по аналогии и с Windows).
The lspci command displays information about PCI buses and the devices attached to them.
Детальную информацию можно посмотреть добавив опции -v (verbose), -vv
redkin_p@testsmsrobot:~$ lspci
00:00.0 Host bridge: Intel Corporation 440BX/ZX/DX - 82443BX/ZX/DX Host bridge (rev 01)
00:01.0 PCI bridge: Intel Corporation 440BX/ZX/DX - 82443BX/ZX/DX AGP bridge (rev 01)
00:07.0 ISA bridge: Intel Corporation 82371AB/EB/MB PIIX4 ISA (rev 08)
00:07.1 IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)
00:07.3 Bridge: Intel Corporation 82371AB/EB/MB PIIX4 ACPI (rev 08)
00:07.7 System peripheral: VMware Virtual Machine Communication Interface (rev 10)
00:0f.0 VGA compatible controller: VMware SVGA II Adapter
00:15.0 PCI bridge: VMware PCI Express Root Port (rev 01)
00:15.1 PCI bridge: VMware PCI Express Root Port (rev 01)
00:15.2 PCI bridge: VMware PCI Express Root Port (rev 01)
03:00.0 Serial Attached SCSI controller: LSI Logic / Symbios Logic SAS1068 PCI-X Fusion-MPT SAS (rev 01)
0b:00.0 Ethernet controller: VMware VMXNET3 Ethernet Controller (rev 01)
13:00.0 Ethernet controller: VMware VMXNET3 Ethernet Controller (rev 01)
redkin.p@govnoserver:~$ lspci | grep VGA
00:02.0 VGA compatible controller: InnoTek Systemberatung GmbH VirtualBox Graphics Adapter
[user1@host1 ~]$ lspci | grep VGA
00:02.0 VGA compatible controller: Intel Corporation Core Processor Integrated Graphics Controller (rev 18)
01:00.0 VGA compatible controller: NVIDIA Corporation GT218M [GeForce 310M] (rev a2)
lsusb
lsusb – инфа о устройствах, подключенных к USB bus. Детальную информацию можно посмотреть добавив опции -v (verbose), -vv.
[user1@host1 ~]$ lsusb
Bus 001 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 064e:a136 Suyin Corp. Asus Integrated Webcam [CN031B]
Bus 001 Device 004: ID 0b05:1788 ASUSTek Computer, Inc. BT-270 Bluetooth Adapter
Bus 002 Device 003: ID 058f:6387 Alcor Micro Corp. Flash Drive
Bus 002 Device 004: ID 0458:003a KYE Systems Corp. (Mouse Systems) NetScroll+ Mini Traveler / Genius NetScroll 120
lscpu

lscpu
– инфа о CPU.
[user1@host1 ~]$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    2
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 37
Model name:            Intel(R) Core(TM) i3 CPU       M 370  @ 2.40GHz
Stepping:              5
CPU MHz:               933.000
BogoMIPS:              4932.50
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              3072K
NUMA node0 CPU(s):     0-3




redkin_p@devastator ~ $ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                8
On-line CPU(s) list:   0-7
Thread(s) per core:    2
Core(s) per socket:    2
Socket(s):             2
Vendor ID:             GenuineIntel
CPU family:            15
Model:                 6
Model name:            Intel(R) Xeon(TM) CPU 3.00GHz
Stepping:              4
CPU MHz:               2999.679
BogoMIPS:              6000.26
Virtualization:        VT-x
L1d cache:             16K
L2 cache:              2048K
sensors
sudo yum install lm_sensors.x86_64 – Ставим сенсоры
sudo sensors-detect – Далее рекомендуется настроить, при этом выбирать дефолты (они большими буквами)
sensors – Смотрим датчики. Например,
acpitz-virtual-0 – один из сенсоров CPU, в интернетах рекомендуют на него не обращать внимания
nouveau – видеокарта
coretemp – CPU
[user1@host1 ~]$ sensors
acpitz-virtual-0
Adapter: Virtual device
temp1: +57.0°C (crit = +108.0°C)
nouveau-pci-0100
Adapter: PCI adapter
temp1: +57.0°C (high = +95.0°C, hyst = +3.0°C)
  (crit = +105.0°C, hyst = +5.0°C)
  (emerg = +135.0°C, hyst = +5.0°C)
coretemp-isa-0000
Adapter: ISA adapter
Core 0: +51.0°C (high = +95.0°C, crit = +105.0°C)
Core 2: +46.0°C (high = +95.0°C, crit = +105.0°C)

 

modules / drivers

Модули ядра в случае с hardware реализуют функционал драйверов этих устройств, хотя в целом модуль далеко не всегда есть драйвер.

Lsmod
Lsmod – Listing (Loaded) Modules, алтернатива просмотр содержимого /proc/modules
Linux provides the lsmod command to view currently loaded modules. Alternatively, you can view them by displaying the contents of the /proc/modules file. Both show module names, memory they are consuming, the number of processes using this and any dependent modules, and a list of dependent modules (if any).
# lsmod | head -n 5
Module Size Used by
joydev 24576 0
hid_generic 16384 0
usbhid 57344 0
hid 139264 2 usbhid,hid_generic
# cat /proc/modules | head -5
joydev 24576 0 - Live 0xffffffffc052c000
hid_generic 16384 0 - Live 0xffffffffc0560000
usbhid 57344 0 - Live 0xffffffffc082a000
hid 139264 2 hid_generic,usbhid, Live 0xffffffffc0501000
igb_uio 16384 0 - Live 0xffffffffc0492000 (OE)

modinfo
Modinfo – Displaying Module Information
The modinfo command can be used to display details about a module. The output shows the module file name, license type, author name, a short description, dependent module names, and other information.
For instance, the following example shows information about a disk mirroring module called dm_mirror:

~# modinfo dm_mirror
filename: /lib/modules/4.19.0-20-amd64/kernel/drivers/md/dm-mirror.ko
license: GPL
author: Joe Thornber
description: device-mapper mirror target
depends: dm-region-hash,dm-mod,dm-log
retpoline: Y
intree: Y
name: dm_mirror
vermagic: 4.19.0-20-amd64 SMP mod_unload modversions 
sig_id: PKCS#7
signer: Debian Secure Boot CA
sig_key: 4B:6E:F5:AB:CA:66:98:25:17:8E:05:2C:84:66:7C:CB:C0:53:1F:8C
sig_hashalgo: sha256
signature: 38:6E:54:9B:40:8A:98:B0:60:FC:53:49:FE:8C:FC:18:A5:22:FB:BA
parm: raid1_resync_throttle:A percentage of time allocated for raid resynchronization (uint)
# modinfo ip_tables
filename: /lib/modules/4.19.0-20-amd64/kernel/net/ipv4/netfilter/ip_tables.ko
alias: ipt_icmp
description: IPv4 packet filter
author: Netfilter Core Team <coreteam@netfilter.org>
license: GPL
depends: x_tables
retpoline: Y
intree: Y
name: ip_tables
vermagic: 4.19.0-20-amd64 SMP mod_unload modversions 
sig_id: PKCS#7
signer: Debian Secure Boot CA
sig_key: 4B:6E:F5:AB:CA:66:98:25:17:8E:05:2C:84:66:7C:CB:C0:53:1F:8C
sig_hashalgo: sha256
signature: 2A:D0:2F:49:E3:38:E1:4C:7E:F7:91:33:4E:84:4C:CD:19:2E:28:45:
modprobe / insmod/ rmmod

modprobe (-r to unload, -v to debug) – Loading and Unloading Modules including dependent modules (для игнорирования зависимостей используются insmod, rmmod).

  • Modprobe работает по умолчанию в системе – обнаруживает новый hardware и активирует модули для этого hardware в ядро
  • Отключение модулей может быть полезно для безопасности – bluetooth, wifi, usb и проч. В том числе с добавлением запрета модуля по имени в автозагрузку за счет спального blacklist списка – /etc/modprobe.d/blacklist*
Execute the modprobe command to load a module dynamically into memory. This command ensures that any dependent modules are also loaded prior to the specified module. To unload the dm_mirror module along with all unused dependent modules, run the modprobe command with the –r option.

[root@localhost ~]# modprobe -v dm_mirror
insmod /lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/drivers/md/dm-log.ko
insmod /lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/drivers/md/dm-region-hash.ko
insmod /lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/drivers/md/dm-mirror.ko

[root@localhost ~]# modprobe -vr dm_mirror
rmmod dm_mirror
rmmod dm_region_hash
rmmod dm_log
depmod
Depmod (-v debug) – Installing New Modules
Linux detects hardware devices and loads appropriate modules automatically; however, there may be instances when a device is left undetected or added online (as in the case of SAN disk allocation). In such a situation, execute the depmod command to force the system to scan the hardware, find appropriate modules for the new devices, create required module dependencies, and update the /lib/modules/3.10.0-327.36.2.el7.x86_64/modules.dep file, in addition to creating and updating several corresponding map files in the /lib/modules/3.10.0-327.36.2.el7.x86_64 directory.

[root@localhost ~]# depmod -v | head -5
/lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/arch/x86/crypto/ablk_helper.ko needs "cryptd_alloc_ablkcipher": /lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/crypto/cryptd.ko
/lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/arch/x86/crypto/camellia-x86_64.ko needs "glue_cbc_encrypt_128bit": /lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/arch/x86/crypto/glue_helper.ko
/lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/arch/x86/crypto/camellia-x86_64.ko needs "lrw_free_table": /lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/crypto/lrw.ko
/lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/arch/x86/crypto/camellia-x86_64.ko needs "xts_crypt": /lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/crypto/xts.ko
/lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/arch/x86/crypto/blowfish-x86_64.ko needs "blowfish_setkey": /lib/modules/3.10.0-327.36.2.el7.x86_64/kernel/crypto/blowfish_common.ko

[root@localhost ~]# ls /lib/modules/3.10.0-327.36.2.el7.x86_64/ | grep modules
modules.alias
modules.alias.bin
modules.block
modules.builtin
modules.builtin.bin
modules.dep
modules.dep.bin
modules.devname
modules.drm
modules.modesetting
modules.networking
modules.order
modules.softdep
modules.symbols
modules.symbols.bin
lshw

(дублируется в NIC, Linux hardware)

lshw -class network # полный вывод

lshw -c network -short -numeric # вывод в виде удобной таблички (short – краткий, numeric – добавляем ID устройства)

# lshw -c network -short -numeric
H/W path Device Class Description
========================================================
/0/100/2/0 ens6f0 network I350 Gigabit Network Connection [8086:1521]
/0/100/2/0.1 ens6f1 network I350 Gigabit Network Connection [8086:1521]
/0/100/2.2/0 network 82599ES 10-Gigabit SFI/SFP+ Network Connection [8086:10FB]
/0/100/2.2/0.1 network 82599ES 10-Gigabit SFI/SFP+ Network Connection [8086:10FB]
/0/100/3.2/0 enp5s0f0 network BCM57840 NetXtreme II 10 Gigabit Ethernet [14E4:16A1]
/0/100/3.2/0.1 enp5s0f1 network BCM57840 NetXtreme II 10 Gigabit Ethernet [14E4:16A1]
/0/100/1c.4/0 enp7s0 network I210 Gigabit Network Connection [8086:1533]
/0/100/1c.5/0 enp8s0 network I210 Gigabit Network Connection [8086:1533]

# lshw -c network -short
H/W path Device Class Description
========================================================
/0/100/2/0 ens6f0 network I350 Gigabit Network Connection
/0/100/2/0.1 ens6f1 network I350 Gigabit Network Connection
/0/100/2.2/0 network 82599ES 10-Gigabit SFI/SFP+ Network Connection
/0/100/2.2/0.1 network 82599ES 10-Gigabit SFI/SFP+ Network Connection
/0/100/3.2/0 enp5s0f0 network BCM57840 NetXtreme II 10 Gigabit Ethernet
/0/100/3.2/0.1 enp5s0f1 network BCM57840 NetXtreme II 10 Gigabit Ethernet
/0/100/1c.4/0 enp7s0 network I210 Gigabit Network Connection
/0/100/1c.5/0 enp8s0 network I210 Gigabit Network Connection

Если девайс в списке есть, но без logical name, перезагрузить сервер или рестартовать службу командой выше. Если состояние DISABLED, то интерфейс нужно включить (ifup/ifconfig/ip link – выше примеры).

~$ sudo lshw -class network
*-network
description: Ethernet interface
product: VMXNET3 Ethernet Controller
vendor: VMware
physical id: 0
bus info: pci@0000:0b:00.0
logical name: eth0
version: 01
serial: 00:50:56:b6:78:b5
capacity: 1Gbit/s
width: 32 bits
clock: 33MHz
capabilities: pm pciexpress msi msix bus_master cap_list rom ethernet physical logical tp 1000bt-fd
configuration: autonegotiation=off broadcast=yes driver=vmxnet3 driverversion=1.4.14.0-k-NAPI duplex=full ip=78.107.63.120 latency=0 link=yes multicast=yes port=twisted pair
resources: irq:19 memory:fd4fb000-fd4fbfff memory:fd4fc000-fd4fcfff memory:fd4fe000-fd4fffff ioport:5000(size=16) memory:fd400000-fd40ffff

*-network
description: Ethernet interface
product: VMXNET3 Ethernet Controller
vendor: VMware
physical id: 0
bus info: pci@0000:13:00.0
logical name: eth1
version: 01
serial: 00:50:56:b6:7d:ab
capacity: 1Gbit/s
width: 32 bits
clock: 33MHz
capabilities: pm pciexpress msi msix bus_master cap_list rom ethernet physical logical tp 1000bt-fd
configuration: autonegotiation=off broadcast=yes driver=vmxnet3 driverversion=1.4.14.0-k-NAPI duplex=full ip=192.168.149.78 latency=0 link=yes multicast=yes port=twisted pair
resources: irq:16 memory:fd3fb000-fd3fbfff memory:fd3fc000-fd3fcfff memory:fd3fe000-fd3fffff ioport:6000(size=16) memory:fd300000-fd30ffff

Если в выводе Unclaimed – вероятнее всего нужно обновлять операционную систему для обновления драйверов.

*-network:0 UNCLAIMED
description: Ethernet controller

Очень удобно и наглядно и по дискам/RAM.

# lshw -c disk -short
H/W path Device Class Description
======================================================
/0/100/17/0 /dev/sda disk 4011MB 4GB SATA Flash D
/0/100/17/1 /dev/sdb disk 1TB TOSHIBA MG04ACA1

# lshw -c memory -short | grep iB
/0/0 memory 64KiB BIOS
/0/54 memory 8GiB System Memory
/0/54/0 memory 4GiB DIMM DDR4 Synchronous 2133 MHz (0.5 ns)
/0/54/8 memory 4GiB DIMM DDR4 Synchronous 2133 MHz (0.5 ns)
/0/6c memory 384KiB L1 cache
/0/6d memory 1536KiB L2 cache
/0/6e memory 15MiB L3 cache
/0/70 memory 384KiB L1 cache
/0/71 memory 1536KiB L2 cache
/0/72 memory 15MiB L3 cache

Leave a Reply