It is known the way to disable logical CPUs in Linux, basically with echo 0 > /sys/devices/system/cpu/cpu<number>/online. This way, you are only telling to the OS to ignore that given (<number>) CPU.
My question goes further, is it possible not only to ignore it but to turn it off physically programmatically? I want that CPU to not receive any power, in order to make its energy consumption zero.
I know that it is possible disable cores from the BIOS (not always), but I want to know whether is possible to do it within a certain program or not.
When you do echo 0 > /sys/devices/system/cpu/cpu<number>/online, what happens next depends on the particular CPU. On ARM embedded systems the kernel will typically disable the clock that drives the particular core PLL so effectively you get what you want.
On Intel X86 systems, you can only disable the interrupts and call the hlt instruction (which Linux Kernel does). This effectively puts CPU to the power-saving state until it is woken up by another CPU at user request. If you have a laptop, you can verify that power draw indeed goes down when you disable the core by reading the power from /sys/class/power_supply/BAT{0,1}/current_now (or uevent for all values such as voltage) or using the "powertop" utility.
For example, here's the call chain for disabling the CPU core in Linux Kernel for Intel CPUs.
https://github.com/torvalds/linux/blob/master/drivers/cpufreq/intel_pstate.c
arch/x86/kernel/smp.c: smp_ops.play_dead = native_play_dead,
arch/x86/kernel/smpboot.c : native_play_dead() -> play_dead_common() -> local_irq_disable()
Before that, CPUFREQ also sets the CPU to the lowest power consumption level before disabling it though this does not seem to be strictly necessary.
intel_pstate_stop_cpu -> intel_cpufreq_stop_cpu -> intel_pstate_set_min_pstate -> intel_pstate_set_pstate -> wrmsrl_on_cpu(cpu->cpu, MSR_IA32_PERF_CTL, pstate_funcs.get_val(cpu, pstate));
On Intel X86 there does not seem to be an official way to disable the actual clocks and voltage regulators. Even if there was, it would be specific to the motherboard and thus your closest bet might be looking into BIOS such as coreboot.
Hmm, I realized I have no idea about Intel except looking into kernel sources.
In Windows 10 it became possible with new power management commands CPMINCORES CPMAXCORES.
Powercfg -setacvalueindex scheme_current sub_processor CPMAXCORES 50
Powercfg -setacvalueindex scheme_current sub_processor CPMINCORES 25
Powercfg -setactive scheme_current
Here 50% of cores are assigned for desired deep sleep, and 25% are forbidden to be parked. Very good in numeric simulations requiring increased clock rate (15% boost on Intel)
You can not choose which cores to park, but Windows 10 kernel checks Intel's Comet Lake and newer "prefered" (more power efficient) cores, and starts parking those not preferred.
It is not a strict parking, so at high load the kernel can use these cores with very low load.
just in case if you are looking for alternatives
You can get closest to this by using governors like cpufreq. Make Linux exclude the CPU and power saving mode will ensure that the core runs at minimal frequency.
You can also isolate cpus from the scheduler at kernel boot time.
Add isolcpus=0,1,2 to the kernel boot parameters.
https://www.linuxtopia.org/online_books/linux_kernel/kernel_configuration/re46.html
I know this is an old question but one way to disable the CPU is via grub config.
If you add to end of GRUB_CMDLINE_LINUX in /etc/default/grub (assuming you are using a standard Linux dist, if you are using an appliance the location of the grub config may be different), e.g.:
GRUB_CMDLINE_LINUX=".......Current config here **maxcpus**=2"
Then remake you grub config by running
grub2-mkconfig -o /boot/grub2/grub.cfg (or grub-mkconfig -o /boot/grub2/grub.cfg depending on your installation). Some distros may require nr_cpus instead of maxcpus.
Just some extra info:
If you are running a server with Multiple physical CPU then disabling one CPU may will most likely disable the memory set that is linked to that CPU, therefore it may have an effect on the performance of the server
Disabling the CPU this way, will not effect your type 1 hypervisor from accessing the CPU (this is based on xen hypervisor, I believe it will apply to vmware as well, if anyone can provide confirmation would be great). Depending on virtualbox setup, it may restrict the amount of CPU you can allocate to VM's unless you are running para-virtualization.
I am unsure however if you will have any power savings, most servers and even desktops these days, already control the power well, putting to sleep any device not needed for the current load. My concern would be by reducing the number of CPU (cores) then you will just be moving the load to the remaining CPU and due to the need to schedule the processors time, and potentially having instructions queued, and the effect of having a smaller number of cores available for interrupts (eg: network traffic), it may have a negative effect on power consumption.
AFAIK there is no system call or library function available as of now. or even ioctl implementation. So apart from creating new module / system call there are two ways I can think of :
using ASM asm(<assembly code>); where assembly code being architecture specific asm code to modify cpu flag.
system call in c (man 3 system). Assuming you just want to do it through c.
Related
I have the latest coffeelake machine which is primarily used as a storage server. The average workload on each core (4 cores) is around 5-10% when running a storage server alone.
I want to run vtune measurements of a workload on this machine using Intel Sampling drivers. However, I'm doubtful whether or not the measurements will be accurate given the storage server application is concurrently running.
But as the intel's documents suggest, the sampling drivers get installed on the Linux kernel, so is it really the case that the measurements will be inaccurate if run concurrently with other applications? In other words, how exactly do the intel sampling drivers work? Are they able to distinguish between the workload process and other processes running on the system?
If VTune is like the Linux PAPI subsystem that perf uses, it basically saves/restores HW event counter registers on context switch, along with the regular register state. So events like instructions and uops_retired should be unaffected. And effects on other events will be due to actual impacts, like extra cache misses.
(The basic mechanism for HW performance events are that each logical core has its own programmable perf counters that increment every time some microarchitectural event happens. If one overflows, it raises an interrupt for the driver to collect the count. Or for perf record type of functionality, perf or VTune would program them to count down so trigger an interrupt regularly, and sample the saved user-space RIP at that point. This produces some funky effects on a superscalar out-of-order CPU, like "blaming" the instruction waiting for data, not the cache miss load itself, for example. But the key point is that the inside-the-core events are totally per-core. The uncore / L3 cache events count stuff about shared resources like L3 cache, so are more easily disturbed by system load.)
Another point is that if you are running something on a CPU core, Linux isn't going to want to schedule other tasks there. So your background load will tend to avoid whichever core your test is running on, leaving it able to use 100% of a single core without a lot of context switches. (Although network / disk interrupts might still be handled on that core.)
So yes, you should be able to fairly accurately measure what's actually happening in your process while it runs on a system that's not totally idle. That might be a bit different from what would happen if it were run on a fully idle system, but probably not much different. Especially if it's single-threaded, or you can limit it to fewer than all of your cores, so there's at least one left for the OS to schedule other tasks onto.
I want to create a simulation of an actual device on an x86 Linux Kernel. Part of this will involve simulating timings as close to possible as I can get. Based on some research it seems I will need at least microsecond resolution timing. I understand that on a non-realtime system it won't be possible to get perfect timing, but I don't perfect, just as close as I can get, perhaps with hacking around with thread scheduling / preemption options.
What I actually want to do is perform an action every interval, i.e. run a some code every Xµs. I've been trying to research the best ways to do this from a Kernel driver as well as some research into whether it's possible to do this reasonably accurately from user mode (keeping the above paragraph in mind). One of the first things that caught my eye was the HPET timer, that is programmable to generate interrupts based on programmable comparators. Unfortunately, it seems on many chipsets it has been rather buggy in the past, and there's not much information on using it for anything that obtaining a timestamp or using it as the main clock source. The linux Kernel provides an HPET driver that in the past, seemed to provide both kernel and user mode interfaces, but seems only to provide a barely documented usermode interface in more recent kernel versions. I've also read about various other kernel functions and interfaces such as the hrtimer interface and the various delay functions, though I'm having a bit of trouble understanding them and if they are suited for my purpose.
Given my current use case, what are the best options I have running recurring events at a µs resolution from say a kernel driver? Obviously accuracy is probably my biggest criteria, but ease of use would be second.
Well, it's possible to achieve your accuracy in userspace -- clock_nanosleep is one ideal option, which has relative and absolute mode. Since clock_nanosleep is based on hrtimer in kernel mode, you may want to use hrtimer if you'd like to implement it in kernel space.
However, to make the timer work accurately, there're two IMPORTENT things worth mentioning.
You should set the timerslack of your process (either by writing nonzero value in ns to /proc/self/timerslack_ns or via prctl(PR_SET_TIMERSLACK,...)). This value is considered as the 'tolerance' of the timer.
The CPU power management also matters here. The CPU has many different Cstates, each of which has a different exit latency. So you need to configure your cpuidle module to not use Cstates other than C0, e.g. for an Intel CPU you could simply write 1 to /sys/devices/system/cpu/cpu$c/cpuidle/state$s/disable to disable state $s of CPU $c. Or just add idle=poll to your kernel options to let CPU keep active (in C0) while kernel idle. NOTE that this significantly influences the power of the computer and leads the cooling fans to make noise.
You can get a timer with delays under 10 microseconds if the two things mentioned above are configured correctly. There is a trade-off between latency and power consumption that you should made.
I replaced my i5 CPU of my laptop with a i7 CPU, so that it can run faster.
But because that the power of i7 is more, and the temperature is also higher than before, my laptop crashed frequently. So, I used cpupower to specify the MAX frequency of CPU, it works.
Now, my question is "Is there a way to specify the CPU frequency as a cmd_line parameter of the linux kernel, at boot time?", so I can ensure that the system has booted stably and correctly.
Btw, if new cpu runs under the freq of 2.5GHz at most, everything is ok, and the performance is twice more than the older. so I think it is worth to change my CPU.
thanks a lot!
UPDATE - 2018-11-25
Also, I want to mention that there are below commands to use CpuFreq subsystem without using any tool (like cpufrequtils as it is used to achieve the same purpose). Sometimes these tools lack features, or they simply don't work as we want. Because CpuFreq core creates a sysfs directory under /sys/devices/system/cpu/, some attributes are available as read-write to be changed at kernel level. These attribute changes are called as policies as CpuFreq has a Policy Interface in sysfs. Below commands should work at boot time and be persistent between boot times.
If scaling governor is selected as intel_pstate; (This part may help to avoid higher frequencies if intel_pstate is decided to be used)
Also turbo can be disabled because of wanting to prevent higher frequencies.
echo "1" | sudo tee /sys/devices/system/cpu/intel_pstate/no_turbo
After this, below command can be useful.
echo "70" | sudo tee /sys/devices/system/cpu/intel_pstate/max_perf_pct (70 can be changed by another percentage if clock speed and turbo speed is higher numbers. 70-80 should be enough to not reaching above 2.5 GHz)
This attribute is explained as below in https://www.kernel.org/doc/Documentation/cpu-freq/intel-pstate.txt and may help to decrement higher CPU frequencies.
max_perf_pct: Limits the maximum P-State that will be requested by the
driver. It states it as a percentage of the available performance.
Because P-States are operational states and by going Pn to P0, frequencies are increasing. So, limiting maximum P-states by percent of the maximum supported performance level can be useful. Check this link: https://software.intel.com/en-us/blogs/2008/05/29/what-exactly-is-a-p-state-pt-1
Also, in intel_pstate, CPUs share same properties. While using intel_pstate as scaling governor, per-CPU performance limits as cpufreq attributes (e.g. scaling_max_freq) can be used by adding below kernel parameter;
intel_pstate=per_cpu_perf_limits
Otherwise, CPUs can be set separately;
echo -n 2457600 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
echo -n 2457600 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq
echo -n 2457600 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq
echo -n 2457600 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq
But, there is an important part which is built-in script in Linux (/etc/init.d/ondemand). If ondemand or powersave is used as used as scaling governor, then configurations we set (like above) can collide with this script. The script should be disabled by below command;
sudo /usr/sbin/update-rc.d ondemand disable
Further info is in here: https://help.ubuntu.com/community/UbuntuStudio/Setting_CPU_Governor
After disabling ondemand, other scaling governors (like userspace, performance) can be set and be used by regarding above configuration.
These are all fundamental commands (both below and above part) and they should help solving CPU frequency scaling problem as I also wanted to give these information for future reference.
First of all, I want to give some information about CPU Frequency Scaling.
Three terms are related to this process (they are layers of a subsystem which is called as "CPU Performance Scaling") and they should be basically reviewed and discussed to ensure that everything is understood correctly.
CPUFreq Core
Scaling Driver
Scaling Governor
CPUFreq core is a basic framework and contains a common code infrastructure for all platforms that support this feature.
CPU frequency driver change CPU P-states that are managed by scaling governors and it communicates with hardware.
(P-States mean they are operational, in contrast of C-States, which they are idle states except C0 state. C0 state is also busy and active state.)
Scaling governors implement scaling algorithms.
By the way, CPU Performance Scaling is a deep topic and there are many things that should be considered. Basically, with the information above, below commands should meet your needs.
Firstly, I think intel_pstate is used as a scaling driver for now in your laptop. So, disabling it may provides us more advanced settings and more governors (intel_pstate has two governors that are powersave and performance). I think powersave is default governor for intel_pstate.
sudo vi /etc/default/grub
Add intel_pstate=disable to the GRUB_CMDLINE_LINUX_DEFAULT parameter.
GRUB_CMDLINE_LINUX_DEFAULT="intel_pstate=disable"
After adding the parameter execute below commands.
modprobe acpi-cpufreq
sudo update-grub
You can check kernel parameters at boot by below command
cat /proc/cmdline
By this way, acpi-cpufreq will be enabled as the scaling driver (because of disabling intel_pstate). So, the next thing can be setting governor as userspace to run the CPU as desired frequencies or letting it be as the default (ondemand should be default setting for acpi-cpufreq).
First Way of Setting Governor and Maximum Frequency Setting
If you want to change scaling governor (e.g. to userspace):
sudo update-rc.d ondemand disable (This command prevents above commands to be reset after reboot)
sudo apt install cpufrequtils (To control the CPU frequency scaling deamon)
echo 'GOVERNOR="userspace"' | sudo tee /etc/default/cpufrequtils
After these steps, we should have acpi-cpufreq as the scaling driver and ondemand (if you didn't change the governor) as the scaling governor. So, the last thing seem to be setting max frequency of the CPU.
Editing /etc/default/cpufrequtils like below should set CPU frequencies. If the file doesn't exist, create it.
MAX_SPEED="2457600"
MIN_SPEED="1536000"
Also check below lines in the same file.
ENABLE="true"
GOVERNOR="ondemand" (or userspace)
But, with this way, I think there is no guarentee for setting all CPU cores to the same frequency values. I saw some people say that below way (second way) set all CPU cores as their desired values but not first way.
Second Way of Setting Governor and Maximum Frequency Setting
Install tlp (Linux Power management tool)
sudo apt install tlp
After installing, edit /etc/default/tlp like below:
# Select a CPU frequency scaling governor: # ondemand, powersave,
performance, conservative # Intel Core i processor with intel_pstate
driver: # powersave, performance # Important: # You must
disable your distribution's governor settings or conflicts will #
occur. ondemand is sufficient for almost all workloads, you should
know # what you're doing! CPU_SCALING_GOVERNOR_ON_AC=ondemand
CPU_SCALING_GOVERNOR_ON_BAT=ondemand
# Set the min/max frequency available for the scaling governor. #
Possible values strongly depend on your CPU. For available frequencies
see # tlp-stat output, Section "+++ Processor".
CPU_SCALING_MIN_FREQ_ON_AC=0
CPU_SCALING_MAX_FREQ_ON_AC=0
CPU_SCALING_MIN_FREQ_ON_BAT=1536000
CPU_SCALING_MAX_FREQ_ON_BAT=2457600
Above settings should be kept after restarting or suspending the device.
I have tried to provide and explain ways to set the CPU frequency (also to keep settings persistent) and I may have forgotten something. So, please check the information above and try if these meet your needs. Also, you can use below command to ensure that everything is right.
cpufreq-info
Note: Please check below pages for more information.
Governors list
https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt
https://www.kernel.org/doc/html/v4.14/admin-guide/pm/cpufreq.html
https://www.kernel.org/doc/html/v4.12/admin-guide/pm/intel_pstate.html
eventually I have time to reply this because I'm busy for doing other things.
I tried all of above solutions, and choosed "tlp + lm-sensors + psensor".
The following is my opinions:
cpupower is a simple but relatively poor of features tool, it only can set the MAX/MIN frequenc of CPU and the governor.
cpufrequtils is basically same as cpupower, except that it base on
acpi drivers, not the Intel genuin one. I guess a Intel genuin
driver with p_state support should be better choice for Intel CPU.
tlp is my choice at last, it has more features to monitor/throttle
the temperature and frequence of CPU, and more configurable options.
Yes, as Erdem Savasci said, with tlp the MAX/MIN freqs of all CPU cores can be set within one step, while those can NOT do with cpufrequtils.
In addition, I installed the lm-sensors and psensor. The former can be think as a driver for querying the temperature/frequence/Fan-speed, the latter is a GUI panel that can show information as above mentioned.
With these tools, I belive that my cpu would be running stablly.
But the solution to "ensure CPU run stablly AT BOOT TIME" has not be found yet.
All of above are started after boot, aren't they?
Sorry for my poor english, I'm a Chinese. Hope I has expressed correctly things.
Thanks again!
I am interested in evaluating the behavior (latency, frequency) of SMI handling on Linux machine running CentOS and used for a (very) soft real time application.
What tools are recommended (hwlatdetect for CentOS?), and what is the best course of action to go about this?
If no good tools are available for CentOS, am I correct to assume that installing a
different OS on the same machine should yield the same results since the underlying hardware/bios are the same?
Is there any source for ballpark figures on these parameters.
The machines are X86_64 architecture, running CentOS 6.4 (kernel 2.6.32-358.23.2.el2.centos.plus.x86_64.)
SMIs can certainly happen during normal operation. My home desktop has a chipset-driven SMI every second and a half which is enabled in the chipset. I've also seen some servers that have them twice a second due to a BIOS-driven CPU frequency scaling scheme. However, some systems can go long periods of time without an SMI occurring so it really depends.
Question #1: hwlatdetect is one option to detect the latency of SMIs occurring on your system. BIOSBITS is another option which is a bootable CD that can identify if SMIs are occuring. You can also write your own test by creating a kernel module that spins in a loop and takes timestamps (using RDTSC). If you see a long gap between two timestamp readings, you could consult CPU MSR 0x34 to see if the SMI counter incremented which would indicate that an SMI happened.
If you want to generate an SMI, you can make a kernel module that does an OUT CPU instruction to port 0xb2, e.g. write a value of 0 to this port. (You can also time this SMI by gathering a timestamp just before and just after the write to port 0xB2).
Question #2, SMIs operate at a layer below the OS so which OS you choose, shouldn't have any impact.
Question #3: BIOSBITS recommends that SMI latencies be kept under 150 microseconds.
SMI will put your system into SMM (System Management Mode) mode, which will postpone the
normal execution of kernel during the SMI handling time period. In other words, SMM
is neither real mode nor protected mode as we know of normal operation of kernel,
instead it executes some special instruction kept in SMRAM (stored in Bios Firmware). To detect it's latency you can try to trigger an SMI (it can be software generated) and try to catch the total time spent in SMM mode. To accomplish this you can write a Linux kernel module, cause you'll be require some special privileges to issue an SMI (I think).
For real time systems I think it's nice if you can avoid these sort of interrupts like SMI.
You can check whether System Management Interrupts (SMI) are serviced or not with turbostat. For example:
# turbostat sleep 120
[check column SMI for value greater than 0]
Of course, from that you can also compute a SMI frequency.
Knowing that SMIs are actually happening at a certain rate is important information. But you also want to know how much time System Management Mode (SMM) spends in those interrupts. For example, if an SMI interruption is only very short than it might be irrelevant for your realtime application. On the other hand, if you have hardware with long SMI interruptions you probably want to talk to the vendor, configure the firmware differently (if possible) and or switch to other hardware with less intrusive SMM.
The perf tool has a mode that measures how many cycles are spend in SMM during SMIs (using the information provided by certain CPU counters). Example:
# perf stat -a -A --smi-cost -- sleep 120
Performance counter stats for 'system wide':
SMI cycles% SMI#
CPU0 0.0% 0
CPU1 0.0% 0
CPU2 0.0% 0
CPU3 0.0% 0
120.002927948 seconds time elapsed
You can also look at the raw values with:
# perf stat -a -A --smi-cost --metric-only -- sleep 120
From that you can compute how much time an SMI takes on average on your machine. (divide cycles difference by the number of cycles per time unit).
It certainly makes sense to cross check the CPU counter based results with empiric ones.
You can use the Linux Hardware Latency Detector that is integrated in the Linux Kernel. Usage example:
# echo hwlat > /sys/kernel/debug/tracing/current_tracer
# echo 1 > /sys/kernel/debug/tracing/tracing_thresh
# watch -d -n 5 cat /sys/kernel/debug/tracing/tracing_max_latency
# echo "Don't forget to disable it again"
# echo nop > /sys/kernel/debug/tracing/current_tracer
Those tools are available on CentOS/RHEL 7 and should be available on other distributions, as well.
Regarding ballpark figures: Recently I came across a HP 2011-ish ProLiant Gen8 Xeon server that fires 504 SMIs per minute. Perf computes a rate of 0.1 % in SMM, and based on the counter values the averge time spent in an SMI is as high as several microseconds - but the Linux hwlat detector doesn't detect such high interruptions on that system.
That SMI rate matches what HP documents in its Configuring and tuning
HPE ProLiant Servers for low-latency applications guide (October, 2017):
Disabling System Management Interrupts to the processor provides one of
the greatest benefits to low-latency environments.
Disabling the Processor Power and Utilization Monitoring SMI has the greatest
effect because it generates a processor interrupt eight times a second in G6
and later servers.
(emphasis mine; and that guide also documents other SMI sources)
On a Supermicro board with Intel Atom C3758 and an Intel NUC (i5-4250U) system of mine there are exactly zero SMIs counted.
On an Intel i7-6600U based Dell laptop, the system reports 8 SMIs per minute, but the aperf counter is lower than the (unhalted) cycles counter which isn't supposed to happen.
Actually, SMI is used for more than just keyboard emulation. Servers use SMI to report and correct ECC memory errors, ACPI uses SMI to communicate with BIOS and perform some tasks, even enabling and disabling ACPI is done through SMI, BIOS often intercepts power state changes through SMI... there's more, this is just a few examples.
According to wikipage on System Management Mode, SMI is not used during normal operation, except perhaps to emulate a PS/2 keyboard with a USB physical keyboard.
And most Linux systems are able to drive genuine USB keyboard without that emulation. You could configure your BIOS to disable it.
I am wondering if Intel's processor provides instructions in their instruction set
to turn on and off the multithreading or hyperthreading capability? Basically, I wanna
know if an Operating System can control these feature via instructions somehow?
Thank you so much
Mareike
Most operating systems have a facility for changing a process' CPU affinity, thereby restricting it to a single physical or virtual core. But multithreading is a program architecture, not a CPU facility.
I think that what you are trying to ask is, "Is there a way to prevent the OS from utilizing hyperthreading and/or multiple cores?"
The answer is, definitely. This isn't governed by a single instruction, and indeed it's not like you can just write a device driver that would automagically disable all of that hardware. Most of this depends on how the kernel configures the interrupt controllers at boot time.
When a machine is first started, there is a designated processor that is used for bootstrapping. It is the responsibility of the OS to configure the multiprocessor hardware accordingly. On PC platforms this would involve reading information about the multiprocessor configuration from in-memory tables provided by the boot firmware. This data would likely conform to either the ACPI or the Intel multiprocessor specifications. The kernel then uses that date to configure the APIC hardware accordingly.
Multithreading and multitasking are not special instructions or modes in the CPU. They're just fancy ways people who write operating systems use interrupts. There is a hardware timer, basically a counter being incremented by a clocking signal, that triggers an interrupt when it overflows. The exact interrupt is platform specific. In the olden days this timer is actually a separate chip/circuit on the motherboard that is simply attached to one of the CPU's interrupt pin. Modern CPUs have this timer built in. So, to turn off multithreading and multitasking the OS can simply disable the interrupt signal.
Alternatively, since it's the OS's job to actually schedule processes/threads, the OS can simply decide to ignore all threads and not run them.
Hyperthreading is a different thing. It sort of allows the OS to see a second virtual CPU that it can execute code on. Never had to deal with the thing directly so I'm not sure how to turn it off (or even if it is possible).
There is no x86 instruction that disables HyperThreading or additional cores. But, there is BIOS settings that can turn off these features. Because it can be set in BIOS, it requires rebooting, and generally it's beyond OS control. There is Windows booting option that limits the number of active core, but HyperThreading can be turn on/off only by BIOS. Current Intel's HyperThreading implementation doesn't allow dynamic turn on and off (and it won't be easily implemented in a near time).
I have assumed 'multithreading' in your question as 'hardware multithreading' which is technically identical to HyperThreading. However, if you really intended software-level multithreading (i.e., multitasking), then it's totally different question. It is (almost) impossible for modern operating systems since they are by default supports multitasking. And, this question actually doesn't make sense. It can make sense if you want to run MS-DOS (as real mode of x86, where a single task can be done).
p.s. Please note that 'multithreading' can be either hardware or software. Also I agree all others' answers such as processor/thread affinity.