Article count:1385 Read by:1972833

Featured Content
Account Entry

Formatting, partitioning, and mounting disk management in Linux - detailed explanation

Latest update time:2023-09-13
    Reads:

Hi, everyone, I am Programmer Lao Wang, Programmer Lao Wang is me.
Today I will introduce to you the steps of formatting, partitioning, mounting and other operations in disk management in Linux. I hope this article will be helpful to you.

1. Disk knowledge

1.Disk meaning

Disk is a physical device used to store and read data. It consists of one or more rotating magnetic platters. These platters are usually made of metal or glass and coated with a magnetic material. Disk is one of the main permanent storage media in computer systems.

2. Disk working mechanism

The working mechanism of magnetic disks is based on the principles of magnetization and magnetic field induction of magnetic materials. Here is the basic process of how a disk works:
  1. Magnetization : Magnetic material on a disk can be magnetized by applying a magnetic field to cause a change in the magnetic orientation of the material. This magnetization can be achieved by a magnetic field generated by an electromagnetic magnet or a magnetic head.
  2. Magnetic field induction : The magnetic head is an inductor on the disk that can sense changes in the magnetic field and convert it into an electrical signal. When the head is close to the disk surface, it can detect the magnetization state of the magnetic material.
  3. Data reading : When reading data, the magnetic head detects the data on the disk by sensing changes in the magnetic field. As the head passes over a magnetized area, the changes in the magnetic field induced are converted into electrical signals and interpreted by the disk controller as corresponding data.
  4. Data writing : When writing data, the head changes the magnetization state on the disk by applying a magnetic field. The head stores data in the magnetic material by creating or changing magnetization patterns at corresponding locations on the disk, depending on the data to be written.
  5. Seeking and rotation : In order to access specific tracks and sectors, the head needs to move to the target location on the disk surface. This process is called a seek operation. The movement of the heads is controlled by the disk drive, and they can move in the radius of the disk. In addition, disks achieve high-speed read and write operations by rotating the platters, and the rotation speed is usually expressed in revolutions per minute (RPM).
By controlling the magnetic field and the movement of the magnetic head, the disk enables the storage and retrieval of data. This mechanism has large storage capacity, low cost, and relatively fast read and write speeds, making disks one of the main permanent storage media in computer systems.

3. The professional name of the disk

3.1 Disk side and magnetic head

Platter : The platter is the circular magnetic disk inside the hard drive, usually made of metal or glass material. A hard drive can contain one or more platters that are stacked together and secured by a central spindle. Each platter has two flat surfaces called sides.
Platter Surface : The Platter Surface is a flat surface on the disc used to store data. A platter usually has two sides, that is, two surfaces that can be used to read and write data. Each side is divided into a series of concentric circular tracks, and each track is divided into sectors.
Head : The head is a device located above the platter and is used to read and write data. In a hard drive, the magnetic heads sit on moving magnetic arms and can move along the radius of the platter. There is a head on each side to interact with the disk. Therefore, if a hard drive has multiple platters, there will be a head on each side.

3.2 Sectors and tracks

Sector : A sector is the smallest storage unit on a disk. It is a small segment on the track, usually 512 bytes or 4KB in size. Each disk sector has a unique address through which specific data can be located and accessed. Operating systems and file systems organize data into sectors and then use sector addresses to read or write data.
Track : A track is a ring on the surface of the disk that extends along the radius of the disk. There are usually multiple tracks on a disk, which are numbered to identify and access specific tracks. Each track can contain multiple sectors, forming a data ring. The disk's head can move on the disk surface to a designated track, and then read or write sector data on the track.

3.3 Magnetic head and cylinder

Head : The head is a device located inside the hard drive that is used to read and write data. In a hard drive, the magnetic heads sit on moving magnetic arms and can move along the radius of the platter. There is a head on each side to interact with the disk. The magnetic head is responsible for reading or writing data on a specific track. By controlling the movement and positioning of the magnetic head, the magnetic head can be positioned to a specific position on the target track to read and write data.
Cylinder : A cylinder is a concept inside a hard drive that represents a collection of tracks located at the same radius on multiple platters. In other words, a cylinder is formed by vertically stacking tracks on multiple platters located at the same radial location. Cylinder numbers are used to represent combinations of tracks on a disk that have the same radial location. By moving the head to a specific cylinder, all tracks on that cylinder can be accessed.

4. Disk classification

