パーティション操作の基礎知識
概念の整理
ロジック⇒物理層のレイヤ順では以下のような概念がある。
ファイルシステム
ストレージ上のデータを「ファイル」として管理する仕組み(ext4, FAT32など)。
パーティション
物理ディスクを論理的に分割した領域
ストレージには1つのパーティションテーブルが存在し、パーティションを管理する。MBR(Master Boot Record)とGPT(GUID Partition Table)とがある。
以下のような種類がある。
システムパーティション: OSやブートローダを配置する領域
プライマリパーティション: OSをインストールするためのパーティション
拡張パーティション: MBRの制限(プライマリ最大4つ)を回避するための仕組み
論理パーティション: 拡張パーティションの中に複数設定されるパーティション領域
リカバリパーティション: OS復旧用の領域
1つのパーティションは同一のファイルシステムによってフォーマットされる。
1つのストレージには複数のパーティションが存在するため、それらの情報をパーティションテーブルによって管理する。すなわち、1つのパーティションテーブルによって複数のパーティションが管理される。
ディスクイメージ(.img)
SDカードやディスクの「バイト列」を丸ごとコピーしたファイル。
コマンドの整理
e2fsck
ext2 / ext3 / ext4 ファイルシステム専用の整合性チェック&修復ツール
resize2fs
ext2 / ext3 / ext4 ファイルシステムそのもののサイズを変更。
パーティションではなくファイルシステム内部のサイズを変更する。
fdisk/parted
パーティションテーブルを表示・編集するツール。
losetup
イメージファイルを「ブロックデバイス」として扱う(デバイスファイルを生成)。
-f:空いているloopデバイスを使う
-P:パーティションを自動認識してloopXp1などを作成
--offset:開始位置を手動指定
--sizelimit:サイズを制限(乖離対策)
mount/umount
ファイルシステムをOSに接続する。
-o ro,norecover:読み取り専用、ジャーナル再生しない(壊れたFSでも読みやすく)
fsck
ファイルシステムの整合性をチェック・修復。
ケース別コマンド早見表
パーティションテーブルの形式確認
MBRの編集はfdisk, GPTの編集はgdiskを使う。
partedはどちらにも使える。
code:bash
# partedを使う方法
$ sudo parted xxx.img
GNU Parted 3.4
Using /home/hht/src/hand_camera/xxx.img
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) unit s
(parted) print
Model: (file)
Disk /home/hht/src/hand_camera/xxx.img: 9411712s
Sector size (logical/physical): 512B/512B
Partition Table: msdos # msdosならMBR, gptならGPT
Disk Flags:
Number Start End Size Type File system Flags
1 8192s 532479s 524288s primary fat32 lba
2 532480s 9411711s 8879232s primary ext4
# fdiskを使う方法
$ fdisk -l xxx.img
Disk xxx.img: 4.49 GiB, 4818796544 bytes, 9411712 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos # dosならMBR, gptならGPT
Disk identifier: 0xd1f84a17
Device Boot Start End Sectors Size Id Type
xxx.img1 8192 532479 524288 256M c W95 FAT32 (LBA)
xxx.img2 532480 9411711 8879232 4.2G 83 Linux
.imgファイルからファイルを取り出す
code:bash
# デバイスファイルの生成
sudo losetup -Pf --show xxx.img
/dev/loop0
# sudo mount /dev/mapper/loop0p2 /mnt/rpi-root
パーティションテーブルの修正
以下では、.imgファイルのパーティションテーブルと実際のパーティションサイズとが乖離している場合に、パーティションテーブルを実態に合わせて修正する。
code:bash
$ sudo parted example.img
GNU Parted 3.4
Using /home/hht/src/hand_camera/example.img
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) unit s
(parted) print
Error: Can't have a partition outside the disk!
Ignore/Cancel? Ignore
Error: Can't have a partition outside the disk!
Ignore/Cancel? Ignore
Model: (file)
Disk /home/hht/src/hand_camera/example.img: 9411712s
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:
Number Start End Size Type File system Flags
1 8192s 532479s 524288s primary fat32 lba
2 532480s 25698303s 25165824s primary ext4
(parted) resizepart
Partition number? 2
Warning: Shrinking a partition can cause data loss, are you sure you want to continue?
Yes/No? Yes
(parted) quit