Ядро линукс low latency

Зачем выбирать ядро ​​с малой задержкой вместо обычного или реального времени?

После установки Ubuntu Studio 12.04 я обнаружил, что она использует ядро ​​с низкой задержкой. Я искал, почему и как изменить обратно на реальный или общий. Но похоже, что эта часть Linux не так много освещена.

В: Почему ядро ​​с малой задержкой предпочитает обычное ядро ​​или ядро ​​реального времени?

PS: я уже прочитал ответы на этот вопрос и этот пост.

Вот несколько простых рекомендаций, которые помогут вам понять, какое ядро ​​и в каком порядке вам следует протестировать в соответствии с вашим вариантом использования.

  • Если для вашей системы не требуется низкая задержка, используйте ядро ​​-generic.
  • Если вам нужна система с низкой задержкой (например, для записи звука), пожалуйста, используйте ядро ​​-preempt в качестве первого выбора. Это уменьшает задержку, но не жертвует функциями энергосбережения. Он доступен только для 64-битных систем (также называемых amd64).
  • Если ядро ​​-preempt не обеспечивает достаточно низкой задержки для ваших нужд (или у вас 32-битная система), вам следует попробовать ядро ​​-lowlatency.
  • Если ядра -lowlatency недостаточно, вам следует попробовать ядро ​​-rt
  • Если ядро ​​-rt недостаточно стабильно для вас, вам следует попробовать ядро ​​-realtime

Так что это зависит от того, что вы будете делать с вашим студийным дистрибутивом. Для большинства пользователей, которым требуется быстрое время отклика конечного пользователя, универсальный режим подойдет просто, для других, которым необходимо профессиональное редактирование видео, где даже простое удаление кадра недопустимо, требуется ядро ​​реального времени.

Для более полного и понятного поста в блоге, прочитайте эту ссылку

Это сообщение в блоге не представляет никакого факта, это только теория . На самом деле, так оно и есть: процессор «останавливается» чаще, чтобы увидеть, есть ли какие-то процессы, требующие немедленного внимания. Это означает, что эти процессы будут выполняться раньше других, поэтому вы не пропустите кадры при кодировании или будете иметь огромные задержки между щелчками мыши и смертью противника. Это не означает, что все процессы завершатся раньше: на самом деле процессор теряет большую часть своего времени, решая, какой процесс будет выполняться дальше, и переключая контекст. Таким образом, общее время выполнения больше, и поэтому никто не запускает вытесняемое ядро ​​на машинах веб-сервера или базы данных. Но лучше всего для игровых серверов лучше всего использовать ядро ​​с частотой 300 Гц (или даже 1000 Гц).

Но в настоящее время процессоры имеют много ядер, поэтому, когда мало процессов, требующих внимания, их можно легко разместить на другом ядре, а не ждать, пока ядро ​​его возьмёт.

