Linux disable one cpu

Linux Hotplug a CPU and Disable CPU Cores At Run Time

I would like to dynamically enable or disable a CPU on a running system. How do I hotplug a CPU on a running Linux system? How do I disable cpu cores on a Linux operating system at run time?

Linux kernel does supports cpu-hotplug mechanism. You can enable or disable CPU or CPU core without a system reboot. CPU hotplug is not just useful to replace defective components it can also be applied in other contexts to increase the productivity of a system. For example on a single system running multiple Linux partitions, as the workloads change it would be extremely useful to be able to move CPUs from one partition to the next as required without rebooting or interrupting the workloads. [donotprint]

Tutorial details
Difficulty level Intermediate
Root privileges Yes
Requirements None
Est. reading time 5m

[/donotprint]This is known as dynamic partitioning. Other applications include Instant Capacity on Demand where extra CPUs are present in a system but aren’t activated. This is useful for customers that predict growth and therefore the need for more computing power but do not have at the time of purchase the means to afford. Please note that not all server supports cpu hotplug but almost all server can support disabling or enabling cpu core on a Linux operating systems. There are couple OEMS that support NUMA hardware which are hot pluggable as well, where physical node insertion and removal require support for CPU hotplug. This tutorial will explain how to hotplug a cpu and disable/enable core on a Linux.

List all current cpus and cores in the system

Type the following command:
# cd /sys/devices/system/cpu
# ls -l

Sample output:

I’ve total 8 core cpu logically started from cpu0 to cpu7. To get more human readable format, try:
# lscpu
Sample outputs:

Under each directory you would find an “online” file which is the control file to logically online/offline a processor.

How do I logically turn off (offline) cpu#6 ?

Warning : It is not possible to disable CPU0 on Linux systems i.e do not try to take cpu0 offline. Some architectures may have some special dependency on a certain CPU. For e.g in IA64 platforms we have ability to sent platform interrupts to the OS. a.k.a Corrected Platform Error Interrupts (CPEI). In current ACPI specifications, we didn’t have a way to change the target CPU. Hence if the current ACPI version doesn’t support such re-direction, we disable that CPU by making it not-removable. In such cases you will also notice that the online file is missing under cpu0.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Type the following command:
# echo 0 > /sys/devices/system/cpu/cpu6/online
# grep «processor» /proc/cpuinfo

How do I logically turn on (online) cpu#6 ?

Type the following command:
# echo 1 > /sys/devices/system/cpu/cpu6/online
# grep «processor» /proc/cpuinfo
Sample session:

Fig.01: Howto enable and disable CPU core in on a multi-core server

How do I verify cpu is online and offline?

Type the following cat command to see a list of cpus which are online:
# cat /sys/devices/system/cpu/online
To see a list of all offline cpus, run:
# cat /sys/devices/system/cpu/offline

Further readings:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

How to do such a similar thing for a hard disk…Juts unmount it or anything else is necessaey to remove and then add other.

Just unmount it and if it is hotplug just replace it.

I’m really curious about this. Can anyone comment if they’ve actually tried it? I’m not sure if any of the x86_(64) systems I’ve ever worked with support this capability – anyone know of systems that do?

You need high end servers such as IBM Power6 series to actually add or remove CPU / memory without rebooting the server. This is called Capacity Upgrade on Demand (CUoD). Other vendor such as Sun and HP also provides the same stuff. Your average server only support hard disk hot-plug. Another example is HP ProLiant ML570 G2 business server powered by Intel Xeon CPUs. Ask, your vendor for CUoD aware server and you will get the list. Be prepared to pay extra for all these fancy features 😉

It’s really works !
On my desktop Atom 330 (dual core + hyperthreading = 4 CPU), i can disable 3 CPUs of 4 🙂

I tried to offline a core in my i386 (kernel 2.6), but I was notified a permission denied.

$ echo 1 > /sys/devices/system/cpu/cpu1/online
bash: /sys/devices/system/cpu/cpu1/online: Permission denied
stefano@stefano-laptop:

$ sudo echo 1 > /sys/devices/system/cpu/cpu1/online
bash: /sys/devices/system/cpu/cpu1/online: Permission denied

Can anybody tell me y? Is it by default enabled in the latest versions?
Thx

You must be root user to hotplug a CPU.

I also tried with sudo, as I reported in the post, but didn’t work.
Moreover, in visudo I’ve set:

stefano ALL=(ALL) ALL

sudo does not support the > operator
Run the command using sudo -i to get an interactive prompt first

Ok, I’v managed.
Thx.
S.

Could you please tell us how you managed, I get the same error “access denied” when run as root

Not only high-end servers – CPU/memory hotplugging is often used in virtualized systems.

I have put cpu 1 to 3 offline.
When I online a cpu I get the following message:
(root @ rhel5)
# echo 1 > /sys/devices/system/cpu/cpu1/online
-bash: echo: write error: Invalid argument

Anyone else got the same message and a solution to this problem?

It works. But system will crash if you unplugging CPU or core which currently busy by some process.

I’m looking at taskset utility to resolve this problem

I also get the same problem: “echo: write error: Invalid argument”
Did anyone find a resolution for this?

For the people confused by “echo: write error: Invalid argument”: Is the CPU already enabled (if trying to enable it) or disabled (if trying to disable it)? AFAICT, the kernel produces an error when you try to put the CPU in the state it is already in, instead of just ignoring the request.

For the people getting permission errors:
Use “echo 0 | sudo tee /sys/devices/system/cpu/cpu6/online” instead of “sudo echo 0 > /sys/devices/system/cpu/cpu6/online”.

