# Create partitions and filesystems

> Split a disk with MBR or GPT using fdisk, gdisk and parted, then put ext4, XFS, FAT, exFAT, Btrfs or swap on it.

Source: https://aminbytes.dev/bytes/devices-and-filesystems/partitions-and-filesystems/


A brand new disk is just a long row of empty blocks. Before Linux can store a single file on it, you need two things: a **partition table** that splits the disk into pieces, and a **filesystem** inside each piece that keeps track of files, folders and free space.

You'll do this when you add a disk to a server, prepare a USB stick, or set up a VM. Getting it wrong can wipe data, so it's worth learning the tools on a practice disk first.

## Practice on a fake disk

You don't need a spare disk. A file can pretend to be one through a **loop device**:

```console
$ truncate -s 1G disk.img
$ sudo losetup -fP --show disk.img
/dev/loop0
```

`-f` picks the first free loop device, `-P` makes the kernel look for partitions on it, and `--show` prints the name. Use `/dev/loop0` wherever this byte says `/dev/sdb`, and `/dev/loop0p1` for `/dev/sdb1`. When you're done, run `sudo losetup -d /dev/loop0`.

> [!TIP]
> This works on any Linux machine or VM. In Docker you need `--privileged`, because a normal container may not create loop devices.

## How disks and partitions are named

Disks show up as files in `/dev`. The name tells you the kind of disk:

| Device | What it is | First partition |
| --- | --- | --- |
| `/dev/sda`, `/dev/sdb` | SATA, SAS or USB disk (SCSI driver) | `/dev/sda1` |
| `/dev/nvme0n1` | NVMe SSD (controller 0, namespace 1) | `/dev/nvme0n1p1` |
| `/dev/vda` | virtio disk in a VM | `/dev/vda1` |
| `/dev/mmcblk0` | SD card or eMMC | `/dev/mmcblk0p1` |

`lsblk` shows them as a tree:

```console
$ lsblk
NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
sda           8:0    0    40G  0 disk
├─sda1        8:1    0     1G  0 part /boot/efi
├─sda2        8:2    0     2G  0 part [SWAP]
└─sda3        8:3    0    37G  0 part /
sdb           8:16   0    10G  0 disk
```

## MBR and GPT

There are two partition table formats. You'll meet both on the exam.

**MBR** (Master Boot Record, also called "DOS" or "msdos") is the old one from the PC BIOS days. It lives in the first 512-byte sector of the disk: 446 bytes of boot code, a 64-byte table with room for four entries, and the signature `0x55AA`.

- At most **4 primary** partitions.
- Need more? Make one of the four an **extended** partition. Inside it you create **logical** partitions, which are always numbered from 5 (`sda5`, `sda6`, ...).
- Sizes are stored as 32-bit sector numbers, so with 512-byte sectors the limit is **2 TiB**.
- Partition types are one byte: `83` Linux, `82` Linux swap, `8e` Linux LVM, `ef` EFI System, `7` NTFS/exFAT, `c` FAT32.

**GPT** (GUID Partition Table) is part of the UEFI standard and the default today.

- **128 partitions** by default, no primary/extended/logical games.
- 64-bit sector numbers: disks up to about 8 ZiB.
- Each partition has a unique ID (PARTUUID) and can have a name.
- A **backup copy** of the table sits at the end of the disk, so a damaged header can be rebuilt.
- Sector 0 holds a **protective MBR**: a fake entry covering the whole disk, so old MBR tools see the disk as "in use" and leave it alone.

 (Side note: You can boot from GPT on an old BIOS machine too. GRUB then needs a tiny "BIOS boot partition" (gdisk type `EF02`) to store its code. On an MBR disk it hides that code in the unused gap right after the MBR instead.)

## fdisk: the classic

`fdisk` comes with util-linux, so it's on every distribution. Modern versions handle both MBR and GPT. `fdisk -l` lists every disk and its partitions:

```console
$ sudo fdisk -l /dev/sda
Disk /dev/sda: 40 GiB, 42949672960 bytes, 83886080 sectors
Disk model: QEMU HARDDISK
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 5C0B7F7A-2B1E-4C5D-9C1A-6E2F2E1A3B4C

Device       Start      End  Sectors Size Type
/dev/sda1     2048  2099199  2097152   1G EFI System
/dev/sda2  2099200  6293503  4194304   2G Linux swap
/dev/sda3  6293504 83884031 77590528  37G Linux filesystem
```

Run it without `-l` to edit. It's interactive: one-letter commands, and **nothing is written until you press `w`**. Here we make a GPT table with a 600 MiB data partition and use the rest as swap:

```console
$ sudo fdisk /dev/sdb

Command (m for help): g
Created a new GPT disklabel (GUID: 0E4D6A1C-...).

Command (m for help): n
Partition number (1-128, default 1):
First sector (2048-2097118, default 2048):
Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-2097118, default 2095103): +600M

Created a new partition 1 of type 'Linux filesystem' and of size 600 MiB.

Command (m for help): n
Partition number (2-128, default 2):
First sector (1230848-2097118, default 1230848):
Last sector, +/-sectors or +/-size{K,M,G,T,P} (1230848-2097118, default 2095103):

Created a new partition 2 of type 'Linux filesystem' and of size 422 MiB.

Command (m for help): t
Partition number (1,2, default 2): 2
Partition type or alias (type L to list all): swap

Changed type of partition 'Linux filesystem' to 'Linux swap'.

Command (m for help): w
The partition table has been altered.
Syncing disks.
```

The commands you need:

| Key | Does |
| --- | --- |
| `m` | help |
| `p` | print the partition table |
| `n` | new partition |
| `d` | delete a partition |
| `t` | change a partition's type (`L` lists the types) |
| `g` / `o` | create a new empty GPT / MBR (DOS) table |
| `w` | write the changes and quit |
| `q` | quit **without** saving |

On an MBR disk, `n` first asks `p` (primary) or `e` (extended), and types are hex codes like `82` for swap.

## gdisk: GPT only

`gdisk` ("GPT fdisk") looks almost the same as fdisk but only writes GPT. Install it with `apt install gdisk` or `dnf install gdisk`. If you open an MBR disk, it offers to convert it to GPT in memory, and only does it if you write.

```console
$ sudo gdisk /dev/sdb
Command (? for help): n
Partition number (1-128, default 1):
First sector (34-2097118, default = 2048) or {+-}size{KMGTP}:
Last sector (2048-2097118, default = 2095103) or {+-}size{KMGTP}: +600M
Current type is 8300 (Linux filesystem)
Hex code or GUID (L to show codes, Enter = 8300):
Changed type of partition to 'Linux filesystem'

Command (? for help): w
Do you want to proceed? (Y/N): y
OK; writing new GUID partition table (GPT) to /dev/sdb.
```

gdisk uses four-digit type codes: `8300` Linux filesystem, `8200` Linux swap, `EF00` EFI System, `8E00` Linux LVM, `0700` Microsoft basic data. `o` creates a new empty GPT, and `?` lists the rest. For scripts there's a sibling tool, `sgdisk`.

## parted: one command at a time

`parted` (GNU Parted) works with both table types and can run as one-shot commands, which is handy in scripts. Sizes can be in MiB, GB or percent.

```bash
sudo parted /dev/sdb mklabel gpt
sudo parted /dev/sdb mkpart data ext4 1MiB 600MiB
sudo parted /dev/sdb mkpart swap linux-swap 600MiB 100%
sudo parted /dev/sdb print
```

```text
Model: Loopback device (loopback)
Disk /dev/sdb: 1074MB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:

Number  Start   End     Size   File system  Name  Flags
 1      1049kB  629MB   628MB               data
 2      629MB   1073MB  444MB               swap
```

On GPT, the word after `mkpart` is the partition **name**. On MBR it's the kind: `primary`, `extended` or `logical`.

