How to limit usable CPU and Memory size in Linux

The GRUB(GNU GRand Unified Bootloader), which allows the user to select an operating system or kernel to be loaded at system boot time. GRUB also allows the user to pass arguments to the kernel. In this post, we learn how to use GRUB to limit the usable CPU and Memory size in Linux.

Set the usable CPU and memory in /etc/sysconfig/grub

1
2
3
4
5
6
7
8
$ vim /etc/sysconfig/grub
GRUB_TIMEOUT=5
GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)"
GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=centos/root rd.lvm.lv=centos/swap rhgb quiet nr_cpus=16 mem=128G"
GRUB_DISABLE_RECOVERY="true"

Use grub2-mkconfig to generate GRUB configuration file

1
2
3
4
5
6
7
8
9
$ grub2-mkconfig -o /boot/grub2/grub.cfg
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-5.7.12-1.el7.elrepo.x86_64
Found initrd image: /boot/initramfs-5.7.12-1.el7.elrepo.x86_64.img
Found linux image: /boot/vmlinuz-3.10.0-1160.el7.x86_64
Found initrd image: /boot/initramfs-3.10.0-1160.el7.x86_64.img
Found linux image: /boot/vmlinuz-0-rescue-18e8af5bca4c485d9c09627e96ff8276
Found initrd image: /boot/initramfs-0-rescue-18e8af5bca4c485d9c09627e96ff8276.img
done

Check the generated GRUB configuration file

1
2
3
4
$ egrep "mem=128|nr_cpus" /boot/grub2/grub.cfg
linux16 /vmlinuz-5.7.12-1.el7.elrepo.x86_64 root=/dev/mapper/centos-root ro crashkernel=auto rd.lvm.lv=centos/root rd.lvm.lv=centos/swap rhgb quiet nr_cpus=16 mem=128G
linux16 /vmlinuz-3.10.0-1160.el7.x86_64 root=/dev/mapper/centos-root ro crashkernel=auto rd.lvm.lv=centos/root rd.lvm.lv=centos/swap rhgb quiet nr_cpus=16 mem=128G
linux16 /vmlinuz-0-rescue-18e8af5bca4c485d9c09627e96ff8276 root=/dev/mapper/centos-root ro crashkernel=auto rd.lvm.lv=centos/root rd.lvm.lv=centos/swap rhgb quiet nr_cpus=16 mem=128G

Verify the usable CPU and Memory size after reboot

1
2
3
4
5
6
7
$ reboot

$ lscpu | grep "^CPU(s):"
CPU(s): 16

$ cat /proc/meminfo | grep MemTotal:
MemTotal: 129471308 kB