As Vivek points out, you need to be root to hotplug a CPU. You might think “But I used sudo”. However, when you use “>”, bash (or your shell, if you use something else) is responsible for opening the file that you’re trying to write to, and then setting that opened file as the destination for stdout (file descriptor 1). bash will then execute “sudo echo 0”, which will cause sudo to do its magic and run “echo 0” as root. Unfortunately, bash isn’t running as root, so it will fail to open /sys/devices/system/cpu/cpu6/online.

By instead piping the output of the echo to sudo tee, tee becomes responsible for opening the file and writing to it. Since tee is run under sudo, it can actually succeed.

I only have a file

/sys/devices/system/cpu/online that contains the id of cores like that 0-15. How can I disable one of cores? How can I know online cores number by shell script commands?

You can know online core number by this command:
lscpu | grep ^On

Does anyone know if this actually de-energises the CPU? In other words, does the disabled core/processor still use power?

Q: Why can’t i remove CPU0 on some systems?
A: Some architectures may have some special dependency on a certain CPU.

For e.g in IA64 platforms we have ability to sent platform interrupts to the
OS. a.k.a Corrected Platform Error Interrupts (CPEI). In current ACPI
specifications, we didn’t have a way to change the target CPU. Hence if the
current ACPI version doesn’t support such re-direction, we disable that CPU
by making it not-removable.

In such cases you will also notice that the online file is missing under cpu0.

Christian: changing a state on a CPU core does not remove it from Linux. Thus, the device would still be polled and would require power. One way to disable a core would be outside of the OS. If supported, one would change the number of CPU cores within the bios. This of course would require an outage.

If my server has 2 physical processor and I want to disable and remove only one processor which has 2 cores if I make offline the CPU cores as per above given commands to remove one physical processor but I dont want to get stop/kill/terminate any job which is handeling by that CPU which i want to remove.

Is there any possibility to migrate all running process from one CPU/Cores to another CPU/Cores or stop handelling any new request to any specific CPU/cores.

I am able to disable the CPU By this process but it get enabled again after every reboot.

It is safe to make a cpu offline and bring it back online if the CPU is stuck with softlock error with CPU showing 100% utilization ? Will it affect the applications which were being served before the CPU went into a softlock ?

Источник

отключение процессорных ядер на четырехъядерном процессоре в Linux

Я хочу отключить 3 ядра процессора и запустить свой процессор на одном ядре. Я использовал команду: maxcpus=1 . Но после этого я выполнил эту команду ls /sys/devices/system/cpu . Это все еще показывает cpu0,cpu1,cpu2,cpu3 .

Я также попытался: echo 0 > /sys/devices/system/cpu3/online но я получаю следующее сообщение об ошибке: no such file or directory .

Если вы хотите выключить все процессоры, кроме cpu0 :

Ввод maxcpus=1 в приглашении оболочки не имеет никакого эффекта. Точнее, она устанавливает переменную maxcpus на значение 1 в этой оболочке, которая не имеет никакого другого эффекта. Вы можете установить количество процессоров во время загрузки, передавая в maxcpus качестве параметра ядра . Для этого вам нужно изменить конфигурацию вашего загрузчика (например, изменить командную строку ядра в U-Boot).

Вы не обязательно выключаете или отключаете ядра.

вы бы использовали процессоры и набор задач

Процессор определяет список процессоров и узлов памяти .

Файловая система cpuset представляет собой интерфейс псевдофайловой системы к механизму cpuset ядра, который используется для управления размещением процессора и размещения памяти в процессах. Обычно он монтируется в / dev / cpuset.

В системах с ядрами, скомпилированными со встроенной поддержкой процессоров, все процессы подключены к процессору, и процессоры всегда присутствуют. Если система поддерживает cpusets, то она будет иметь запись nodev cpuset в файле / proc / filesystems. Смонтировав файловую систему cpuset (см. Раздел «ПРИМЕР» ниже), администратор может настроить процессорные наборы в системе для управления процессором и размещением процессов в памяти в этой системе. По умолчанию, если конфигурация cpuset в системе не изменена или файловая система cpuset даже не смонтирована, тогда механизм cpuset, хотя и присутствует, не влияет на поведение системы.

Процессоры системы включают в себя все логические процессоры, на которых может выполняться процесс, в том числе, если они имеются, несколько процессорных ядер в пакете и гиперпотоки в ядре процессора. Узлы памяти включают в себя все отдельные банки основной памяти; В малых и SMP-системах обычно имеется только один узел памяти, который содержит всю основную память системы, в то время как системы NUMA (с неоднородным доступом к памяти) имеют несколько узлов памяти.

Короче говоря, если у вас 1 процессор с 6 ядрами, вы сконфигурируете процессоры и запускаете процесс в процессоре , настроенном только на одном ядре, например, на ядре № 3. Если бы это был параллельный процесс, все это было бы ограничено этим одним ядром, так что если вы запустили 4 процесса в данном процессоре, для которого определено только одно ядро, то каждый из 4 процессов получит 25% загрузки процессора на ядре № 3.

Основываясь на этом, обычно происходит то, что процессор настроен так, что

  • в системе с ядром 200+, например, cpusetA — это ядра 0 . 60, где бы они ни находились, cpusetB — это ядра 61..70; cpusetC — это ядра 71..80; и так далее, однако администратор / архитектор выбирает для настройки.
  • cpusetA выделяется для определенных пользователей и / или определенных программ; cpusetB выделен разным пользователям / программам; и так далее.
  • пользователь запускает задание (процесс), которое запрашивает N ядер . в данном процессоре, и теперь эти множественные (параллельные) процессы ограничиваются данным процессором. А для тех N параллелей, ограниченных данным процессором, каждый из этих процессов будет / должен использовать привязку процессора или привязку процессора, чтобы эти параллельные процессы не перебрасывались на разных ядрах внутри процессора.

Источник

Читайте также:  Как запустить kali linux с флешки без установки
Оцените статью