Disk devices in linux

2. Devices

There is a special nomenclature that linux uses to refer to hard drive partitions that must be understood in order to follow the discussion on the following pages.

In Linux, partitions are represented by device files. These are phoney files located in /dev . Here are a few entries:

brw-rw—- 1 root disk 3, 0 May 5 1998 hda brw-rw—- 1 root disk 8, 0 May 5 1998 sda crw——- 1 root tty 4, 64 May 5 1998 ttyS0

A device file is a file with type c ( for «character» devices, devices that do not use the buffer cache) or b (for «block» devices, which go through the buffer cache). In Linux, all disks are represented as block devices only.

2.1. Device names


2.1.1. Naming Convention

By convention, IDE drives will be given device names /dev/hda to /dev/hdd . H ard D rive A ( /dev/hda ) is the first drive and H ard D rive C ( /dev/hdc ) is the third.

Table 2. IDE controller naming convention

drive namedrive controllerdrive number
/dev/hda11
/dev/hdb12
/dev/hdc21
/dev/hdd22

A typical PC has two IDE controllers, each of which can have two drives connected to it. For example, /dev/hda is the first drive (master) on the first IDE controller and /dev/hdd is the second (slave) drive on the second controller (the fourth IDE drive in the computer).

You can write to these devices directly (using cat or dd ). However, since these devices represent the entire disk, starting at the first block, you can mistakenly overwrite the master boot record and the partition table, which will render the drive unusable.

drive namedrive controllerdrive numberpartition typepartition number
/dev/hda111primary1
/dev/hda211primary2
/dev/hda311primary3
/dev/hda411swapNA
/dev/hdb112primary1
/dev/hdb212primary2
/dev/hdb312primary3
/dev/hdb412primary4

Once a drive has been partitioned, the partitions will represented as numbers on the end of the names. For example, the second partition on the second drive will be /dev/hdb2 . The partition type (primary) is listed in the table above for clarity, although the concept is not explained until Section 3.3 .

drive namedrive controllerdrive numberpartition typepartition number
/dev/sda116primary1
/dev/sda216primary2
/dev/sda316primary3

SCSI drives follow a similar pattern; They are represented by ‘sd’ instead of ‘hd’. The first partition of the second SCSI drive would therefore be /dev/sdb1 . In the table above, the drive number is arbitraily chosen to be 6 to introduce the idea that SCSI ID numbers do not map onto device names under linux.

2.1.2. Name Assignment

Under (Sun) Solaris and (SGI) IRIX, the device name given to a SCSI drive has some relationship to where you plug it in. Under linux, there is only wailing and gnashing of teeth.

Читайте также:  Proxy settings for linux

SCSI ID #2 SCSI ID #5 SCSI ID #7 SCSI ID #8 /dev/sda /dev/sdb /dev/sdc /dev/sdd

SCSI ID #2 SCSI ID #7 SCSI ID #8 /dev/sda /dev/sdb /dev/sdc

SCSI drives have ID numbers which go from 1 through 15. Lower SCSI ID numbers are assigned lower-order letters. For example, if you have two drives numbered 2 and 5, then #2 will be /dev/sda and #5 will be /dev/sdb . If you remove either, all the higher numbered drives will be renamed the next time you boot up.

If you have two SCSI controllers in your linux box, you will need to examine the output of /bin/dmesg in order to see what name each drive was assigned. If you remove one of two controllers, the remaining controller might have all its drives renamed. Grrr.

There are two work-arounds; both involve using a program to put a label on each partition (see Section 6 ). The label is persistent even when the device is physically moved. You then refer to the partition directly or indirectly by label.

2.1.3. Logical Partitions

Table 5. Logical Partitions

drive namedrive controllerdrive numberpartition typepartition number
/dev/hdb112primary1
/dev/hdb212extendedNA
/dev/hda512logical2
/dev/hdb612logical3