> [!WARNING]
> Two parted habits catch people out. First, parted writes **immediately**: there is no `w` step and no undo. Second, the `ext4` in `mkpart` only sets the partition type. It doesn't create a filesystem, so the File system column stays empty until you run `mkfs`.

Other useful parted commands: `rm 2` deletes partition 2, `resizepart 1 800MiB` moves the end of partition 1, and `unit MiB print` changes how sizes are shown. Run `parted /dev/sdb` without a command to get an interactive `(parted)` prompt.

## Making filesystems with mkfs

Now each partition needs a filesystem. `mkfs` is a front end: `mkfs -t ext4 /dev/sdb1` simply runs `mkfs.ext4 /dev/sdb1`. You can call either form.

```console
$ sudo mkfs.ext4 -L data /dev/sdb1
mke2fs 1.47.0 (5-Feb-2023)
Discarding device blocks: done
Creating filesystem with 153600 4k blocks and 38400 inodes
Filesystem UUID: 3c1d6f0e-8a7b-4e2a-9d61-0f6b2a9c4e11
Superblock backups stored on blocks:
	32768, 98304

Allocating group tables: done
Writing inode tables: done
Creating journal (4096 blocks): done
Writing superblocks and filesystem accounting information: done
```

The filesystems the exam expects you to know:

| Filesystem | Create with | Label option | Notes |
| --- | --- | --- | --- |
| ext2 | `mkfs.ext2` | `-L` | No journal. Still fine for small `/boot` or flash. |
| ext3 | `mkfs.ext3` | `-L` | ext2 plus a **journal**, so recovery after a crash is fast. |
| ext4 | `mkfs.ext4` | `-L` | Default on Debian and Ubuntu. Extents, bigger files and volumes. |
| XFS | `mkfs.xfs` | `-L` (max 12 chars) | Default on RHEL. Fast with big files. Can grow, can't shrink. |
| VFAT | `mkfs.vfat` or `mkfs.fat` | `-n` (max 11 chars) | FAT32 for USB sticks and the EFI System Partition. Add `-F 32` to force FAT32. |
| exFAT | `mkfs.exfat` | `-L` | For big USB drives and SD cards. No 4 GiB file limit like FAT32. |
| Btrfs | `mkfs.btrfs` | `-L` | Copy-on-write, snapshots, multi-device. Default on Fedora. |

All the ext tools come from one program, `mke2fs`, in the `e2fsprogs` package. The others need their own package: `xfsprogs`, `dosfstools`, `exfatprogs` and `btrfs-progs`.

```bash
sudo mkfs.xfs -L logs /dev/sdb1
sudo mkfs.vfat -F 32 -n USBSTICK /dev/sdc1
sudo mkfs.exfat -L CAMERA /dev/sdd1
```