Disks can be divided into many types based on interface type. The following are some common disk interface classifications:
  • SATA (Serial ATA) disk : SATA is currently the most common type of disk interface and is widely used in desktop and laptop computers. It provides higher data transfer speeds and lower costs, and supports hot plugging and hot swapping.
  • SAS (Serial Attached SCSI) disk : SAS is a high-performance disk interface mainly used in enterprise-level servers and storage systems. It provides higher data transfer speeds and more reliable connections, supports multi-path redundancy and hot-swappable capabilities.
  • SCSI (Small Computer System Interface) disk : SCSI is an early disk interface used to connect high-performance computer systems and external storage devices. It provides high-speed data transfer and flexible device connection options, supporting multi-device links and advanced features.
  • NVMe (Non-Volatile Memory Express) disk : NVMe is a high-performance disk interface based on the PCIe (Peripheral Component Interconnect Express) bus. It is designed specifically for solid-state drives (SSDs) with low latency and high-speed data transfer capabilities and is widely used in high-performance computing and data center environments.
These disk interface types differ in terms of performance, reliability, compatibility, and cost, and are suitable for different application scenarios and requirements. Selecting the appropriate disk interface type considers the host device's interface support, data transfer needs, and budget constraints.

2. Advantages of disk partitioning

Manage and organize data : Partitioning can help you better manage and organize the data on your disk. By splitting the disk into multiple regions, you can store different types of data in different partitions, such as operating system files, applications, user data, etc. This allows for better organization of files and makes them easier to manage and maintain. Without partitioning, all data is stored on the same disk, which can lead to data clutter and difficulty in management.
Performance : Partitioning can have an impact on disk performance. Disk access can be made more efficient by distributing data across multiple partitions. For example, allocating operating system and program files to one partition and user data to another partition can reduce the moving distance of the magnetic head and increase read and write speeds. When there are no partitions, all data is stored in the same area, which may cause frequent movement of the magnetic head and reduce access efficiency.
Security and stability : By storing system and user data separately in different partitions, the security and stability of the system can be improved. If a system failure or data corruption occurs, it may only affect a specific partition and not the data on the entire disk. Without partitioning, the security and stability of your data may be at greater risk because the data on the entire disk is at the same risk.
Multi-boot system : Partitioning makes it possible to install multiple operating systems on the same disk. Each operating system can be located in a different partition, which enables multi-boot and allows the user to select which operating system to run at boot time. You cannot easily implement a multi-boot system without partitioning the disk.
Compatibility : Some file systems require specific partition types when used. By partitioning the disk, you can choose the appropriate partition type to support the required file system. Without partitions, the requirements of a particular file system may not be met.
In summary, disk partitioning provides better data management, performance, security, and flexibility. It allows better organization and management of data on disk, improves performance, provides data security and stability, and allows for multi-boot systems and compatibility of different file systems. Without partitioning, these benefits and features would not be possible.

3. Disk partition

Under Linux, the detailed steps for disk formatting, partitioning and mounting are as follows:

1. Determine the disk device

Use the following command to view available disk devices:

# fdisk -l
Disk /dev/mmcblk1: 7456 MB, 7818182656 bytes, 15269888 sectors
238592 cylinders, 4 heads, 16 sectors/track
Units: sectors of 1 * 512 = 512 bytes

Disk /dev/mmcblk1 doesn't contain a valid partition table
Disk /dev/mmcblk1boot0: 4 MB, 4194304 bytes, 8192 sectors
128 cylinders, 4 heads, 16 sectors/track
Units: sectors of 1 * 512 = 512 bytes

Disk /dev/mmcblk1boot0 doesn't contain a valid partition table
Disk /dev/mmcblk1boot1: 4 MB, 4194304 bytes, 8192 sectors
128 cylinders, 4 heads, 16 sectors/track
Units: sectors of 1 * 512 = 512 bytes

Disk /dev/mmcblk1boot1 doesn't contain a valid partition table
Disk /dev/mmcblk0: 15 GB, 15931539456 bytes, 31116288 sectors
486192 cylinders, 4 heads, 16 sectors/track
Units: sectors of 1 * 512 = 512 bytes

Device       Boot StartCHS    EndCHS        StartLBA     EndLBA    Sectors  Size Id Type
/dev/mmcblk0p1 *  0,32,33     8,73,1            2048     133119     131072 64.0M  c Win95 FAT32 (LBA)
/dev/mmcblk0p2    8,73,2      912,229,21      133120   31116287   30983168 14.783 Linux

From the above it can be concluded:

/dev/mmcblk1 : A disk with a capacity of 7456 MB. 238592 cylinders, 4 heads, 16 sectors per track. There is no valid partition table on the disk.

/dev/mmcblk1boot0 and /dev/mmcblk1boot1 are the boot sectors of the disk and are 4 MB in size, but they do not have a valid partition table.

