Skip to content

磁盘分区

分区是在硬盘上创建一个或几个便于分别管理的区域。一个硬盘能够被划分为一个或多个分区,分区方案被被存储在分区表中。

linux 中最为经典的分区工具就是 fdisk。目前还提供了一种LVM机制来将分区作为一个存储池使用。

分区要想正常使用还必须创建文件系统

分区表

分区表中存储了分区方案,目前主流的有两种分区表类型:

  • MBR(Master Boot Record): 主引导记录
  • GTP(GUID Partition Table): GUID 分区表

MBR

主引导记录是存储设备(磁盘)最开始的 512 字节,其中包含了操作系统启动加载器和分区表:

地址 长度 描述
0 440 代码区,系统启动加载器
440 4 选用磁盘标志
444 2 空值
446 64 标准 MBR 分区表规划(4 个 16byte 的主分区表入口)
510 2 MBR 标志位: 0x55AA

由于他的系统启动器只有 440 字节所以可以实现的功能非常少。还有他的分区只能规划四个(当然可以将分区规划为扩展分区来建立逻辑分区),并且最大支持 2T(扇区是 512byte 的磁盘如此,如果是 4K 扇区的支持 16T)的硬盘。

基于这种结构,我们可以使用 dd 来保存或者恢复 440 字节的引导代码来实现对系统引导的备份和恢复 MBR 的 512 字节实际上是一个扇区的大小

GPT

他是由 UEFI 标准定义的规范,使用 GUID(通用唯一识别码)来定义分区和分区类型:

gpt

上图每个 LBA 是 512 字节:

  1. LBA0: 兼容 MBR
  2. LBA1: GPT 头,存储了 GPT 分区表信息
  3. LBA2~33: 真正的分区数据

其中 2~33 定义分区表项目:

起始字节 长度 内容
0 16 字节 分区类型 GUID(固定的,例如 EFI 分区)
16 16 字节 分区 GUID(创建分区时随机生成)
32 8 字节 起始 LBA
40 8 字节 末尾 LBA
48 8 字节 属性标签(例如 60 表示只读)
56 72 字节 分区名称(可以包含 36 个 UTF-16 字符)

fdisk

由 util-linux 提供的fdisk命令来基于命令行创建分区表:

Bash
# 显示分区表
fdisk -l /dev/sda

# 创建分区表和分区
fdisk /dev/sda # 会进入命令

Command (m for help): m

Help:

  DOS (MBR)
   a   toggle a bootable flag
   b   edit nested BSD disklabel
   c   toggle the dos compatibility flag

  Generic
   d   delete a partition
   F   list free unpartitioned space
   l   list known partition types
   n   add a new partition
   p   print the partition table
   t   change a partition type
   v   verify the partition table
   i   print information about a partition

  Misc
   m   print this menu
   u   change display/entry units
   x   extra functionality (experts only)

  Script
   I   load disk layout from sfdisk script file
   O   dump disk layout to sfdisk script file

  Save & Exit
   w   write table to disk and exit
   q   quit without saving changes

  Create a new label
   g   create a new empty GPT partition table
   G   create a new empty SGI (IRIX) partition table
   o   create a new empty MBR (DOS) partition table
   s   create a new empty Sun partition table

Command (m for help):

最基本的流程:

  1. 创建分区表类型: g/o 对应 GPT 和 MBR
  2. 新建分区: n 根据提示输入开始分区、结束分区
  3. 转换分区类型: t GPT 需要创建 EFI 类型分区(0)
  4. 保存: w