The table above illustrates a mysterious jump in the name assignments. This is due to the use of logical partitions (see Section 3.4 , which always start with 5, for reasons explained later.

This is all you have to know to deal with linux disk devices. For the sake of completeness, see Kristian’s discussion of device numbers below.

2.2. Device numbers

The only important thing with a device file are its major and minor device numbers, which are shown instead of the file size:

Table 6. Device file attributes

brw-rw—-1rootdisk3,0Jul 18 1994/dev/hda
permissions ownergroupmajor device numberminor device numberdatedevice name

When accessing a device file, the major number selects which device driver is being called to perform the input/output operation. This call is being done with the minor number as a parameter and it is entirely up to the driver how the minor number is being interpreted. The driver documentation usually describes how the driver uses minor numbers. For IDE disks, this documentation is in /usr/src/linux/Documentation/ide.txt . For SCSI disks, one would expect such documentation in /usr/src/linux/Documentation/scsi.txt , but it isn’t there. One has to look at the driver source to be sure ( /usr/src/linux/driver/scsi/sd.c :184-196). Fortunately, there is Peter Anvin’s list of device numbers and names in /usr/src/linux/Documentation/devices.txt ; see the entries for block devices, major 3, 22, 33, 34 for IDE and major 8 for SCSI disks. The major and minor numbers are a byte each and that is why the number of partitions per disk is limited.

Источник

This post and this website contains affiliate links. See my disclosure about affiliate links.

Читайте также:  Linux mac address изменить

how to list all hard disks in linux from command line

Hard Disk, Hard Drive, Disk Drive or Hard Disk Drive are all names for a data storage device (hardware device) for storing and retrieving digital information usually in a computer. A computer can have multiple hard disks attached to it, both internal and external.

Now these hard disks can be further divided to multiple logical containers in order to host different file systems or to keep file systems/files separate. These are called partitions and they can then mounted independently with out affecting the other disks and partitions. At a high level abstraction, you can view partition as separate disks as well.

Hard disks on a system are detected and/or identified by various device drivers in the kernel and then assigned an unique device id at boot time, enabling it to be mounted and read later (yeah, this is an over simplification of how it all works but it should suffice for this post). We will see later in the post how you can list disks that have been identified by the system.

The hard disks can be differentiated based on the interface used to interact with them. Some of the commonly used types of disk are SCSI (Small Computer System Interface), ATA or IDE (Advanced Technology Attachment), SATA (Serial ATA), SAS (Serial Attached SCSI) among others. As I mentioned, the physical hard disk is assigned an unique id at startup. This can configured (using udev among others) so that you can assign it pretty much id, but usually most systems follow some universally accepted conventions when naming devices.

By convention, the IDE disks use the device id prefixed with hd and the SCSI (and SATA) disks prefix their device id with sd. So, an IDE disk would be located at /dev/hd(*). eg: /dev/hda, /dev/hdb etc. Similarly, the SCSI disks would be /dev/sda, /dev/sdb etc or in general of the format /dev/sd(*).

Источник

Смотрим список дисков Linux

Linux отображает подключённые жёсткие диски иначе, чем Windows. В операционной системе от Microsoft мы привыкли к тому, что у нас есть диск C, D, E, и нам не нужно задумываться о реальных именах разделов и жёстких дисков. Все диски размещены в проводнике и очень просто доступны.

В Linux такой возможности нет, как и нет такой абстракции. Диски и разделы именуются как есть, и вы будете иметь дело именно с этими именами. В этой статье мы разберём, как посмотреть список дисков Linux.

Как посмотреть список дисков в Linux

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

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

  • sd — устройство, подключённое по SCSI;
  • hd — устройство ATA;
  • vd — виртуальное устройство;
  • mmcblk — обозначаются флешки, подключённые через картридер;
Читайте также:  Install minecraft mods on linux server

В наше время большинство блочных устройств Linux подключаются через интерфейс SCSI. Сюда входят жёсткие диски, USB-флешки, даже ATA-диски теперь тоже подключаются к SCSI через специальный переходник. Поэтому в большинстве случаев вы будете иметь дело именно с дисками sd.

Третья буква в имени диска означает его порядковый номер в системе. Используется алфавитная система. Например sda — первый диск, sdb — второй диск, sdc — третий и так далее. Дальше следует цифра — это номер раздела на диске — sda1, sda2.

Самый простой способ увидеть все подключённые диски — это посмотреть содержимое каталога /dev/ и отфильтровать устройства sd:

Как видите, в моей системе сейчас есть только один диск и два раздела. Дальше мы можем посмотреть, куда примонтирован каждый из разделов:

Здесь, кроме дисков, будут отображаться различные специальные файловые системы: procfs, sysfs, tmpfs, cgroup и так далее. Однако все эти команды не помогут нам получить доступ к информации о дисках. Поэтому нам понадобится кое-что другое. Посмотреть подключённые диски с выводом информации о размере и свободном пространстве можно с помощью утилиты df:

Здесь отображается уже подробная информация. Но вы можете узнать ещё больше с помощью команды lsblk:

В этом случае список примонтированных дисков Linux включает ещё и информацию о точке монтирования, типе раздела (диск, раздел, привод) и его мажорном и минорном номере, по которым можно понять, что это за устройство. Если вам нужна информация о размере, то лучше использовать fdisk:

Это все утилиты, которыми вы можете воспользоваться, чтобы просмотреть список дисков Linux. Но есть ещё и графические утилиты.

Посмотреть список дисков в GUI

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

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

Утилита отображает всю доступную информацию о дисках и разделах на них, вы можете даже посмотреть информацию о состоянии smart. Список дисков находится на панели слева, а справа разделы на этом диске:

Ещё одна утилита, которую вы можете использовать, чтобы посмотреть список жёстких дисков Linux — это Gparted. Это редактор разделов для Linux, но вы можете посмотреть подключнёные диски и структуру каждого из них. Раскрывающийся список вы найдёте в верхнем правом углу:

А в основной части окна программы отображается список разделов.

Выводы

В этой статье мы разобрали несколько способов посмотреть список примонтированных дисков Linux. Каждый из них может понадобиться в различных ситуациях. Если у вас остались вопросы, спрашивайте в комментариях!

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

Источник

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