/dev/mmcblk0 : A disk with a capacity of 15 GB. 486192 cylinders, 4 heads, 16 sectors per track. Contains two partitions:

  • /dev/mmcblk0p1 is the boot partition with a size of 64.0M and uses the Win95 FAT32 (LBA) file system.
  • /dev/mmcblk0p2 is the second partition, 14.7G in size, using the Linux file system (ID 83).

2. Use the fdisk command to partition the disk

# fdisk /dev/mmcblk1

The number of cylinders for this disk is set to 238592.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)

Command (m for help):

At this time, the command bar prompts to enter 'm' , and you can see the following parameters:

Command (m for help): m
Command Action
a       toggle a bootable flag
b       edit bsd disklabel
c       toggle the dos compatibility flag
d       delete a partition
l       list known partition types
n       add a new partition
o       create a new empty DOS partition table
p       print the partition table
q       quit without saving changes
s       create a new empty Sun disklabel
t       change a partition's system id
u       change display/entry units
v       verify the partition table
w       write table to disk and exit
x       extra functionality (experts only)

Command (m for help): 

The meaning of each command is as follows:

  • a: toggle a bootable flag
  • b: Edit BSD disk label (edit bsd disklabel)
  • c: toggle the dos compatibility flag
  • d: delete a partition
  • l: List known partition types (list known partition types)
  • n: add a new partition
  • o: Create a new empty DOS partition table (create a new empty DOS partition table)
  • p: print the partition table
  • q: quit without saving changes
  • s: create a new empty Sun disklabel (create a new empty Sun disklabel)
  • t: change a partition's system id
  • u: change display/entry units
  • v: verify the partition table
  • w: write table to disk and exit (write table to disk and exit)
  • x: Extra functionality (experts only) Continue below to create a partition:
Command (m for help): n
Partition type
   p   primary partition (1-4)
   e   extended
p
Partition number (1-4): 1
First sector (16-15269887default 16)
Using default value 16
Last sector or +size
{,K,M,G,T} (16-15269887default 15269887): +32M

Command (m for help): n
Partition type
   p   primary partition (1-4)
   e   extended

p
Partition number (1-4): 2
First sector (65552-15269887default 65552)
Using default value 65552
Last sector or +size
{,K,M,G,T} (65552-15269887default 15269887): 
Using default value 15269887

Command (m for help): t
Partition number (1-4): 1
Hex code (type L to list codes): c
Changed system type of partition 1 to c (Win95 FAT32 (LBA))

Command (m for help): a
Partition number (1-4): 1

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table
[ 1334.059435]  mmcblk1: p1 p2

Here is a detailed explanation of the command entered above:

  1. Create a new partition using command 'n' :
  • Select the primary partition type and enter 'p' .
  • Enter the partition number, select 1 here .
  • Enter the starting sector, the default is 16, you can directly press the Enter key to use the default value.
  • Enter the end sector or partition size. Enter '+32M' here to indicate that the partition size is 32MB.
  1. Create a new partition again using command 'n' :
  • Select the primary partition type and enter 'p' .
  • Enter the partition number, select 2 here .
  • Enter the starting sector, the default is 65552, you can directly press the Enter key to use the default value.
  • Enter the end sector or partition size. The default value 15269887 is used here.
  1. Use the command 't' to set the partition type:
  • Enter the partition number of the type to be set, select 1 here .
  • Enter the Hex code (Hex code). Entering 'c' here means setting the system type of partition 1 to Win95 FAT32 (LBA).
  1. Use command 'a' to set the boot flag:
  • Enter the partition number to set the boot flag, select 1 here .
  1. Use command 'w' to save changes and exit:
  • Confirm that the partition table has been modified, and call ioctl() to re-read the partition table.
  • Prompt that the partition table has been modified and the changes were saved successfully.
Finally, the disk partition table will be modified, and partition 1 will be set to Win95 FAT32 (LBA) type and set as the boot partition.
Please note that these operations may have an impact on the data on the disk, please make sure to back up important data before performing such operations .

4. Disk formatting

Disk formatting is the process of creating a file system on a disk in preparation for storing data. With formatting, the disk is partitioned into logical blocks and a file system structure is created for storing and organizing files. Formatting a disk will clear all data on the disk and provide it with a clean file system environment in which it can begin storing new data.
Here, we format the above two partitions into Fat32 format file system and ext4 format file system respectively.
  • Format '/dev/mmcblk1p1' to a Fat32 format file system
  • Format '/dev/mmcblk1p2' to an ext4 format file system

Fat32 format, use the command as follows:

mkfs.vfat -F 32 -n "boot" /dev/mmcblk1p1

The meaning of each option is explained below:

  • -F 32: Specifies the file system type to be created as FAT32.
  • -n MyVolume: Set the volume label to "MyVolume", which will be displayed as the name of the file system.
  • /dev/mmcblk1p1: is the device or partition to be formatted

ext4 format, use the following command:

mkfs.ext4 -F -L  "rootfs"  /dev/mmcblk1p2

-/bin/sh: mkfs.ext4: not found 

The meaning of each option is explained below:

  • -F: Force formatting even if the device is mounted.
  • -L "rootfs": Set the file system label to "rootfs", which will be displayed as the name of the file system.
  • /dev/mmcblk1p2: The device or partition to be formatted.
Our file system here does not support the mkfs.ext4 format, but its twin brother "mke2fs" can be used with the following instructions:
mke2fs -F -L "rootfs" /dev/mmcblk1p2

Filesystem label=rootfs
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
475136 inodes, 1900542 blocks
95027 blocks (5%) reserved for the super user
First data block=0
Maximum filesystem blocks=4194304
58 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
        32768983041638402293762949128192008847361605632
/ # 
Now that we have formatted the above two partitions, the next step is to mount the partitions.

5. Disk mounting

1. Create a mount point

First, you need to select a directory as a mount point. You can use the mkdir command to create an empty directory as a mount point, for example:
mkdir /mnt/boot

2. Execute the mount command

Use the mount command to mount the file system to the specified mount point, for example:

mount /dev/mmcblk1p1 /mnt/boot

Use the " df " command to check whether the mounting is successful. The command is as follows:

# df -a
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/root             15141732    161948  14188824   1% /
devtmpfs                216388         0    216388   0% /dev
proc                         0         0         0   0% /proc
tmpfs                   249668         0    249668   0% /tmp
sysfs                        0         0         0   0% /sys
devpts                       0         0         0   0% /dev/pts
/dev/mmcblk1p1           32260         1     32260   0% /mnt/boot

It is obvious that the '/dev/mmcblk1p1' partition has been successfully mounted to the '/mnt/boot' directory.

3. Access the file system

Now, files and directories in the file system can be accessed and manipulated through the mount point.
For example, you can use the cd command to enter the mount point, and use other file operation commands to read and write files:
cd /mnt/boot
touch test.txt
Then power off and restart the development board, and check again whether there is a test.txt file under '/mnt/boot':
# ls /mnt/boot/
/ # 
Obviously there is no test.txt file. The '/dev/mmcblk1p1' partition of the disk is not mounted to the '/mnt/boot' directory, so the test.txt file cannot be seen under '/mnt/boot'. .
# df -a
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/root             15141732    161948  14188824   1% /
devtmpfs                216388         0    216388   0% /dev
proc                         0         0         0   0% /proc
tmpfs                   249668         0    249668   0% /tmp
sysfs                        0         0         0   0% /sys
devpts                       0         0         0   0% /dev/pts
The test.txt file is saved in the '/dev/mmcblk1p1' partition of the disk. After power failure, you need to manually mount it to the '/mnt/boot' directory to view the test.txt file, as follows:
# mount /dev/mmcblk1p1 /mnt/boot
[  179.885442] FAT-fs (mmcblk1p1): Volume was not properly unmounted. Some data may be corrupt. Please run fsck.

# ls /mnt/boot/
test.txt
#

Another partition is mounted as follows:

mkdir /mnt/rootfs
mount /dev/mmcblk1p2 /mnt/rootfs
# df -h
Filesystem                Size      Used Available Use% Mounted on
/dev/root                14.4G    158.2M     13.5G   1% /
devtmpfs                211.3M         0    211.3M   0% /dev
tmpfs                   243.8M         0    243.8M   0% /tmp
/dev/mmcblk1p1           31.5M       512     31.5M   0% /mnt/boot
/dev/mmcblk1p2            7.1G     20.0K      6.8G   0% /mnt/rootfs

6. Automatically mount when booting

1. Device path mounting

If you want to automatically mount the partition when the system starts, you can edit the /etc/fstab file and add the corresponding entries. For example:
#<file system>  <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    defaults        0       0
tmpfs           /tmp            tmpfs   defaults        0       0
sysfs           /sys            sysfs   defaults        0       0
/dev/mmcblk1p1  /mnt/boot       vfat    defaults        0       0
/dev/mmcblk1p2  /mnt/rootfs     ext4    defaults        0       0

Restart the development board and use the 'df' command to check whether it is automatically mounted.