(stackexchange требует от меня ссылок / личного опыта: я инженер-электронщик, кровожадный нубгеймер, управляющий несколькими игровыми серверами на http://www.gamezoo.it ).

Так что, как правило, я бы сказал: если ваш процессор является мощным высокочастотным четырехъядерным процессором, работающим с большими числами, и вы обычно не открываете тонны веб-страниц при кодировании / декодировании / играх (да), вы могли бы просто попробуйте стандартное (или i686, или amd64, если они существуют) ядро ​​и имеют максимально возможную пропускную способность (т. е. необработанное вычисление числа, которое способен процессор). Если у вас возникли проблемы (они действительно должны быть незначительными) или ваша машина немного менее мощная, чем вершина рынка, выберите вариант -preempt.

Если вы работаете на младшей машине с одним или двумя ядрами, попробуйте опцию -lowlatency. Вы также можете попробовать -realtime, но вы обнаружите, что он имеет тенденцию блокировать процессы, пока те, которые работают в режиме реального времени, не закончили свою работу. Я считаю, что ядро ​​реального времени не является «ванильным», но имеет патч CONFIG_PREEMPT_RT. Я думаю, что ядра реального времени предназначены только для тех, кому нужно создавать одно приложение на встраиваемых системах, поэтому обычные пользователи настольных компьютеров не должны иметь реальных преимуществ, потому что они обычно запускают достаточное количество приложений одновременно.

Наконец, наиболее подходящие параметры ядра, если вы хотите самостоятельно перекомпилировать ядро, чтобы иметь рабочий стол с низкой задержкой:

Чтобы добавить немного энергосбережения, вы можете проверить это:

Источник

Ubuntu Documentation

Home

Ubuntu Studio Controls

Audio Handbook

FAQ

Other Resources and Links

About RealTime Kernels

Early on in Linux audio production, Real-Time kernels were the only way to get low- and no-latency audio for professional audio applications. However, since Linux 2.6, the real-time stack has been part of the Linux kernel, having a kernel patched with a real-time stack is no longer necessary.

RealTime Kernels Still Exist

However, there continued to be a demand for real-time kernels with a special patch. A patch does exist to enable process to have real-time process access to any process requesting it. This is good for applicance-like applications, such as audio mixers that use Linux (the Behringer X-series mixers and the Allen & Heath iLive series mixers are good examples). For desktop computer use, THIS IS A BAD IDEA.

Читайте также:  Настройка запуска windows с жесткого диска

Security Implications

All it would take is one malicious process to execute and take advantage of the real-time code to completely lock-out a user from their machine, turning that machine into part of a botnet or other malicious purpose. Real-Time processes have the potential to completely take-over a machine. This is the number one reason Ubuntu does not carry a Real-Time kernel.

Low-Latency Kernel

The Low-Latency Kernel included in Ubuntu Studio (and available in the Ubuntu repositories) does not allow such malicious code from locking-out a user from their machine. It does contain other optimizations, such as Preempt-RT being enabled in the kernel configuration, to achieve the lowest possible latency for audio and other applications, while keeping the user interface usable. Latency as low as 0.1 millisecond can and has been achieved using this kernel.

Summary

For desktop computer usage, using a real-time kernel can cause security nightmares. The low-latency kernel included in Ubuntu Studio is completely capable of low- to no- latency while not enabling malicious processes to lock-out a user from their computer.

UbuntuStudio/RealTimeKernel (последним исправлял пользователь eeickmeyer 2020-02-26 16:19:05)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

Источник

Low-Latency HOWTO

by Paul Winkler 9/11/2000
Maintained by Patrick Shirkey
additions by Patrick Shirkey, Eric Rzewnicki, Mark Knecht

Last update Monday 27 October 2008 08:57

This wiki-page has been created from http://lowlatency.linuxaudio.org/ on April 27, 2012. The content is pretty much outdated (linux-2.2, linux-2.4), nevertheless there is still some general good advice and info in this article.

Besides that, It’s a classic! It was a famous page in the early days of Linux-Audio. Treat it with respect. — Those who are interested in the original HTML can get a backup of the vhost’s docroot (1 html file, 1 gif image).

Introduction

For the latest kernel patches and to stay informed about the bleeding edge of realtime kernel lowlatency development visit the Realtime Low Latency Wiki.

For most users the latest 2.6 series kernels are sufficient for low latency. However there are a few things you have to configure. For example make sure you have “Generic PCI bus-master DMA support” on in the kernel, run your root filesystem on ext2 and partition your discs so that your software is not stored on the root filesystem partition. It’s also a good idea to have the disc you record to running on a seperate ide bus to the root filesystem disc and you definitely want to mount /tmp to tmpfs.

none /tmp tmpfs defaults 0 0

For audio you will want to use JACK and associated applications. Another important part of latency is getting your interrupt (IRQ) settings correct.

Info on setting IRQs

Contributed by Mark Knecht.

This is a simple, or difficult, subject. Due to the history of the PC architecture, PC’s first had 1 interrupt controller, and then with the AT architecture, added a second. This accounts for the sort of strange numbers I’m going to give you next.

Here’s the order of interrupt priority on a non-APIC machine:

0, 1, 8, 9, 10, 11, 12, 13, 14, 15, 3, 4, 5, 6, 7

0 is the highest priority
7 is the lowest priority

Potentially 9, 10, 11, 3, 4, 5, 6, 7 are made available to PCI slots on many motherboards. I won’t go into why the order is this way, but it is. You MUST look at your SPECIFIC motherboard to know what’s available to you. Many newer mobos allow you to change the irq settings for the pci interface in the BIOS. This is also useful for USB devices as the usb IRQ generally tags along with one of the pci slots. So you may be able to change the IRQ for your USB card by adjusting the the BIOS settings for the PCI slots. If you cannot adjust the settings in the BIOS your other option is to juggle the cards around the available slots. (NB — requires opening your case)

In my experience all audio cards want to be on IRQ’s 9, 10 or 11. It isn’t actually that important WHAT IRQ a card is on, but it IS IMPORTANT what devices are on higher IRQs. For instance, if Steve’s audio card is on IRQ 11, and nothing is on IRQ 9 or 10, then no problem. But if Steve was to insert a PCI graphics adapter on IRQ9, his audio card could start having trouble because the graphics adapter would have higher priority.

Читайте также:  Qualcomm atheros ar9485 wireless network adapter linux driver

Again, I won’t go into all the reasons why, but just assume that any device with a higher priority number (from the list above) gets in the way of devices with lower priorities.

One last thing about non-APIC, interrupts may be shared. Just because your card is on IRQ9 doesn’t mean that another device isn’t sharing IRQ9. What matters in this case is how many interrupts the other device is going to generate, and how well it’s driver is written.

How to find your IRQs

There are a few ways to do this. The easiest is to

But you can get more information from running

If you want to find the IRQs for your usb device you need to look for the usb bus controller and then compare its number with the results from.

APIC interrupts settings

The kernel must be configured to assign different vector numbers to specific interrupts. The standard kernel cannot do this but Clemens Ladisch has written a patch which adds this capability.

Historical info on upgrading linux kernel

This document is specifically aimed at those interested in using 2.4.x with Andrew Morton’s low-latency patch for audio purposes.

It’s not really hard when you know what to do, but there’s a lot of stuff to upgrade before you can compile and install the kernel if you are moving from linux 2.2.x. So if you are, don’t forget to read the section on updating your system files.

We suggest scanning through this whole document to get an overview before you start mucking with the kernel. Everything described here requires kernel configuration, and it’s easier to do it all in one go rather than rebuilding the kernel again for each feature you want. You should also read through the necessary upgrades to make sure you have all your software in order before you start configuring.

Downloading and Patching the Kernel

If that’s the case, remove the link:

Otherwise, if /usr/src/linux is a directory and not a symlink, rename it so the name includes the kernel version, e.g.:

This should patch without any problems. However some people have found that this works better:

Configuring and Building the New Kernel

should yield “1” or ‘on’. if not

to turn it on. Building your kernel with “Low latency scheduling” and “Control low latency with sysctl” will give you a /proc/sys/kernel/lowlatency file which you can echo 0 or 1 to to disable or enable low latency patches dynamically in the kernel. This is usually done through /etc/sysctl.conf:

This file is executed by /etc/init.d/procps on startup or can be run manually as root with ‘sysctl -p’. If you build your kernel only with ‘Low latency scheduling’ then low latency will be enabled by default and there will be no way to disable the low latency patches short of recompiling your kernel. If you want to double check if your kernel is patched with the low latency patches, I’m assuming Andrew Morton’s patches, either repatch or check for existence of /include/linux/lowlatency.h.

rajesh/howto/ext3/ext3-5.html Note that you DON’T need to patch your kernel if you have a recent 2.4.x Linux kernel source tree. Ext3 now comes standard, though it’s still labelled “experimental.”

By doing this, you can greatly reduce the chance of filesystem damage, and even avoid needing to fsck on reboot. I find that if the freeze happens while I’m in X, I’m usually unable to get the screen back, but I can do a safe reboot. Note that some of the key combinations seem to work with one Alt key and not the other… but it’s not consistent, I don’t know why. Try both Alt keys.

And make the directory: mkdir /dev/shm
It won’t affect booting an old linux 2.2 kernel — you’ll just get a complaint that the kernel does not support the shm filesystem. While you are editing /etc/fstab you can also mount your /tmp/jack directory in RAM. This solution reduces the audio buffer overruns and therefore greatly improves JACKs performance if you are using a journalling filesystem (as recommended above) but you will loose all data in this dir on shutdown. Other *nix’s use this approach.

There is more information on this in the JACK FAQ .

Next check to see that the compile succeeded. There is nothing more frustrating than removing the files below before you find out that there was a problem you didn’t notice while compiling. Usually compile problems are because of missing module dependencies. Often the output will look normal but you will know for sure there was something missing from the config if you don’t have a System.map. If you do then proceed below, if you don’t then you need to hunt down the missing dep. Sometimes the location of the dependency changes between kernel versions. If you are using a ‘pre’ kernel you may even have to to patch a file by hand.

Читайте также:  Windows показывает одно ядро

If you also want to use your cdwriter, or rip audio from a CD, there’s one more thing to add in lilo.conf before you’ll be able to use the drive:

… replacing X with the drive letter of your IDE cd drive, e.g. my CD drive is /dev/hdc. (I’m not clear on which of those options is actually needed, I think it may have changed at some point. I have both options, which seems to be safe — the invalid one is ignored.) If you already have an “append” line in lilo.conf, just add the text in quotes.

As always, running LILO is VERY important. You won’t be able to boot the new kernel until you do so. This is especially important if you ever remove your old kernel!

(either one should work) Once again, replace N in these commands with the appropriate number. In my case, I have no real SCSI devices, so I choose /dev/sr0. Be sure that your /etc/fstab has an entry for your CDROM device that points to the correct device. The device can either be /dev/cdrom if you’ve updated that symlink, or it can be /dev/srN as described above. Now that you’ve got everything ready, try mounting a data CD to make sure that still works. Also try playing an audio cd. Next, try ripping and/or burning. Useful tools include cdrecord and cdparanoia. More information can be found in the CD-Writing HOWTO, which may be in your installed documentation, or check here: http://www.tldp.org/HOWTO/CD-Writing-HOWTO.html

Update Modutils and Load your Modules

There’s a few things you need to do before you can load modules with 2.4.

See below for the correct version number. Hopefully you won’t have to, but if you do then you need to download the modutils package. Compile and install it now, or use your distribution’s latest available package. Make sure your old modutils is gone!

Alternative Build and Install for Debian Users

The above directions will work just as well as the following, but this method using make-kpkg can save some work for Debian users. Starting after the kernel configuration:

or, if you want to time the kernel build so you’ll know how long it takes if you need to do it again:

The kernel package will take care of configuring and running LILO. It also handles the modules. For more information on the organization of kernel package management in Debian see the dpkg and make-kpkg man pages.

Install ALSA

Now you’re finally ready to get your soundcard working again. I won’t go into detail on this because ALSA installation and configuration is well covered elsewhere. Go to The ALSA howto. I didn’t have to do anything differently with the 2.4 kernel; ALSA just worked fine!

Necessary Upgrades

There are a number of packages you may need to upgrade. These are listed in /usr/src/linux/Documentation/Changes. The listing below is taken from Documentation/Changes for a 2.4.17 kernel.

Additional test commands that take advantage of your distribution packaging system:

Notes from Documentation/Changes: “If you can, upgrade to the latest 2.9.5 binutils release. Older releases such as 2.8, 2.8.xx, and the FSF’s 2.9.1 should be avoided if at all possible. The later releases of 2.9.1.0.x (anything where x >= 22) can and do compile the kernel properly, but there are many benefits to upgrading to 2.9.5 if you’re up to it.” Note: there is a problem with later 2.4.x kernels and recent binutils versions. This bit me with kernel 2.4.16 and binutils 2.11.92.0.12.3. Depending on the kernel configuration building the kernel fails with this error:

There are several workarounds to be found in various mailing list archives. Using binutils version 2.11.92.0.10 instead of 2.11.92.0.12.3 worked for me.

Note that you *can* compile util-linux yourself, but this is potentially dangerous — you MUST carefully read the MCONFIG file and make sure everything’s right. I tried to compile it and didn’t know what I was doing, and I made it impossible to log in to my system!! After some hairy battling with broken boot floppies, I managed to get my system working again. I have since used only prepackaged versions with no trouble.

Installation Notes: If you want to compile modutils, Wait until after you’ve compiled and booted your 2.4 kernel before you try to compile modutils! I was unable to compile modutils until after I’d booted 2.4; then it went fine. This means also that you should NOT compile anything ESSENTIAL to your 2.4 kernel as a module, because you won’t be able to load the modules the first time you boot 2.4.
I had modutils-2.1.121-4 previously, and this version WILL NOT load modules for a 2.4 kernel.

Questions, comments, corrections: Linux audio users.

Источник

Оцените статью