CentOS / RHEL : How to prioritize the devices used for swap partition

If you check the output of the swapon -s command, you would see the Priority column. The priority column defines the order in which the swap devices are used when required. In our example below the priority -1 is higher than the priority -2 (as the values are in negative).

# swapon -s
Filename    Type  Size Used Priority
/dev/dm-1               partition 268435452 0 -1
/swapfile               file       102396 0 -2

By default when the priorities are assigned as the swap devices are created and added as swap. But we can also change the priority of the devices.

Temporarily change the swap priority

1. Before changing the priority make sure the swap device is not in use by the system.

# free
              total        used        free      shared  buff/cache   available
Mem:      263847032     4561048   214238864      324524    45047120   257755920
Swap:     268537848           0   268537848

As seen in the output above, 0 MB of swap is being used currently.

2. Disable the swap devices

# swapoff /swapfile 
# swapoff /dev/dm-1
# swapon -s
Filename    Type  Size Used Priority
/dev/dm-1                               partition 268435452 0 -1

3. set the priority of the swap device /swapfile as 5 which higher than the priority of the other swap device(-1).

# swapon -p 5 /swapfile
# swapon -s
Filename    Type  Size     Used Priority
/dev/dm-1               partition 268435452 0     -1
/swapfile               file     102396     0      5

Persistently change the swap priority

To change the priority of swap device permanently, we have to edit the /etc/fstab file accordingly.

1. First, take the backup of /etc/fstab file.

# cp -p /etc/fstab /etc/fstba_orig

2. Modify the swap device priority of /swapfile to 5 from -2.

# vi /etc/fstab
/dev/mapper/vg_os-lv_swap swap                    swap    defaults        0 0
/swapfile           swap                    swap    pri=9         0 0
Related Post