# df -h
Filesystem                Size      Used Available Use% Mounted on
/dev/root                14.4G    158.2M     13.5G   1% /
devtmpfs                211.3M         0    211.3M   0% /dev
tmpfs                   243.8M         0    243.8M   0% /tmp
/dev/mmcblk1p1           31.5M       512     31.5M   0% /mnt/boot
/dev/mmcblk1p2            7.1G     20.0K      6.8G   0% /mnt/rootfs

ok, automatic mounting is successful.

2.UUID mounting

Another mounting method, here I will teach you how to use UUID for automatic mounting, as follows:

Get the UUID of a partition: Use the following command to get the UUID of each partition:

# blkid 
/dev/mmcblk0p2: LABEL="rootfs" UUID="4bdc82c7-5e83-4992-9966-cd99a2317944" TYPE="ext4"
/dev/mmcblk0p1: LABEL="boot" UUID="DF8D-2A71" TYPE="vfat"
/dev/mmcblk1p2: LABEL="rootfs" UUID="54b75bd6-7cdf-4e80-aa48-1af163bf61f3" TYPE="ext2"
/dev/mmcblk1p1: TYPE="vfat"

Edit the /etc/fstab file and add the appropriate entries. For example:

#<file system>  <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    defaults        0       0
tmpfs           /tmp            tmpfs   defaults        0       0
sysfs           /sys            sysfs   defaults        0       0
UUID=54b75bd6-7cdf-4e80-aa48-1af163bf61f3   /mnt/rootfs ext4 defaults 0 0

After saving, restart the development board and successfully mount it automatically, as follows:

# df -h
Filesystem                Size      Used Available Use% Mounted on
/dev/root                14.4G    158.2M     13.5G   1% /
devtmpfs                211.3M         0    211.3M   0% /dev
tmpfs                   243.8M         0    243.8M   0% /tmp
/dev/mmcblk1p2            7.1G     20.0K      6.8G   0% /mnt/rootfs
When mounting a file system, you can use the device path (such as /dev/mmcblk1p1) or the UUID of the file system to identify the partition to be mounted. Each of these two methods has some differences and benefits:

1. Device path (/dev/mmcblk1p1):

  • Identify the path to the partition: Using the device path is a straightforward and simple way to identify the partition to be mounted. It is based on the physical path of the device file and can explicitly specify the partition to be mounted. For example, '/dev/mmcblk1p1' represents the first partition of the second MMC type disk.

  • Relatively easy to remember: Device paths are usually short and easy to remember because they are directly related to the name of the device file.

However, device paths may be affected by device plugging and unplugging. The device path may change if there are multiple disks in your system or if the device connection status changes.

2. File system UUID:

  • Uniqueness of identifying partitions: Each file system has a unique UUID (Universally Unique Identifier) ​​that is used to identify the partition. The UUID is generated when the file system is created and is globally unique. It is not affected by the device connection state, so even if the device path changes, the UUID will remain the same.

  • Stability and persistence: Using UUID to mount partitions can provide a more stable and durable mounting method, because even if the system is restarted or the device connection status is changed, the partition identified by the UUID can still be found accurately.

  • Better for automation and scripting: Using UUID makes it easier to automate and script because UUID provides a fixed identifier to uniquely identify a specific partition.

In general, mounting using device path or UUID are both viable methods, depending on your needs and usage scenarios. If your system does not frequently plug and unplug devices and does not involve automation, using device paths may be simpler and more straightforward. And if you need a more stable and durable mounting method that is more suitable for automated operations, using UUID is more reliable and recommended.
That’s the end of today’s content. Thank you all for watching. If there is anything wrong, please criticize and correct me. See you next time!
-END-

Recommended articles from past issues:

1. Detailed explanation of network transplantation and debugging of u-boot

2.u-boot startup process analysis - the most complete and detailed in history

3. Detailed explanation of EMMC and SD card operation commands of u-boot command

4.Transplant the Linux 6.3.5 system to the imx6ull development board

5. Rootfs root file system creation and mounting method - detailed explanation

For more knowledge about embedded C language, FreeRTOS, RT-Thread, Linux application programming, Linux driver and other related knowledge, follow the public account [Embedded Linux Knowledge Sharing], and watch the follow-up exciting content in time.


 
EEWorld WeChat Subscription

 
EEWorld WeChat Service Number

 
AutoDevelopers

About Us Customer Service Contact Information Datasheet Sitemap LatestNews

Room 1530, Zhongguancun MOOC Times Building,Block B, 18 Zhongguancun Street, Haidian District,Beijing, China Tel:(010)82350740 Postcode:100190

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号