> [!CAUTION]
> `mkfs` destroys whatever was on the partition. Run `lsblk -f` first and read the device name twice. `mkfs.xfs` refuses to overwrite an existing filesystem unless you add `-f`, which is a nice safety net.

 (Side note: Recent `mkfs.xfs` versions refuse filesystems smaller than 300 MB. That's why the practice partition here is 600 MiB.)

## Swap with mkswap

**Swap** is disk space the kernel uses when RAM runs low. A swap partition doesn't get a filesystem. Instead, `mkswap` writes a small header, and `swapon` turns it on:

```console
$ sudo mkswap -L swap /dev/sdb2
Setting up swapspace version 1, size = 422 MiB (442494976 bytes)
LABEL=swap, UUID=9f1e2c3d-4b5a-4c6d-8e7f-0a1b2c3d4e5f
$ sudo swapon /dev/sdb2
$ swapon --show
NAME      TYPE      SIZE USED PRIO
/dev/sda2 partition   2G   0B   -2
/dev/sdb2 partition 422M   0B   -3
```

`swapoff /dev/sdb2` turns it off again. Give the partition the swap type (`82` on MBR, `8200` in gdisk, `swap` in fdisk) so other tools recognize it.

A **swap file** works too, and is easier to resize later:

```bash
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
```

## Btrfs basics

Btrfs (say "butter FS") does things the other filesystems leave to separate tools. Three of them are on the exam.

**Multi-device filesystems.** One Btrfs filesystem can span several disks, with a RAID profile for data (`-d`) and metadata (`-m`):

```bash
sudo mkfs.btrfs -L pool -d raid1 -m raid1 /dev/sdb /dev/sdc
sudo mount /dev/sdb /mnt/pool
sudo btrfs filesystem show /mnt/pool
sudo btrfs device add /dev/sdd /mnt/pool
sudo btrfs balance start /mnt/pool
```

You can mount it through any of its devices. `btrfs device add` grows the pool while it's mounted, and `balance` spreads the existing data over the new disk.

**Subvolumes.** A subvolume looks like a normal directory, but it's a separate tree you can mount on its own and snapshot:

```console
$ sudo btrfs subvolume create /mnt/pool/home
Create subvolume '/mnt/pool/home'
$ sudo btrfs subvolume list /mnt/pool
ID 256 gen 9 top level 5 path home
$ sudo btrfs subvolume snapshot /mnt/pool/home /mnt/pool/home-before-upgrade
$ sudo mount -o subvol=home /dev/sdb /home
```

Snapshots are instant and take no space at first, because Btrfs only copies blocks when they change (that's **copy-on-write**).

**Compression.** Btrfs can compress data as it writes. Turn it on for a whole mount, or for one directory:

```bash
sudo mount -o compress=zstd /dev/sdb /mnt/pool
sudo btrfs property set /mnt/pool/logs compression zstd
```

Algorithms are `zlib`, `lzo` and `zstd`. Only data written after you turn it on gets compressed.

> [!NOTE]
> Fedora uses Btrfs by default, and SUSE uses it for the root filesystem. RHEL dropped Btrfs from its kernel in version 8, so on RHEL you use XFS (or ext4) instead.

## Exam checklist

- MBR: 4 primary partitions, or 3 primary + 1 extended holding logical ones (numbered from 5). Limit 2 TiB.
- GPT: 128 partitions by default, backup table at the end of the disk, protective MBR in sector 0. Needed for UEFI and disks over 2 TiB.
- `fdisk` and `gdisk` keep changes in memory until `w`. `q` quits without saving. `parted` writes **immediately**.
- `fdisk -l` lists disks. Type codes: `83`/`82`/`8e`/`ef` in MBR, `8300`/`8200`/`8E00`/`EF00` in gdisk.
- `mkfs -t TYPE` is the same as `mkfs.TYPE`. ext2/3/4 are made by `mke2fs`. ext3 = ext2 + journal.
- Labels: `-L` for ext, XFS, exFAT and Btrfs, but `-n` for `mkfs.vfat`.
- Swap: `mkswap` to prepare, `swapon`/`swapoff` to use, `swapon --show` to list.
- Btrfs: `mkfs.btrfs` with several devices and `-d`/`-m` profiles, `btrfs subvolume create|list|snapshot`, mount with `subvol=`, compression with `compress=zstd`.


## Byte check

1. A new 4 TB disk must hold six partitions and later be used on a UEFI machine. Which partition table fits?
   - MBR with three primary partitions and one extended
   - **GPT** (correct)
   - MBR with six primary partitions
   MBR tops out at 2 TiB with 512-byte sectors and only has four primary slots. GPT handles huge disks, holds 128 partitions by default and is what UEFI expects.

2. You ran `parted /dev/sdb mkpart data ext4 1MiB 100%`. What is on the new partition now?
   - An empty ext4 filesystem
   - **Nothing yet: parted only wrote the partition table entry, you still need `mkfs.ext4`** (correct)
   - A swap area
   The filesystem type in `mkpart` is only a hint for the partition type. You create the actual filesystem afterwards with `mkfs`.

3. Which command prepares `/dev/sdb3` to be used as swap?
   - `mkfs -t swap /dev/sdb3`
   - `swapon /dev/sdb3`
   - **`mkswap /dev/sdb3`** (correct)
   `mkswap` writes the swap signature. Only after that can `swapon` start using it.


